soundcloud.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import re
  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. float_or_none,
  17. int_or_none,
  18. KNOWN_EXTENSIONS,
  19. merge_dicts,
  20. mimetype2ext,
  21. str_or_none,
  22. try_get,
  23. unified_timestamp,
  24. update_url_query,
  25. url_or_none,
  26. )
  27. class SoundcloudIE(InfoExtractor):
  28. """Information extractor for soundcloud.com
  29. To access the media, the uid of the song and a stream token
  30. must be extracted from the page source and the script must make
  31. a request to media.soundcloud.com/crossdomain.xml. Then
  32. the media can be grabbed by requesting from an url composed
  33. of the stream token and uid
  34. """
  35. _VALID_URL = r'''(?x)^(?:https?://)?
  36. (?:(?:(?:www\.|m\.)?soundcloud\.com/
  37. (?!stations/track)
  38. (?P<uploader>[\w\d-]+)/
  39. (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
  40. (?P<title>[\w\d-]+)/?
  41. (?P<token>[^?]+?)?(?:[?].*)?$)
  42. |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
  43. (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
  44. |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
  45. )
  46. '''
  47. IE_NAME = 'soundcloud'
  48. _TESTS = [
  49. {
  50. 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
  51. 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
  52. 'info_dict': {
  53. 'id': '62986583',
  54. 'ext': 'mp3',
  55. 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
  56. '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',
  57. 'uploader': 'E.T. ExTerrestrial Music',
  58. 'timestamp': 1349920598,
  59. 'upload_date': '20121011',
  60. 'duration': 143.216,
  61. 'license': 'all-rights-reserved',
  62. 'view_count': int,
  63. 'like_count': int,
  64. 'comment_count': int,
  65. 'repost_count': int,
  66. }
  67. },
  68. # not streamable song
  69. {
  70. 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
  71. 'info_dict': {
  72. 'id': '47127627',
  73. 'ext': 'mp3',
  74. 'title': 'Goldrushed',
  75. 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
  76. 'uploader': 'The Royal Concept',
  77. 'timestamp': 1337635207,
  78. 'upload_date': '20120521',
  79. 'duration': 30,
  80. 'license': 'all-rights-reserved',
  81. 'view_count': int,
  82. 'like_count': int,
  83. 'comment_count': int,
  84. 'repost_count': int,
  85. },
  86. 'params': {
  87. # rtmp
  88. 'skip_download': True,
  89. },
  90. },
  91. # private link
  92. {
  93. 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
  94. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  95. 'info_dict': {
  96. 'id': '123998367',
  97. 'ext': 'mp3',
  98. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  99. 'description': 'test chars: \"\'/\\ä↭',
  100. 'uploader': 'jaimeMF',
  101. 'timestamp': 1386604920,
  102. 'upload_date': '20131209',
  103. 'duration': 9.927,
  104. 'license': 'all-rights-reserved',
  105. 'view_count': int,
  106. 'like_count': int,
  107. 'comment_count': int,
  108. 'repost_count': int,
  109. },
  110. },
  111. # private link (alt format)
  112. {
  113. 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
  114. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  115. 'info_dict': {
  116. 'id': '123998367',
  117. 'ext': 'mp3',
  118. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  119. 'description': 'test chars: \"\'/\\ä↭',
  120. 'uploader': 'jaimeMF',
  121. 'timestamp': 1386604920,
  122. 'upload_date': '20131209',
  123. 'duration': 9.927,
  124. 'license': 'all-rights-reserved',
  125. 'view_count': int,
  126. 'like_count': int,
  127. 'comment_count': int,
  128. 'repost_count': int,
  129. },
  130. },
  131. # downloadable song
  132. {
  133. 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
  134. 'md5': '7624f2351f8a3b2e7cd51522496e7631',
  135. 'info_dict': {
  136. 'id': '128590877',
  137. 'ext': 'mp3',
  138. 'title': 'Bus Brakes',
  139. 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
  140. 'uploader': 'oddsamples',
  141. 'timestamp': 1389232924,
  142. 'upload_date': '20140109',
  143. 'duration': 17.346,
  144. 'license': 'cc-by-sa',
  145. 'view_count': int,
  146. 'like_count': int,
  147. 'comment_count': int,
  148. 'repost_count': int,
  149. },
  150. },
  151. # private link, downloadable format
  152. {
  153. 'url': 'https://soundcloud.com/oriuplift/uponly-238-no-talking-wav/s-AyZUd',
  154. 'md5': '64a60b16e617d41d0bef032b7f55441e',
  155. 'info_dict': {
  156. 'id': '340344461',
  157. 'ext': 'wav',
  158. 'title': 'Uplifting Only 238 [No Talking] (incl. Alex Feed Guestmix) (Aug 31, 2017) [wav]',
  159. 'description': 'md5:fa20ee0fca76a3d6df8c7e57f3715366',
  160. 'uploader': 'Ori Uplift Music',
  161. 'timestamp': 1504206263,
  162. 'upload_date': '20170831',
  163. 'duration': 7449.096,
  164. 'license': 'all-rights-reserved',
  165. 'view_count': int,
  166. 'like_count': int,
  167. 'comment_count': int,
  168. 'repost_count': int,
  169. },
  170. },
  171. # no album art, use avatar pic for thumbnail
  172. {
  173. 'url': 'https://soundcloud.com/garyvee/sideways-prod-mad-real',
  174. 'md5': '59c7872bc44e5d99b7211891664760c2',
  175. 'info_dict': {
  176. 'id': '309699954',
  177. 'ext': 'mp3',
  178. 'title': 'Sideways (Prod. Mad Real)',
  179. 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
  180. 'uploader': 'garyvee',
  181. 'timestamp': 1488152409,
  182. 'upload_date': '20170226',
  183. 'duration': 207.012,
  184. 'thumbnail': r're:https?://.*\.jpg',
  185. 'license': 'all-rights-reserved',
  186. 'view_count': int,
  187. 'like_count': int,
  188. 'comment_count': int,
  189. 'repost_count': int,
  190. },
  191. 'params': {
  192. 'skip_download': True,
  193. },
  194. },
  195. # not available via api.soundcloud.com/i1/tracks/id/streams
  196. {
  197. 'url': 'https://soundcloud.com/giovannisarani/mezzo-valzer',
  198. 'md5': 'e22aecd2bc88e0e4e432d7dcc0a1abf7',
  199. 'info_dict': {
  200. 'id': '583011102',
  201. 'ext': 'mp3',
  202. 'title': 'Mezzo Valzer',
  203. 'description': 'md5:4138d582f81866a530317bae316e8b61',
  204. 'uploader': 'Giovanni Sarani',
  205. 'timestamp': 1551394171,
  206. 'upload_date': '20190228',
  207. 'duration': 180.157,
  208. 'thumbnail': r're:https?://.*\.jpg',
  209. 'license': 'all-rights-reserved',
  210. 'view_count': int,
  211. 'like_count': int,
  212. 'comment_count': int,
  213. 'repost_count': int,
  214. },
  215. 'expected_warnings': ['Unable to download JSON metadata'],
  216. }
  217. ]
  218. _CLIENT_ID = 'BeGVhOrGmfboy1LtiHTQF6Ejpt9ULJCI'
  219. @staticmethod
  220. def _extract_urls(webpage):
  221. return [m.group('url') for m in re.finditer(
  222. r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
  223. webpage)]
  224. @classmethod
  225. def _resolv_url(cls, url):
  226. return 'https://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  227. def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
  228. track_id = compat_str(info['id'])
  229. title = info['title']
  230. name = full_title or track_id
  231. if quiet:
  232. self.report_extraction(name)
  233. thumbnail = info.get('artwork_url') or info.get('user', {}).get('avatar_url')
  234. if isinstance(thumbnail, compat_str):
  235. thumbnail = thumbnail.replace('-large', '-t500x500')
  236. username = try_get(info, lambda x: x['user']['username'], compat_str)
  237. def extract_count(key):
  238. return int_or_none(info.get('%s_count' % key))
  239. like_count = extract_count('favoritings')
  240. if like_count is None:
  241. like_count = extract_count('likes')
  242. result = {
  243. 'id': track_id,
  244. 'uploader': username,
  245. 'timestamp': unified_timestamp(info.get('created_at')),
  246. 'title': title,
  247. 'description': info.get('description'),
  248. 'thumbnail': thumbnail,
  249. 'duration': float_or_none(info.get('duration'), 1000),
  250. 'webpage_url': info.get('permalink_url'),
  251. 'license': info.get('license'),
  252. 'view_count': extract_count('playback'),
  253. 'like_count': like_count,
  254. 'comment_count': extract_count('comment'),
  255. 'repost_count': extract_count('reposts'),
  256. 'genre': info.get('genre'),
  257. }
  258. format_urls = set()
  259. formats = []
  260. query = {'client_id': self._CLIENT_ID}
  261. if secret_token is not None:
  262. query['secret_token'] = secret_token
  263. if info.get('downloadable', False):
  264. # We can build a direct link to the song
  265. format_url = update_url_query(
  266. 'https://api.soundcloud.com/tracks/%s/download' % track_id, query)
  267. format_urls.add(format_url)
  268. formats.append({
  269. 'format_id': 'download',
  270. 'ext': info.get('original_format', 'mp3'),
  271. 'url': format_url,
  272. 'vcodec': 'none',
  273. 'preference': 10,
  274. })
  275. # Old API, does not work for some tracks (e.g.
  276. # https://soundcloud.com/giovannisarani/mezzo-valzer)
  277. format_dict = self._download_json(
  278. 'https://api.soundcloud.com/i1/tracks/%s/streams' % track_id,
  279. track_id, 'Downloading track url', query=query, fatal=False)
  280. if format_dict:
  281. for key, stream_url in format_dict.items():
  282. if stream_url in format_urls:
  283. continue
  284. format_urls.add(stream_url)
  285. ext, abr = 'mp3', None
  286. mobj = re.search(r'_([^_]+)_(\d+)_url', key)
  287. if mobj:
  288. ext, abr = mobj.groups()
  289. abr = int(abr)
  290. if key.startswith('http'):
  291. stream_formats = [{
  292. 'format_id': key,
  293. 'ext': ext,
  294. 'url': stream_url,
  295. }]
  296. elif key.startswith('rtmp'):
  297. # The url doesn't have an rtmp app, we have to extract the playpath
  298. url, path = stream_url.split('mp3:', 1)
  299. stream_formats = [{
  300. 'format_id': key,
  301. 'url': url,
  302. 'play_path': 'mp3:' + path,
  303. 'ext': 'flv',
  304. }]
  305. elif key.startswith('hls'):
  306. stream_formats = self._extract_m3u8_formats(
  307. stream_url, track_id, ext, entry_protocol='m3u8_native',
  308. m3u8_id=key, fatal=False)
  309. else:
  310. continue
  311. if abr:
  312. for f in stream_formats:
  313. f['abr'] = abr
  314. formats.extend(stream_formats)
  315. # New API
  316. transcodings = try_get(
  317. info, lambda x: x['media']['transcodings'], list) or []
  318. for t in transcodings:
  319. if not isinstance(t, dict):
  320. continue
  321. format_url = url_or_none(t.get('url'))
  322. if not format_url:
  323. continue
  324. stream = self._download_json(
  325. update_url_query(format_url, query), track_id, fatal=False)
  326. if not isinstance(stream, dict):
  327. continue
  328. stream_url = url_or_none(stream.get('url'))
  329. if not stream_url:
  330. continue
  331. if stream_url in format_urls:
  332. continue
  333. format_urls.add(stream_url)
  334. protocol = try_get(t, lambda x: x['format']['protocol'], compat_str)
  335. if protocol != 'hls' and '/hls' in format_url:
  336. protocol = 'hls'
  337. ext = None
  338. preset = str_or_none(t.get('preset'))
  339. if preset:
  340. ext = preset.split('_')[0]
  341. if ext not in KNOWN_EXTENSIONS:
  342. mimetype = try_get(
  343. t, lambda x: x['format']['mime_type'], compat_str)
  344. ext = mimetype2ext(mimetype) or 'mp3'
  345. format_id_list = []
  346. if protocol:
  347. format_id_list.append(protocol)
  348. format_id_list.append(ext)
  349. format_id = '_'.join(format_id_list)
  350. formats.append({
  351. 'url': stream_url,
  352. 'format_id': format_id,
  353. 'ext': ext,
  354. 'protocol': 'm3u8_native' if protocol == 'hls' else 'http',
  355. })
  356. if not formats:
  357. # We fallback to the stream_url in the original info, this
  358. # cannot be always used, sometimes it can give an HTTP 404 error
  359. formats.append({
  360. 'format_id': 'fallback',
  361. 'url': update_url_query(info['stream_url'], query),
  362. 'ext': 'mp3',
  363. })
  364. self._check_formats(formats, track_id)
  365. for f in formats:
  366. f['vcodec'] = 'none'
  367. self._sort_formats(formats)
  368. result['formats'] = formats
  369. return result
  370. def _real_extract(self, url):
  371. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  372. if mobj is None:
  373. raise ExtractorError('Invalid URL: %s' % url)
  374. track_id = mobj.group('track_id')
  375. new_info = {}
  376. if track_id is not None:
  377. info_json_url = 'https://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  378. full_title = track_id
  379. token = mobj.group('secret_token')
  380. if token:
  381. info_json_url += '&secret_token=' + token
  382. elif mobj.group('player'):
  383. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  384. real_url = query['url'][0]
  385. # If the token is in the query of the original url we have to
  386. # manually add it
  387. if 'secret_token' in query:
  388. real_url += '?secret_token=' + query['secret_token'][0]
  389. return self.url_result(real_url)
  390. else:
  391. # extract uploader (which is in the url)
  392. uploader = mobj.group('uploader')
  393. # extract simple title (uploader + slug of song title)
  394. slug_title = mobj.group('title')
  395. token = mobj.group('token')
  396. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  397. if token:
  398. resolve_title += '/%s' % token
  399. webpage = self._download_webpage(url, full_title, fatal=False)
  400. if webpage:
  401. entries = self._parse_json(
  402. self._search_regex(
  403. r'var\s+c\s*=\s*(\[.+?\])\s*,\s*o\s*=Date\b', webpage,
  404. 'data', default='[]'), full_title, fatal=False)
  405. if entries:
  406. for e in entries:
  407. if not isinstance(e, dict):
  408. continue
  409. if e.get('id') != 67:
  410. continue
  411. data = try_get(e, lambda x: x['data'][0], dict)
  412. if data:
  413. new_info = data
  414. break
  415. info_json_url = self._resolv_url(
  416. 'https://soundcloud.com/%s' % resolve_title)
  417. # Contains some additional info missing from new_info
  418. info = self._download_json(
  419. info_json_url, full_title, 'Downloading info JSON')
  420. return self._extract_info_dict(
  421. merge_dicts(info, new_info), full_title, secret_token=token)
  422. class SoundcloudPlaylistBaseIE(SoundcloudIE):
  423. @staticmethod
  424. def _extract_id(e):
  425. return compat_str(e['id']) if e.get('id') else None
  426. def _extract_track_entries(self, tracks):
  427. return [
  428. self.url_result(
  429. track['permalink_url'], SoundcloudIE.ie_key(),
  430. video_id=self._extract_id(track))
  431. for track in tracks if track.get('permalink_url')]
  432. class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
  433. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  434. IE_NAME = 'soundcloud:set'
  435. _TESTS = [{
  436. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  437. 'info_dict': {
  438. 'id': '2284613',
  439. 'title': 'The Royal Concept EP',
  440. },
  441. 'playlist_mincount': 5,
  442. }, {
  443. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
  444. 'only_matching': True,
  445. }]
  446. def _real_extract(self, url):
  447. mobj = re.match(self._VALID_URL, url)
  448. # extract uploader (which is in the url)
  449. uploader = mobj.group('uploader')
  450. # extract simple title (uploader + slug of song title)
  451. slug_title = mobj.group('slug_title')
  452. full_title = '%s/sets/%s' % (uploader, slug_title)
  453. url = 'https://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  454. token = mobj.group('token')
  455. if token:
  456. full_title += '/' + token
  457. url += '/' + token
  458. resolv_url = self._resolv_url(url)
  459. info = self._download_json(resolv_url, full_title)
  460. if 'errors' in info:
  461. msgs = (compat_str(err['error_message']) for err in info['errors'])
  462. raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
  463. entries = self._extract_track_entries(info['tracks'])
  464. return {
  465. '_type': 'playlist',
  466. 'entries': entries,
  467. 'id': '%s' % info['id'],
  468. 'title': info['title'],
  469. }
  470. class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
  471. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  472. def _extract_playlist(self, base_url, playlist_id, playlist_title):
  473. COMMON_QUERY = {
  474. 'limit': 50,
  475. 'client_id': self._CLIENT_ID,
  476. 'linked_partitioning': '1',
  477. }
  478. query = COMMON_QUERY.copy()
  479. query['offset'] = 0
  480. next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
  481. entries = []
  482. for i in itertools.count():
  483. response = self._download_json(
  484. next_href, playlist_id, 'Downloading track page %s' % (i + 1))
  485. collection = response['collection']
  486. if not isinstance(collection, list):
  487. collection = []
  488. # Empty collection may be returned, in this case we proceed
  489. # straight to next_href
  490. def resolve_entry(candidates):
  491. for cand in candidates:
  492. if not isinstance(cand, dict):
  493. continue
  494. permalink_url = url_or_none(cand.get('permalink_url'))
  495. if not permalink_url:
  496. continue
  497. return self.url_result(
  498. permalink_url,
  499. ie=SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
  500. video_id=self._extract_id(cand),
  501. video_title=cand.get('title'))
  502. for e in collection:
  503. entry = resolve_entry((e, e.get('track'), e.get('playlist')))
  504. if entry:
  505. entries.append(entry)
  506. next_href = response.get('next_href')
  507. if not next_href:
  508. break
  509. parsed_next_href = compat_urlparse.urlparse(response['next_href'])
  510. qs = compat_urlparse.parse_qs(parsed_next_href.query)
  511. qs.update(COMMON_QUERY)
  512. next_href = compat_urlparse.urlunparse(
  513. parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
  514. return {
  515. '_type': 'playlist',
  516. 'id': playlist_id,
  517. 'title': playlist_title,
  518. 'entries': entries,
  519. }
  520. class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
  521. _VALID_URL = r'''(?x)
  522. https?://
  523. (?:(?:www|m)\.)?soundcloud\.com/
  524. (?P<user>[^/]+)
  525. (?:/
  526. (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
  527. )?
  528. /?(?:[?#].*)?$
  529. '''
  530. IE_NAME = 'soundcloud:user'
  531. _TESTS = [{
  532. 'url': 'https://soundcloud.com/soft-cell-official',
  533. 'info_dict': {
  534. 'id': '207965082',
  535. 'title': 'Soft Cell (All)',
  536. },
  537. 'playlist_mincount': 28,
  538. }, {
  539. 'url': 'https://soundcloud.com/soft-cell-official/tracks',
  540. 'info_dict': {
  541. 'id': '207965082',
  542. 'title': 'Soft Cell (Tracks)',
  543. },
  544. 'playlist_mincount': 27,
  545. }, {
  546. 'url': 'https://soundcloud.com/soft-cell-official/albums',
  547. 'info_dict': {
  548. 'id': '207965082',
  549. 'title': 'Soft Cell (Albums)',
  550. },
  551. 'playlist_mincount': 1,
  552. }, {
  553. 'url': 'https://soundcloud.com/jcv246/sets',
  554. 'info_dict': {
  555. 'id': '12982173',
  556. 'title': 'Jordi / cv (Playlists)',
  557. },
  558. 'playlist_mincount': 2,
  559. }, {
  560. 'url': 'https://soundcloud.com/jcv246/reposts',
  561. 'info_dict': {
  562. 'id': '12982173',
  563. 'title': 'Jordi / cv (Reposts)',
  564. },
  565. 'playlist_mincount': 6,
  566. }, {
  567. 'url': 'https://soundcloud.com/clalberg/likes',
  568. 'info_dict': {
  569. 'id': '11817582',
  570. 'title': 'clalberg (Likes)',
  571. },
  572. 'playlist_mincount': 5,
  573. }, {
  574. 'url': 'https://soundcloud.com/grynpyret/spotlight',
  575. 'info_dict': {
  576. 'id': '7098329',
  577. 'title': 'Grynpyret (Spotlight)',
  578. },
  579. 'playlist_mincount': 1,
  580. }]
  581. _BASE_URL_MAP = {
  582. 'all': '%s/stream/users/%%s' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  583. 'tracks': '%s/users/%%s/tracks' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  584. 'albums': '%s/users/%%s/albums' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  585. 'sets': '%s/users/%%s/playlists' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  586. 'reposts': '%s/stream/users/%%s/reposts' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  587. 'likes': '%s/users/%%s/likes' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  588. 'spotlight': '%s/users/%%s/spotlight' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  589. }
  590. _TITLE_MAP = {
  591. 'all': 'All',
  592. 'tracks': 'Tracks',
  593. 'albums': 'Albums',
  594. 'sets': 'Playlists',
  595. 'reposts': 'Reposts',
  596. 'likes': 'Likes',
  597. 'spotlight': 'Spotlight',
  598. }
  599. def _real_extract(self, url):
  600. mobj = re.match(self._VALID_URL, url)
  601. uploader = mobj.group('user')
  602. url = 'https://soundcloud.com/%s/' % uploader
  603. resolv_url = self._resolv_url(url)
  604. user = self._download_json(
  605. resolv_url, uploader, 'Downloading user info')
  606. resource = mobj.group('rsrc') or 'all'
  607. return self._extract_playlist(
  608. self._BASE_URL_MAP[resource] % user['id'], compat_str(user['id']),
  609. '%s (%s)' % (user['username'], self._TITLE_MAP[resource]))
  610. class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
  611. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
  612. IE_NAME = 'soundcloud:trackstation'
  613. _TESTS = [{
  614. 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
  615. 'info_dict': {
  616. 'id': '286017854',
  617. 'title': 'Track station: your-text',
  618. },
  619. 'playlist_mincount': 47,
  620. }]
  621. def _real_extract(self, url):
  622. track_name = self._match_id(url)
  623. webpage = self._download_webpage(url, track_name)
  624. track_id = self._search_regex(
  625. r'soundcloud:track-stations:(\d+)', webpage, 'track id')
  626. return self._extract_playlist(
  627. '%s/stations/soundcloud:track-stations:%s/tracks'
  628. % (self._API_V2_BASE, track_id),
  629. track_id, 'Track station: %s' % track_name)
  630. class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
  631. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  632. IE_NAME = 'soundcloud:playlist'
  633. _TESTS = [{
  634. 'url': 'https://api.soundcloud.com/playlists/4110309',
  635. 'info_dict': {
  636. 'id': '4110309',
  637. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  638. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  639. },
  640. 'playlist_count': 6,
  641. }]
  642. def _real_extract(self, url):
  643. mobj = re.match(self._VALID_URL, url)
  644. playlist_id = mobj.group('id')
  645. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  646. data_dict = {
  647. 'client_id': self._CLIENT_ID,
  648. }
  649. token = mobj.group('token')
  650. if token:
  651. data_dict['secret_token'] = token
  652. data = compat_urllib_parse_urlencode(data_dict)
  653. data = self._download_json(
  654. base_url + data, playlist_id, 'Downloading playlist')
  655. entries = self._extract_track_entries(data['tracks'])
  656. return {
  657. '_type': 'playlist',
  658. 'id': playlist_id,
  659. 'title': data.get('title'),
  660. 'description': data.get('description'),
  661. 'entries': entries,
  662. }
  663. class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
  664. IE_NAME = 'soundcloud:search'
  665. IE_DESC = 'Soundcloud search'
  666. _MAX_RESULTS = float('inf')
  667. _TESTS = [{
  668. 'url': 'scsearch15:post-avant jazzcore',
  669. 'info_dict': {
  670. 'title': 'post-avant jazzcore',
  671. },
  672. 'playlist_count': 15,
  673. }]
  674. _SEARCH_KEY = 'scsearch'
  675. _MAX_RESULTS_PER_PAGE = 200
  676. _DEFAULT_RESULTS_PER_PAGE = 50
  677. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  678. def _get_collection(self, endpoint, collection_id, **query):
  679. limit = min(
  680. query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
  681. self._MAX_RESULTS_PER_PAGE)
  682. query['limit'] = limit
  683. query['client_id'] = self._CLIENT_ID
  684. query['linked_partitioning'] = '1'
  685. query['offset'] = 0
  686. data = compat_urllib_parse_urlencode(query)
  687. next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
  688. collected_results = 0
  689. for i in itertools.count(1):
  690. response = self._download_json(
  691. next_url, collection_id, 'Downloading page {0}'.format(i),
  692. 'Unable to download API page')
  693. collection = response.get('collection', [])
  694. if not collection:
  695. break
  696. collection = list(filter(bool, collection))
  697. collected_results += len(collection)
  698. for item in collection:
  699. yield self.url_result(item['uri'], SoundcloudIE.ie_key())
  700. if not collection or collected_results >= limit:
  701. break
  702. next_url = response.get('next_href')
  703. if not next_url:
  704. break
  705. def _get_n_results(self, query, n):
  706. tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
  707. return self.playlist_result(tracks, playlist_title=query)