soundcloud.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import itertools
  5. from .common import (
  6. InfoExtractor,
  7. SearchInfoExtractor
  8. )
  9. from ..compat import (
  10. compat_str,
  11. compat_urlparse,
  12. compat_urllib_parse_urlencode,
  13. )
  14. from ..utils import (
  15. ExtractorError,
  16. int_or_none,
  17. unified_strdate,
  18. )
  19. class SoundcloudIE(InfoExtractor):
  20. """Information extractor for soundcloud.com
  21. To access the media, the uid of the song and a stream token
  22. must be extracted from the page source and the script must make
  23. a request to media.soundcloud.com/crossdomain.xml. Then
  24. the media can be grabbed by requesting from an url composed
  25. of the stream token and uid
  26. """
  27. _VALID_URL = r'''(?x)^(?:https?://)?
  28. (?:(?:(?:www\.|m\.)?soundcloud\.com/
  29. (?P<uploader>[\w\d-]+)/
  30. (?!(?:tracks|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
  31. (?P<title>[\w\d-]+)/?
  32. (?P<token>[^?]+?)?(?:[?].*)?$)
  33. |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
  34. (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
  35. |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
  36. )
  37. '''
  38. IE_NAME = 'soundcloud'
  39. _TESTS = [
  40. {
  41. 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
  42. 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
  43. 'info_dict': {
  44. 'id': '62986583',
  45. 'ext': 'mp3',
  46. 'upload_date': '20121011',
  47. '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',
  48. 'uploader': 'E.T. ExTerrestrial Music',
  49. 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
  50. 'duration': 143,
  51. 'license': 'all-rights-reserved',
  52. }
  53. },
  54. # not streamable song
  55. {
  56. 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
  57. 'info_dict': {
  58. 'id': '47127627',
  59. 'ext': 'mp3',
  60. 'title': 'Goldrushed',
  61. 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
  62. 'uploader': 'The Royal Concept',
  63. 'upload_date': '20120521',
  64. 'duration': 227,
  65. 'license': 'all-rights-reserved',
  66. },
  67. 'params': {
  68. # rtmp
  69. 'skip_download': True,
  70. },
  71. },
  72. # private link
  73. {
  74. 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
  75. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  76. 'info_dict': {
  77. 'id': '123998367',
  78. 'ext': 'mp3',
  79. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  80. 'uploader': 'jaimeMF',
  81. 'description': 'test chars: \"\'/\\ä↭',
  82. 'upload_date': '20131209',
  83. 'duration': 9,
  84. 'license': 'all-rights-reserved',
  85. },
  86. },
  87. # private link (alt format)
  88. {
  89. 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
  90. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  91. 'info_dict': {
  92. 'id': '123998367',
  93. 'ext': 'mp3',
  94. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  95. 'uploader': 'jaimeMF',
  96. 'description': 'test chars: \"\'/\\ä↭',
  97. 'upload_date': '20131209',
  98. 'duration': 9,
  99. 'license': 'all-rights-reserved',
  100. },
  101. },
  102. # downloadable song
  103. {
  104. 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
  105. 'md5': '7624f2351f8a3b2e7cd51522496e7631',
  106. 'info_dict': {
  107. 'id': '128590877',
  108. 'ext': 'mp3',
  109. 'title': 'Bus Brakes',
  110. 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
  111. 'uploader': 'oddsamples',
  112. 'upload_date': '20140109',
  113. 'duration': 17,
  114. 'license': 'cc-by-sa',
  115. },
  116. },
  117. ]
  118. _CLIENT_ID = '02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea'
  119. _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
  120. @staticmethod
  121. def _extract_urls(webpage):
  122. return [m.group('url') for m in re.finditer(
  123. r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
  124. webpage)]
  125. def report_resolve(self, video_id):
  126. """Report information extraction."""
  127. self.to_screen('%s: Resolving id' % video_id)
  128. @classmethod
  129. def _resolv_url(cls, url):
  130. return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  131. def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
  132. track_id = compat_str(info['id'])
  133. name = full_title or track_id
  134. if quiet:
  135. self.report_extraction(name)
  136. thumbnail = info['artwork_url']
  137. track_license = info['license']
  138. if thumbnail is not None:
  139. thumbnail = thumbnail.replace('-large', '-t500x500')
  140. ext = 'mp3'
  141. result = {
  142. 'id': track_id,
  143. 'uploader': info['user']['username'],
  144. 'upload_date': unified_strdate(info['created_at']),
  145. 'title': info['title'],
  146. 'description': info['description'],
  147. 'thumbnail': thumbnail,
  148. 'duration': int_or_none(info.get('duration'), 1000),
  149. 'webpage_url': info.get('permalink_url'),
  150. 'license': track_license,
  151. }
  152. formats = []
  153. if info.get('downloadable', False):
  154. # We can build a direct link to the song
  155. format_url = (
  156. 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
  157. track_id, self._CLIENT_ID))
  158. formats.append({
  159. 'format_id': 'download',
  160. 'ext': info.get('original_format', 'mp3'),
  161. 'url': format_url,
  162. 'vcodec': 'none',
  163. 'preference': 10,
  164. })
  165. # We have to retrieve the url
  166. streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
  167. 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
  168. format_dict = self._download_json(
  169. streams_url,
  170. track_id, 'Downloading track url')
  171. for key, stream_url in format_dict.items():
  172. if key.startswith('http'):
  173. formats.append({
  174. 'format_id': key,
  175. 'ext': ext,
  176. 'url': stream_url,
  177. 'vcodec': 'none',
  178. })
  179. elif key.startswith('rtmp'):
  180. # The url doesn't have an rtmp app, we have to extract the playpath
  181. url, path = stream_url.split('mp3:', 1)
  182. formats.append({
  183. 'format_id': key,
  184. 'url': url,
  185. 'play_path': 'mp3:' + path,
  186. 'ext': 'flv',
  187. 'vcodec': 'none',
  188. })
  189. if not formats:
  190. # We fallback to the stream_url in the original info, this
  191. # cannot be always used, sometimes it can give an HTTP 404 error
  192. formats.append({
  193. 'format_id': 'fallback',
  194. 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
  195. 'ext': ext,
  196. 'vcodec': 'none',
  197. })
  198. for f in formats:
  199. if f['format_id'].startswith('http'):
  200. f['protocol'] = 'http'
  201. if f['format_id'].startswith('rtmp'):
  202. f['protocol'] = 'rtmp'
  203. self._check_formats(formats, track_id)
  204. self._sort_formats(formats)
  205. result['formats'] = formats
  206. return result
  207. def _real_extract(self, url):
  208. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  209. if mobj is None:
  210. raise ExtractorError('Invalid URL: %s' % url)
  211. track_id = mobj.group('track_id')
  212. token = None
  213. if track_id is not None:
  214. info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  215. full_title = track_id
  216. token = mobj.group('secret_token')
  217. if token:
  218. info_json_url += '&secret_token=' + token
  219. elif mobj.group('player'):
  220. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  221. real_url = query['url'][0]
  222. # If the token is in the query of the original url we have to
  223. # manually add it
  224. if 'secret_token' in query:
  225. real_url += '?secret_token=' + query['secret_token'][0]
  226. return self.url_result(real_url)
  227. else:
  228. # extract uploader (which is in the url)
  229. uploader = mobj.group('uploader')
  230. # extract simple title (uploader + slug of song title)
  231. slug_title = mobj.group('title')
  232. token = mobj.group('token')
  233. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  234. if token:
  235. resolve_title += '/%s' % token
  236. self.report_resolve(full_title)
  237. url = 'http://soundcloud.com/%s' % resolve_title
  238. info_json_url = self._resolv_url(url)
  239. info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
  240. return self._extract_info_dict(info, full_title, secret_token=token)
  241. class SoundcloudSetIE(SoundcloudIE):
  242. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  243. IE_NAME = 'soundcloud:set'
  244. _TESTS = [{
  245. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  246. 'info_dict': {
  247. 'id': '2284613',
  248. 'title': 'The Royal Concept EP',
  249. },
  250. 'playlist_mincount': 6,
  251. }, {
  252. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
  253. 'only_matching': True,
  254. }]
  255. def _real_extract(self, url):
  256. mobj = re.match(self._VALID_URL, url)
  257. # extract uploader (which is in the url)
  258. uploader = mobj.group('uploader')
  259. # extract simple title (uploader + slug of song title)
  260. slug_title = mobj.group('slug_title')
  261. full_title = '%s/sets/%s' % (uploader, slug_title)
  262. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  263. token = mobj.group('token')
  264. if token:
  265. full_title += '/' + token
  266. url += '/' + token
  267. self.report_resolve(full_title)
  268. resolv_url = self._resolv_url(url)
  269. info = self._download_json(resolv_url, full_title)
  270. if 'errors' in info:
  271. msgs = (compat_str(err['error_message']) for err in info['errors'])
  272. raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
  273. entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in info['tracks']]
  274. return {
  275. '_type': 'playlist',
  276. 'entries': entries,
  277. 'id': '%s' % info['id'],
  278. 'title': info['title'],
  279. }
  280. class SoundcloudUserIE(SoundcloudIE):
  281. _VALID_URL = r'''(?x)
  282. https?://
  283. (?:(?:www|m)\.)?soundcloud\.com/
  284. (?P<user>[^/]+)
  285. (?:/
  286. (?P<rsrc>tracks|sets|reposts|likes|spotlight)
  287. )?
  288. /?(?:[?#].*)?$
  289. '''
  290. IE_NAME = 'soundcloud:user'
  291. _TESTS = [{
  292. 'url': 'https://soundcloud.com/the-akashic-chronicler',
  293. 'info_dict': {
  294. 'id': '114582580',
  295. 'title': 'The Akashic Chronicler (All)',
  296. },
  297. 'playlist_mincount': 111,
  298. }, {
  299. 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
  300. 'info_dict': {
  301. 'id': '114582580',
  302. 'title': 'The Akashic Chronicler (Tracks)',
  303. },
  304. 'playlist_mincount': 50,
  305. }, {
  306. 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
  307. 'info_dict': {
  308. 'id': '114582580',
  309. 'title': 'The Akashic Chronicler (Playlists)',
  310. },
  311. 'playlist_mincount': 3,
  312. }, {
  313. 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
  314. 'info_dict': {
  315. 'id': '114582580',
  316. 'title': 'The Akashic Chronicler (Reposts)',
  317. },
  318. 'playlist_mincount': 7,
  319. }, {
  320. 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
  321. 'info_dict': {
  322. 'id': '114582580',
  323. 'title': 'The Akashic Chronicler (Likes)',
  324. },
  325. 'playlist_mincount': 321,
  326. }, {
  327. 'url': 'https://soundcloud.com/grynpyret/spotlight',
  328. 'info_dict': {
  329. 'id': '7098329',
  330. 'title': 'Grynpyret (Spotlight)',
  331. },
  332. 'playlist_mincount': 1,
  333. }]
  334. _API_BASE = 'https://api.soundcloud.com'
  335. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  336. _BASE_URL_MAP = {
  337. 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE,
  338. 'tracks': '%s/users/%%s/tracks' % _API_BASE,
  339. 'sets': '%s/users/%%s/playlists' % _API_V2_BASE,
  340. 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE,
  341. 'likes': '%s/users/%%s/likes' % _API_V2_BASE,
  342. 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE,
  343. }
  344. _TITLE_MAP = {
  345. 'all': 'All',
  346. 'tracks': 'Tracks',
  347. 'sets': 'Playlists',
  348. 'reposts': 'Reposts',
  349. 'likes': 'Likes',
  350. 'spotlight': 'Spotlight',
  351. }
  352. def _real_extract(self, url):
  353. mobj = re.match(self._VALID_URL, url)
  354. uploader = mobj.group('user')
  355. url = 'http://soundcloud.com/%s/' % uploader
  356. resolv_url = self._resolv_url(url)
  357. user = self._download_json(
  358. resolv_url, uploader, 'Downloading user info')
  359. resource = mobj.group('rsrc') or 'all'
  360. base_url = self._BASE_URL_MAP[resource] % user['id']
  361. COMMON_QUERY = {
  362. 'limit': 50,
  363. 'client_id': self._CLIENT_ID,
  364. 'linked_partitioning': '1',
  365. }
  366. query = COMMON_QUERY.copy()
  367. query['offset'] = 0
  368. next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
  369. entries = []
  370. for i in itertools.count():
  371. response = self._download_json(
  372. next_href, uploader, 'Downloading track page %s' % (i + 1))
  373. collection = response['collection']
  374. if not collection:
  375. break
  376. def resolve_permalink_url(candidates):
  377. for cand in candidates:
  378. if isinstance(cand, dict):
  379. permalink_url = cand.get('permalink_url')
  380. if permalink_url and permalink_url.startswith('http'):
  381. return permalink_url
  382. for e in collection:
  383. permalink_url = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
  384. if permalink_url:
  385. entries.append(self.url_result(permalink_url))
  386. next_href = response.get('next_href')
  387. if not next_href:
  388. break
  389. parsed_next_href = compat_urlparse.urlparse(response['next_href'])
  390. qs = compat_urlparse.parse_qs(parsed_next_href.query)
  391. qs.update(COMMON_QUERY)
  392. next_href = compat_urlparse.urlunparse(
  393. parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
  394. return {
  395. '_type': 'playlist',
  396. 'id': compat_str(user['id']),
  397. 'title': '%s (%s)' % (user['username'], self._TITLE_MAP[resource]),
  398. 'entries': entries,
  399. }
  400. class SoundcloudPlaylistIE(SoundcloudIE):
  401. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  402. IE_NAME = 'soundcloud:playlist'
  403. _TESTS = [{
  404. 'url': 'http://api.soundcloud.com/playlists/4110309',
  405. 'info_dict': {
  406. 'id': '4110309',
  407. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  408. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  409. },
  410. 'playlist_count': 6,
  411. }]
  412. def _real_extract(self, url):
  413. mobj = re.match(self._VALID_URL, url)
  414. playlist_id = mobj.group('id')
  415. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  416. data_dict = {
  417. 'client_id': self._CLIENT_ID,
  418. }
  419. token = mobj.group('token')
  420. if token:
  421. data_dict['secret_token'] = token
  422. data = compat_urllib_parse_urlencode(data_dict)
  423. data = self._download_json(
  424. base_url + data, playlist_id, 'Downloading playlist')
  425. entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in data['tracks']]
  426. return {
  427. '_type': 'playlist',
  428. 'id': playlist_id,
  429. 'title': data.get('title'),
  430. 'description': data.get('description'),
  431. 'entries': entries,
  432. }
  433. class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
  434. IE_NAME = 'soundcloud:search'
  435. IE_DESC = 'Soundcloud search'
  436. _MAX_RESULTS = float('inf')
  437. _TESTS = [{
  438. 'url': 'scsearch15:post-avant jazzcore',
  439. 'info_dict': {
  440. 'title': 'post-avant jazzcore',
  441. },
  442. 'playlist_count': 15,
  443. }]
  444. _SEARCH_KEY = 'scsearch'
  445. _MAX_RESULTS_PER_PAGE = 200
  446. _DEFAULT_RESULTS_PER_PAGE = 50
  447. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  448. def _get_collection(self, endpoint, collection_id, **query):
  449. limit = min(
  450. query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
  451. self._MAX_RESULTS_PER_PAGE)
  452. query['limit'] = limit
  453. query['client_id'] = self._CLIENT_ID
  454. query['linked_partitioning'] = '1'
  455. query['offset'] = 0
  456. data = compat_urllib_parse_urlencode(query)
  457. next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
  458. collected_results = 0
  459. for i in itertools.count(1):
  460. response = self._download_json(
  461. next_url, collection_id, 'Downloading page {0}'.format(i),
  462. 'Unable to download API page')
  463. collection = response.get('collection', [])
  464. if not collection:
  465. break
  466. collection = list(filter(bool, collection))
  467. collected_results += len(collection)
  468. for item in collection:
  469. yield self.url_result(item['uri'], SoundcloudIE.ie_key())
  470. if not collection or collected_results >= limit:
  471. break
  472. next_url = response.get('next_href')
  473. if not next_url:
  474. break
  475. def _get_n_results(self, query, n):
  476. tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
  477. return self.playlist_result(tracks, playlist_title=query)