You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

384 lines
14 KiB

10 years ago
10 years ago
  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import itertools
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_str,
  8. compat_urlparse,
  9. compat_urllib_parse,
  10. )
  11. from ..utils import (
  12. ExtractorError,
  13. int_or_none,
  14. unified_strdate,
  15. )
  16. class SoundcloudIE(InfoExtractor):
  17. """Information extractor for soundcloud.com
  18. To access the media, the uid of the song and a stream token
  19. must be extracted from the page source and the script must make
  20. a request to media.soundcloud.com/crossdomain.xml. Then
  21. the media can be grabbed by requesting from an url composed
  22. of the stream token and uid
  23. """
  24. _VALID_URL = r'''(?x)^(?:https?://)?
  25. (?:(?:(?:www\.|m\.)?soundcloud\.com/
  26. (?P<uploader>[\w\d-]+)/
  27. (?!sets/|likes/?(?:$|[?#]))
  28. (?P<title>[\w\d-]+)/?
  29. (?P<token>[^?]+?)?(?:[?].*)?$)
  30. |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
  31. (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
  32. |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
  33. )
  34. '''
  35. IE_NAME = 'soundcloud'
  36. _TESTS = [
  37. {
  38. 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
  39. 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
  40. 'info_dict': {
  41. 'id': '62986583',
  42. 'ext': 'mp3',
  43. 'upload_date': '20121011',
  44. 'description': 'No Downloads untill we record the finished version this weekend, i was too pumped n i had to post it , earl is prolly gonna b hella p.o\'d',
  45. 'uploader': 'E.T. ExTerrestrial Music',
  46. 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
  47. 'duration': 143,
  48. }
  49. },
  50. # not streamable song
  51. {
  52. 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
  53. 'info_dict': {
  54. 'id': '47127627',
  55. 'ext': 'mp3',
  56. 'title': 'Goldrushed',
  57. 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
  58. 'uploader': 'The Royal Concept',
  59. 'upload_date': '20120521',
  60. 'duration': 227,
  61. },
  62. 'params': {
  63. # rtmp
  64. 'skip_download': True,
  65. },
  66. },
  67. # private link
  68. {
  69. 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
  70. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  71. 'info_dict': {
  72. 'id': '123998367',
  73. 'ext': 'mp3',
  74. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  75. 'uploader': 'jaimeMF',
  76. 'description': 'test chars: \"\'/\\ä↭',
  77. 'upload_date': '20131209',
  78. 'duration': 9,
  79. },
  80. },
  81. # private link (alt format)
  82. {
  83. 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
  84. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  85. 'info_dict': {
  86. 'id': '123998367',
  87. 'ext': 'mp3',
  88. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  89. 'uploader': 'jaimeMF',
  90. 'description': 'test chars: \"\'/\\ä↭',
  91. 'upload_date': '20131209',
  92. 'duration': 9,
  93. },
  94. },
  95. # downloadable song
  96. {
  97. 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
  98. 'md5': '7624f2351f8a3b2e7cd51522496e7631',
  99. 'info_dict': {
  100. 'id': '128590877',
  101. 'ext': 'mp3',
  102. 'title': 'Bus Brakes',
  103. 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
  104. 'uploader': 'oddsamples',
  105. 'upload_date': '20140109',
  106. 'duration': 17,
  107. },
  108. },
  109. ]
  110. _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
  111. _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
  112. def report_resolve(self, video_id):
  113. """Report information extraction."""
  114. self.to_screen('%s: Resolving id' % video_id)
  115. @classmethod
  116. def _resolv_url(cls, url):
  117. return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  118. def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
  119. track_id = compat_str(info['id'])
  120. name = full_title or track_id
  121. if quiet:
  122. self.report_extraction(name)
  123. thumbnail = info['artwork_url']
  124. if thumbnail is not None:
  125. thumbnail = thumbnail.replace('-large', '-t500x500')
  126. ext = 'mp3'
  127. result = {
  128. 'id': track_id,
  129. 'uploader': info['user']['username'],
  130. 'upload_date': unified_strdate(info['created_at']),
  131. 'title': info['title'],
  132. 'description': info['description'],
  133. 'thumbnail': thumbnail,
  134. 'duration': int_or_none(info.get('duration'), 1000),
  135. 'webpage_url': info.get('permalink_url'),
  136. }
  137. formats = []
  138. if info.get('downloadable', False):
  139. # We can build a direct link to the song
  140. format_url = (
  141. 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
  142. track_id, self._CLIENT_ID))
  143. formats.append({
  144. 'format_id': 'download',
  145. 'ext': info.get('original_format', 'mp3'),
  146. 'url': format_url,
  147. 'vcodec': 'none',
  148. 'preference': 10,
  149. })
  150. # We have to retrieve the url
  151. streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
  152. 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
  153. format_dict = self._download_json(
  154. streams_url,
  155. track_id, 'Downloading track url')
  156. for key, stream_url in format_dict.items():
  157. if key.startswith('http'):
  158. formats.append({
  159. 'format_id': key,
  160. 'ext': ext,
  161. 'url': stream_url,
  162. 'vcodec': 'none',
  163. })
  164. elif key.startswith('rtmp'):
  165. # The url doesn't have an rtmp app, we have to extract the playpath
  166. url, path = stream_url.split('mp3:', 1)
  167. formats.append({
  168. 'format_id': key,
  169. 'url': url,
  170. 'play_path': 'mp3:' + path,
  171. 'ext': ext,
  172. 'vcodec': 'none',
  173. })
  174. if not formats:
  175. # We fallback to the stream_url in the original info, this
  176. # cannot be always used, sometimes it can give an HTTP 404 error
  177. formats.append({
  178. 'format_id': 'fallback',
  179. 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
  180. 'ext': ext,
  181. 'vcodec': 'none',
  182. })
  183. for f in formats:
  184. if f['format_id'].startswith('http'):
  185. f['protocol'] = 'http'
  186. if f['format_id'].startswith('rtmp'):
  187. f['protocol'] = 'rtmp'
  188. self._sort_formats(formats)
  189. result['formats'] = formats
  190. return result
  191. def _real_extract(self, url):
  192. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  193. if mobj is None:
  194. raise ExtractorError('Invalid URL: %s' % url)
  195. track_id = mobj.group('track_id')
  196. token = None
  197. if track_id is not None:
  198. info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  199. full_title = track_id
  200. token = mobj.group('secret_token')
  201. if token:
  202. info_json_url += "&secret_token=" + token
  203. elif mobj.group('player'):
  204. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  205. return self.url_result(query['url'][0])
  206. else:
  207. # extract uploader (which is in the url)
  208. uploader = mobj.group('uploader')
  209. # extract simple title (uploader + slug of song title)
  210. slug_title = mobj.group('title')
  211. token = mobj.group('token')
  212. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  213. if token:
  214. resolve_title += '/%s' % token
  215. self.report_resolve(full_title)
  216. url = 'http://soundcloud.com/%s' % resolve_title
  217. info_json_url = self._resolv_url(url)
  218. info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
  219. return self._extract_info_dict(info, full_title, secret_token=token)
  220. class SoundcloudSetIE(SoundcloudIE):
  221. _VALID_URL = r'https?://(?:www\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  222. IE_NAME = 'soundcloud:set'
  223. _TESTS = [{
  224. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  225. 'info_dict': {
  226. 'id': '2284613',
  227. 'title': 'The Royal Concept EP',
  228. },
  229. 'playlist_mincount': 6,
  230. }]
  231. def _real_extract(self, url):
  232. mobj = re.match(self._VALID_URL, url)
  233. # extract uploader (which is in the url)
  234. uploader = mobj.group('uploader')
  235. # extract simple title (uploader + slug of song title)
  236. slug_title = mobj.group('slug_title')
  237. full_title = '%s/sets/%s' % (uploader, slug_title)
  238. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  239. token = mobj.group('token')
  240. if token:
  241. full_title += '/' + token
  242. url += '/' + token
  243. self.report_resolve(full_title)
  244. resolv_url = self._resolv_url(url)
  245. info = self._download_json(resolv_url, full_title)
  246. if 'errors' in info:
  247. for err in info['errors']:
  248. self._downloader.report_error('unable to download video webpage: %s' % compat_str(err['error_message']))
  249. return
  250. return {
  251. '_type': 'playlist',
  252. 'entries': [self._extract_info_dict(track, secret_token=token) for track in info['tracks']],
  253. 'id': '%s' % info['id'],
  254. 'title': info['title'],
  255. }
  256. class SoundcloudUserIE(SoundcloudIE):
  257. _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)/?((?P<rsrc>tracks|likes)/?)?(\?.*)?$'
  258. IE_NAME = 'soundcloud:user'
  259. _TESTS = [{
  260. 'url': 'https://soundcloud.com/the-concept-band',
  261. 'info_dict': {
  262. 'id': '9615865',
  263. 'title': 'The Royal Concept',
  264. },
  265. 'playlist_mincount': 12
  266. }, {
  267. 'url': 'https://soundcloud.com/the-concept-band/likes',
  268. 'info_dict': {
  269. 'id': '9615865',
  270. 'title': 'The Royal Concept',
  271. },
  272. 'playlist_mincount': 1,
  273. }]
  274. def _real_extract(self, url):
  275. mobj = re.match(self._VALID_URL, url)
  276. uploader = mobj.group('user')
  277. resource = mobj.group('rsrc')
  278. if resource is None:
  279. resource = 'tracks'
  280. elif resource == 'likes':
  281. resource = 'favorites'
  282. url = 'http://soundcloud.com/%s/' % uploader
  283. resolv_url = self._resolv_url(url)
  284. user = self._download_json(
  285. resolv_url, uploader, 'Downloading user info')
  286. base_url = 'http://api.soundcloud.com/users/%s/%s.json?' % (uploader, resource)
  287. entries = []
  288. for i in itertools.count():
  289. data = compat_urllib_parse.urlencode({
  290. 'offset': i * 50,
  291. 'limit': 50,
  292. 'client_id': self._CLIENT_ID,
  293. })
  294. new_entries = self._download_json(
  295. base_url + data, uploader, 'Downloading track page %s' % (i + 1))
  296. if len(new_entries) == 0:
  297. self.to_screen('%s: End page received' % uploader)
  298. break
  299. entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
  300. return {
  301. '_type': 'playlist',
  302. 'id': compat_str(user['id']),
  303. 'title': user['username'],
  304. 'entries': entries,
  305. }
  306. class SoundcloudPlaylistIE(SoundcloudIE):
  307. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  308. IE_NAME = 'soundcloud:playlist'
  309. _TESTS = [{
  310. 'url': 'http://api.soundcloud.com/playlists/4110309',
  311. 'info_dict': {
  312. 'id': '4110309',
  313. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  314. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  315. },
  316. 'playlist_count': 6,
  317. }]
  318. def _real_extract(self, url):
  319. mobj = re.match(self._VALID_URL, url)
  320. playlist_id = mobj.group('id')
  321. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  322. data_dict = {
  323. 'client_id': self._CLIENT_ID,
  324. }
  325. token = mobj.group('token')
  326. if token:
  327. data_dict['secret_token'] = token
  328. data = compat_urllib_parse.urlencode(data_dict)
  329. data = self._download_json(
  330. base_url + data, playlist_id, 'Downloading playlist')
  331. entries = [
  332. self._extract_info_dict(t, quiet=True, secret_token=token)
  333. for t in data['tracks']]
  334. return {
  335. '_type': 'playlist',
  336. 'id': playlist_id,
  337. 'title': data.get('title'),
  338. 'description': data.get('description'),
  339. 'entries': entries,
  340. }