soundcloud.py 29 KB

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