soundcloud.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. # coding: 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 = 'fDoItMDbsbZz8dY16ZzARCZmzgHBPotA'
  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.get('artwork_url')
  137. if isinstance(thumbnail, compat_str):
  138. thumbnail = thumbnail.replace('-large', '-t500x500')
  139. ext = 'mp3'
  140. result = {
  141. 'id': track_id,
  142. 'uploader': info.get('user', {}).get('username'),
  143. 'upload_date': unified_strdate(info.get('created_at')),
  144. 'title': info['title'],
  145. 'description': info.get('description'),
  146. 'thumbnail': thumbnail,
  147. 'duration': int_or_none(info.get('duration'), 1000),
  148. 'webpage_url': info.get('permalink_url'),
  149. 'license': info.get('license'),
  150. }
  151. formats = []
  152. if info.get('downloadable', False):
  153. # We can build a direct link to the song
  154. format_url = (
  155. 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
  156. track_id, self._CLIENT_ID))
  157. formats.append({
  158. 'format_id': 'download',
  159. 'ext': info.get('original_format', 'mp3'),
  160. 'url': format_url,
  161. 'vcodec': 'none',
  162. 'preference': 10,
  163. })
  164. # We have to retrieve the url
  165. format_dict = self._download_json(
  166. 'http://api.soundcloud.com/i1/tracks/%s/streams' % track_id,
  167. track_id, 'Downloading track url', query={
  168. 'client_id': self._CLIENT_ID,
  169. 'secret_token': secret_token,
  170. })
  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. elif key.startswith('hls'):
  190. m3u8_formats = self._extract_m3u8_formats(
  191. stream_url, track_id, 'mp3', entry_protocol='m3u8_native',
  192. m3u8_id=key, fatal=False)
  193. for f in m3u8_formats:
  194. f['vcodec'] = 'none'
  195. formats.extend(m3u8_formats)
  196. if not formats:
  197. # We fallback to the stream_url in the original info, this
  198. # cannot be always used, sometimes it can give an HTTP 404 error
  199. formats.append({
  200. 'format_id': 'fallback',
  201. 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
  202. 'ext': ext,
  203. 'vcodec': 'none',
  204. })
  205. for f in formats:
  206. if f['format_id'].startswith('http'):
  207. f['protocol'] = 'http'
  208. if f['format_id'].startswith('rtmp'):
  209. f['protocol'] = 'rtmp'
  210. self._check_formats(formats, track_id)
  211. self._sort_formats(formats)
  212. result['formats'] = formats
  213. return result
  214. def _real_extract(self, url):
  215. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  216. if mobj is None:
  217. raise ExtractorError('Invalid URL: %s' % url)
  218. track_id = mobj.group('track_id')
  219. if track_id is not None:
  220. info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  221. full_title = track_id
  222. token = mobj.group('secret_token')
  223. if token:
  224. info_json_url += '&secret_token=' + token
  225. elif mobj.group('player'):
  226. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  227. real_url = query['url'][0]
  228. # If the token is in the query of the original url we have to
  229. # manually add it
  230. if 'secret_token' in query:
  231. real_url += '?secret_token=' + query['secret_token'][0]
  232. return self.url_result(real_url)
  233. else:
  234. # extract uploader (which is in the url)
  235. uploader = mobj.group('uploader')
  236. # extract simple title (uploader + slug of song title)
  237. slug_title = mobj.group('title')
  238. token = mobj.group('token')
  239. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  240. if token:
  241. resolve_title += '/%s' % token
  242. self.report_resolve(full_title)
  243. url = 'http://soundcloud.com/%s' % resolve_title
  244. info_json_url = self._resolv_url(url)
  245. info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
  246. return self._extract_info_dict(info, full_title, secret_token=token)
  247. class SoundcloudPlaylistBaseIE(SoundcloudIE):
  248. @staticmethod
  249. def _extract_id(e):
  250. return compat_str(e['id']) if e.get('id') else None
  251. def _extract_track_entries(self, tracks):
  252. return [
  253. self.url_result(
  254. track['permalink_url'], SoundcloudIE.ie_key(),
  255. video_id=self._extract_id(track))
  256. for track in tracks if track.get('permalink_url')]
  257. class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
  258. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  259. IE_NAME = 'soundcloud:set'
  260. _TESTS = [{
  261. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  262. 'info_dict': {
  263. 'id': '2284613',
  264. 'title': 'The Royal Concept EP',
  265. },
  266. 'playlist_mincount': 6,
  267. }, {
  268. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
  269. 'only_matching': True,
  270. }]
  271. def _real_extract(self, url):
  272. mobj = re.match(self._VALID_URL, url)
  273. # extract uploader (which is in the url)
  274. uploader = mobj.group('uploader')
  275. # extract simple title (uploader + slug of song title)
  276. slug_title = mobj.group('slug_title')
  277. full_title = '%s/sets/%s' % (uploader, slug_title)
  278. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  279. token = mobj.group('token')
  280. if token:
  281. full_title += '/' + token
  282. url += '/' + token
  283. self.report_resolve(full_title)
  284. resolv_url = self._resolv_url(url)
  285. info = self._download_json(resolv_url, full_title)
  286. if 'errors' in info:
  287. msgs = (compat_str(err['error_message']) for err in info['errors'])
  288. raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
  289. entries = self._extract_track_entries(info['tracks'])
  290. return {
  291. '_type': 'playlist',
  292. 'entries': entries,
  293. 'id': '%s' % info['id'],
  294. 'title': info['title'],
  295. }
  296. class SoundcloudUserIE(SoundcloudPlaylistBaseIE):
  297. _VALID_URL = r'''(?x)
  298. https?://
  299. (?:(?:www|m)\.)?soundcloud\.com/
  300. (?P<user>[^/]+)
  301. (?:/
  302. (?P<rsrc>tracks|sets|reposts|likes|spotlight)
  303. )?
  304. /?(?:[?#].*)?$
  305. '''
  306. IE_NAME = 'soundcloud:user'
  307. _TESTS = [{
  308. 'url': 'https://soundcloud.com/the-akashic-chronicler',
  309. 'info_dict': {
  310. 'id': '114582580',
  311. 'title': 'The Akashic Chronicler (All)',
  312. },
  313. 'playlist_mincount': 74,
  314. }, {
  315. 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
  316. 'info_dict': {
  317. 'id': '114582580',
  318. 'title': 'The Akashic Chronicler (Tracks)',
  319. },
  320. 'playlist_mincount': 37,
  321. }, {
  322. 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
  323. 'info_dict': {
  324. 'id': '114582580',
  325. 'title': 'The Akashic Chronicler (Playlists)',
  326. },
  327. 'playlist_mincount': 2,
  328. }, {
  329. 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
  330. 'info_dict': {
  331. 'id': '114582580',
  332. 'title': 'The Akashic Chronicler (Reposts)',
  333. },
  334. 'playlist_mincount': 7,
  335. }, {
  336. 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
  337. 'info_dict': {
  338. 'id': '114582580',
  339. 'title': 'The Akashic Chronicler (Likes)',
  340. },
  341. 'playlist_mincount': 321,
  342. }, {
  343. 'url': 'https://soundcloud.com/grynpyret/spotlight',
  344. 'info_dict': {
  345. 'id': '7098329',
  346. 'title': 'GRYNPYRET (Spotlight)',
  347. },
  348. 'playlist_mincount': 1,
  349. }]
  350. _API_BASE = 'https://api.soundcloud.com'
  351. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  352. _BASE_URL_MAP = {
  353. 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE,
  354. 'tracks': '%s/users/%%s/tracks' % _API_BASE,
  355. 'sets': '%s/users/%%s/playlists' % _API_V2_BASE,
  356. 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE,
  357. 'likes': '%s/users/%%s/likes' % _API_V2_BASE,
  358. 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE,
  359. }
  360. _TITLE_MAP = {
  361. 'all': 'All',
  362. 'tracks': 'Tracks',
  363. 'sets': 'Playlists',
  364. 'reposts': 'Reposts',
  365. 'likes': 'Likes',
  366. 'spotlight': 'Spotlight',
  367. }
  368. def _real_extract(self, url):
  369. mobj = re.match(self._VALID_URL, url)
  370. uploader = mobj.group('user')
  371. url = 'http://soundcloud.com/%s/' % uploader
  372. resolv_url = self._resolv_url(url)
  373. user = self._download_json(
  374. resolv_url, uploader, 'Downloading user info')
  375. resource = mobj.group('rsrc') or 'all'
  376. base_url = self._BASE_URL_MAP[resource] % user['id']
  377. COMMON_QUERY = {
  378. 'limit': 50,
  379. 'client_id': self._CLIENT_ID,
  380. 'linked_partitioning': '1',
  381. }
  382. query = COMMON_QUERY.copy()
  383. query['offset'] = 0
  384. next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
  385. entries = []
  386. for i in itertools.count():
  387. response = self._download_json(
  388. next_href, uploader, 'Downloading track page %s' % (i + 1))
  389. collection = response['collection']
  390. if not collection:
  391. break
  392. def resolve_permalink_url(candidates):
  393. for cand in candidates:
  394. if isinstance(cand, dict):
  395. permalink_url = cand.get('permalink_url')
  396. entry_id = self._extract_id(cand)
  397. if permalink_url and permalink_url.startswith('http'):
  398. return permalink_url, entry_id
  399. for e in collection:
  400. permalink_url, entry_id = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
  401. if permalink_url:
  402. entries.append(self.url_result(permalink_url, video_id=entry_id))
  403. next_href = response.get('next_href')
  404. if not next_href:
  405. break
  406. parsed_next_href = compat_urlparse.urlparse(response['next_href'])
  407. qs = compat_urlparse.parse_qs(parsed_next_href.query)
  408. qs.update(COMMON_QUERY)
  409. next_href = compat_urlparse.urlunparse(
  410. parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
  411. return {
  412. '_type': 'playlist',
  413. 'id': compat_str(user['id']),
  414. 'title': '%s (%s)' % (user['username'], self._TITLE_MAP[resource]),
  415. 'entries': entries,
  416. }
  417. class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
  418. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  419. IE_NAME = 'soundcloud:playlist'
  420. _TESTS = [{
  421. 'url': 'http://api.soundcloud.com/playlists/4110309',
  422. 'info_dict': {
  423. 'id': '4110309',
  424. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  425. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  426. },
  427. 'playlist_count': 6,
  428. }]
  429. def _real_extract(self, url):
  430. mobj = re.match(self._VALID_URL, url)
  431. playlist_id = mobj.group('id')
  432. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  433. data_dict = {
  434. 'client_id': self._CLIENT_ID,
  435. }
  436. token = mobj.group('token')
  437. if token:
  438. data_dict['secret_token'] = token
  439. data = compat_urllib_parse_urlencode(data_dict)
  440. data = self._download_json(
  441. base_url + data, playlist_id, 'Downloading playlist')
  442. entries = self._extract_track_entries(data['tracks'])
  443. return {
  444. '_type': 'playlist',
  445. 'id': playlist_id,
  446. 'title': data.get('title'),
  447. 'description': data.get('description'),
  448. 'entries': entries,
  449. }
  450. class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
  451. IE_NAME = 'soundcloud:search'
  452. IE_DESC = 'Soundcloud search'
  453. _MAX_RESULTS = float('inf')
  454. _TESTS = [{
  455. 'url': 'scsearch15:post-avant jazzcore',
  456. 'info_dict': {
  457. 'title': 'post-avant jazzcore',
  458. },
  459. 'playlist_count': 15,
  460. }]
  461. _SEARCH_KEY = 'scsearch'
  462. _MAX_RESULTS_PER_PAGE = 200
  463. _DEFAULT_RESULTS_PER_PAGE = 50
  464. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  465. def _get_collection(self, endpoint, collection_id, **query):
  466. limit = min(
  467. query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
  468. self._MAX_RESULTS_PER_PAGE)
  469. query['limit'] = limit
  470. query['client_id'] = self._CLIENT_ID
  471. query['linked_partitioning'] = '1'
  472. query['offset'] = 0
  473. data = compat_urllib_parse_urlencode(query)
  474. next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
  475. collected_results = 0
  476. for i in itertools.count(1):
  477. response = self._download_json(
  478. next_url, collection_id, 'Downloading page {0}'.format(i),
  479. 'Unable to download API page')
  480. collection = response.get('collection', [])
  481. if not collection:
  482. break
  483. collection = list(filter(bool, collection))
  484. collected_results += len(collection)
  485. for item in collection:
  486. yield self.url_result(item['uri'], SoundcloudIE.ie_key())
  487. if not collection or collected_results >= limit:
  488. break
  489. next_url = response.get('next_href')
  490. if not next_url:
  491. break
  492. def _get_n_results(self, query, n):
  493. tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
  494. return self.playlist_result(tracks, playlist_title=query)