soundcloud.py 30 KB

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