soundcloud.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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. for k in ('ext', 'abr'):
  333. v = f.get(k)
  334. if v:
  335. format_id_list.append(v)
  336. preview = is_preview or re.search(r'/(?:preview|playlist)/0/30/', f['url'])
  337. if preview:
  338. format_id_list.append('preview')
  339. abr = f.get('abr')
  340. if abr:
  341. f['abr'] = int(abr)
  342. f.update({
  343. 'format_id': '_'.join(format_id_list),
  344. 'protocol': 'm3u8_native' if protocol == 'hls' else 'http',
  345. 'preference': -10 if preview else None,
  346. })
  347. formats.append(f)
  348. # New API
  349. transcodings = try_get(
  350. info, lambda x: x['media']['transcodings'], list) or []
  351. for t in transcodings:
  352. if not isinstance(t, dict):
  353. continue
  354. format_url = url_or_none(t.get('url'))
  355. if not format_url:
  356. continue
  357. stream = self._download_json(
  358. format_url, track_id, query=query, fatal=False)
  359. if not isinstance(stream, dict):
  360. continue
  361. stream_url = url_or_none(stream.get('url'))
  362. if invalid_url(stream_url):
  363. continue
  364. format_urls.add(stream_url)
  365. stream_format = t.get('format') or {}
  366. protocol = stream_format.get('protocol')
  367. if protocol != 'hls' and '/hls' in format_url:
  368. protocol = 'hls'
  369. ext = None
  370. preset = str_or_none(t.get('preset'))
  371. if preset:
  372. ext = preset.split('_')[0]
  373. if ext not in KNOWN_EXTENSIONS:
  374. ext = mimetype2ext(stream_format.get('mime_type'))
  375. add_format({
  376. 'url': stream_url,
  377. 'ext': ext,
  378. }, 'http' if protocol == 'progressive' else protocol,
  379. t.get('snipped') or '/preview/' in format_url)
  380. for f in formats:
  381. f['vcodec'] = 'none'
  382. if not formats and info.get('policy') == 'BLOCK':
  383. self.raise_geo_restricted()
  384. self._sort_formats(formats)
  385. user = info.get('user') or {}
  386. thumbnails = []
  387. artwork_url = info.get('artwork_url')
  388. thumbnail = artwork_url or user.get('avatar_url')
  389. if isinstance(thumbnail, compat_str):
  390. if re.search(self._IMAGE_REPL_RE, thumbnail):
  391. for image_id, size in self._ARTWORK_MAP.items():
  392. i = {
  393. 'id': image_id,
  394. 'url': re.sub(self._IMAGE_REPL_RE, '-%s.jpg' % image_id, thumbnail),
  395. }
  396. if image_id == 'tiny' and not artwork_url:
  397. size = 18
  398. elif image_id == 'original':
  399. i['preference'] = 10
  400. if size:
  401. i.update({
  402. 'width': size,
  403. 'height': size,
  404. })
  405. thumbnails.append(i)
  406. else:
  407. thumbnails = [{'url': thumbnail}]
  408. def extract_count(key):
  409. return int_or_none(info.get('%s_count' % key))
  410. return {
  411. 'id': track_id,
  412. 'uploader': user.get('username'),
  413. 'uploader_id': str_or_none(user.get('id')) or user.get('permalink'),
  414. 'uploader_url': user.get('permalink_url'),
  415. 'timestamp': unified_timestamp(info.get('created_at')),
  416. 'title': title,
  417. 'description': info.get('description'),
  418. 'thumbnails': thumbnails,
  419. 'duration': float_or_none(info.get('duration'), 1000),
  420. 'webpage_url': info.get('permalink_url'),
  421. 'license': info.get('license'),
  422. 'view_count': extract_count('playback'),
  423. 'like_count': extract_count('favoritings') or extract_count('likes'),
  424. 'comment_count': extract_count('comment'),
  425. 'repost_count': extract_count('reposts'),
  426. 'genre': info.get('genre'),
  427. 'formats': formats
  428. }
  429. def _real_extract(self, url):
  430. mobj = re.match(self._VALID_URL, url)
  431. track_id = mobj.group('track_id')
  432. query = {}
  433. if track_id:
  434. info_json_url = self._API_V2_BASE + 'tracks/' + track_id
  435. full_title = track_id
  436. token = mobj.group('secret_token')
  437. if token:
  438. query['secret_token'] = token
  439. else:
  440. full_title = resolve_title = '%s/%s' % mobj.group('uploader', 'title')
  441. token = mobj.group('token')
  442. if token:
  443. resolve_title += '/%s' % token
  444. info_json_url = self._resolv_url(self._BASE_URL + resolve_title)
  445. info = self._download_json(
  446. info_json_url, full_title, 'Downloading info JSON', query=query)
  447. return self._extract_info_dict(info, full_title, token)
  448. class SoundcloudPlaylistBaseIE(SoundcloudIE):
  449. def _extract_set(self, playlist, token=None):
  450. playlist_id = compat_str(playlist['id'])
  451. tracks = playlist.get('tracks') or []
  452. if not all([t.get('permalink_url') for t in tracks]) and token:
  453. tracks = self._download_json(
  454. self._API_V2_BASE + 'tracks', playlist_id,
  455. 'Downloading tracks', query={
  456. 'ids': ','.join([compat_str(t['id']) for t in tracks]),
  457. 'playlistId': playlist_id,
  458. 'playlistSecretToken': token,
  459. })
  460. entries = []
  461. for track in tracks:
  462. track_id = str_or_none(track.get('id'))
  463. url = track.get('permalink_url')
  464. if not url:
  465. if not track_id:
  466. continue
  467. url = self._API_V2_BASE + 'tracks/' + track_id
  468. if token:
  469. url += '?secret_token=' + token
  470. entries.append(self.url_result(
  471. url, SoundcloudIE.ie_key(), track_id))
  472. return self.playlist_result(
  473. entries, playlist_id,
  474. playlist.get('title'),
  475. playlist.get('description'))
  476. class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
  477. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  478. IE_NAME = 'soundcloud:set'
  479. _TESTS = [{
  480. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  481. 'info_dict': {
  482. 'id': '2284613',
  483. 'title': 'The Royal Concept EP',
  484. 'description': 'md5:71d07087c7a449e8941a70a29e34671e',
  485. },
  486. 'playlist_mincount': 5,
  487. }, {
  488. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
  489. 'only_matching': True,
  490. }]
  491. def _real_extract(self, url):
  492. mobj = re.match(self._VALID_URL, url)
  493. full_title = '%s/sets/%s' % mobj.group('uploader', 'slug_title')
  494. token = mobj.group('token')
  495. if token:
  496. full_title += '/' + token
  497. info = self._download_json(self._resolv_url(
  498. self._BASE_URL + full_title), full_title)
  499. if 'errors' in info:
  500. msgs = (compat_str(err['error_message']) for err in info['errors'])
  501. raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
  502. return self._extract_set(info, token)
  503. class SoundcloudPagedPlaylistBaseIE(SoundcloudIE):
  504. def _extract_playlist(self, base_url, playlist_id, playlist_title):
  505. COMMON_QUERY = {
  506. 'limit': 2000000000,
  507. 'linked_partitioning': '1',
  508. }
  509. query = COMMON_QUERY.copy()
  510. query['offset'] = 0
  511. next_href = base_url
  512. entries = []
  513. for i in itertools.count():
  514. response = self._download_json(
  515. next_href, playlist_id,
  516. 'Downloading track page %s' % (i + 1), query=query)
  517. collection = response['collection']
  518. if not isinstance(collection, list):
  519. collection = []
  520. # Empty collection may be returned, in this case we proceed
  521. # straight to next_href
  522. def resolve_entry(candidates):
  523. for cand in candidates:
  524. if not isinstance(cand, dict):
  525. continue
  526. permalink_url = url_or_none(cand.get('permalink_url'))
  527. if not permalink_url:
  528. continue
  529. return self.url_result(
  530. permalink_url,
  531. SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
  532. str_or_none(cand.get('id')), cand.get('title'))
  533. for e in collection:
  534. entry = resolve_entry((e, e.get('track'), e.get('playlist')))
  535. if entry:
  536. entries.append(entry)
  537. next_href = response.get('next_href')
  538. if not next_href:
  539. break
  540. next_href = response['next_href']
  541. parsed_next_href = compat_urlparse.urlparse(next_href)
  542. query = compat_urlparse.parse_qs(parsed_next_href.query)
  543. query.update(COMMON_QUERY)
  544. return {
  545. '_type': 'playlist',
  546. 'id': playlist_id,
  547. 'title': playlist_title,
  548. 'entries': entries,
  549. }
  550. class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
  551. _VALID_URL = r'''(?x)
  552. https?://
  553. (?:(?:www|m)\.)?soundcloud\.com/
  554. (?P<user>[^/]+)
  555. (?:/
  556. (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
  557. )?
  558. /?(?:[?#].*)?$
  559. '''
  560. IE_NAME = 'soundcloud:user'
  561. _TESTS = [{
  562. 'url': 'https://soundcloud.com/soft-cell-official',
  563. 'info_dict': {
  564. 'id': '207965082',
  565. 'title': 'Soft Cell (All)',
  566. },
  567. 'playlist_mincount': 28,
  568. }, {
  569. 'url': 'https://soundcloud.com/soft-cell-official/tracks',
  570. 'info_dict': {
  571. 'id': '207965082',
  572. 'title': 'Soft Cell (Tracks)',
  573. },
  574. 'playlist_mincount': 27,
  575. }, {
  576. 'url': 'https://soundcloud.com/soft-cell-official/albums',
  577. 'info_dict': {
  578. 'id': '207965082',
  579. 'title': 'Soft Cell (Albums)',
  580. },
  581. 'playlist_mincount': 1,
  582. }, {
  583. 'url': 'https://soundcloud.com/jcv246/sets',
  584. 'info_dict': {
  585. 'id': '12982173',
  586. 'title': 'Jordi / cv (Sets)',
  587. },
  588. 'playlist_mincount': 2,
  589. }, {
  590. 'url': 'https://soundcloud.com/jcv246/reposts',
  591. 'info_dict': {
  592. 'id': '12982173',
  593. 'title': 'Jordi / cv (Reposts)',
  594. },
  595. 'playlist_mincount': 6,
  596. }, {
  597. 'url': 'https://soundcloud.com/clalberg/likes',
  598. 'info_dict': {
  599. 'id': '11817582',
  600. 'title': 'clalberg (Likes)',
  601. },
  602. 'playlist_mincount': 5,
  603. }, {
  604. 'url': 'https://soundcloud.com/grynpyret/spotlight',
  605. 'info_dict': {
  606. 'id': '7098329',
  607. 'title': 'Grynpyret (Spotlight)',
  608. },
  609. 'playlist_mincount': 1,
  610. }]
  611. _BASE_URL_MAP = {
  612. 'all': 'stream/users/%s',
  613. 'tracks': 'users/%s/tracks',
  614. 'albums': 'users/%s/albums',
  615. 'sets': 'users/%s/playlists',
  616. 'reposts': 'stream/users/%s/reposts',
  617. 'likes': 'users/%s/likes',
  618. 'spotlight': 'users/%s/spotlight',
  619. }
  620. def _real_extract(self, url):
  621. mobj = re.match(self._VALID_URL, url)
  622. uploader = mobj.group('user')
  623. user = self._download_json(
  624. self._resolv_url(self._BASE_URL + uploader),
  625. uploader, 'Downloading user info')
  626. resource = mobj.group('rsrc') or 'all'
  627. return self._extract_playlist(
  628. self._API_V2_BASE + self._BASE_URL_MAP[resource] % user['id'],
  629. str_or_none(user.get('id')),
  630. '%s (%s)' % (user['username'], resource.capitalize()))
  631. class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
  632. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
  633. IE_NAME = 'soundcloud:trackstation'
  634. _TESTS = [{
  635. 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
  636. 'info_dict': {
  637. 'id': '286017854',
  638. 'title': 'Track station: your text',
  639. },
  640. 'playlist_mincount': 47,
  641. }]
  642. def _real_extract(self, url):
  643. track_name = self._match_id(url)
  644. track = self._download_json(self._resolv_url(url), track_name)
  645. track_id = self._search_regex(
  646. r'soundcloud:track-stations:(\d+)', track['id'], 'track id')
  647. return self._extract_playlist(
  648. self._API_V2_BASE + 'stations/%s/tracks' % track['id'],
  649. track_id, 'Track station: %s' % track['title'])
  650. class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
  651. _VALID_URL = r'https?://api(?:-v2)?\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  652. IE_NAME = 'soundcloud:playlist'
  653. _TESTS = [{
  654. 'url': 'https://api.soundcloud.com/playlists/4110309',
  655. 'info_dict': {
  656. 'id': '4110309',
  657. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  658. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  659. },
  660. 'playlist_count': 6,
  661. }]
  662. def _real_extract(self, url):
  663. mobj = re.match(self._VALID_URL, url)
  664. playlist_id = mobj.group('id')
  665. query = {}
  666. token = mobj.group('token')
  667. if token:
  668. query['secret_token'] = token
  669. data = self._download_json(
  670. self._API_V2_BASE + 'playlists/' + playlist_id,
  671. playlist_id, 'Downloading playlist', query=query)
  672. return self._extract_set(data, token)
  673. class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
  674. IE_NAME = 'soundcloud:search'
  675. IE_DESC = 'Soundcloud search'
  676. _MAX_RESULTS = float('inf')
  677. _TESTS = [{
  678. 'url': 'scsearch15:post-avant jazzcore',
  679. 'info_dict': {
  680. 'title': 'post-avant jazzcore',
  681. },
  682. 'playlist_count': 15,
  683. }]
  684. _SEARCH_KEY = 'scsearch'
  685. _MAX_RESULTS_PER_PAGE = 200
  686. _DEFAULT_RESULTS_PER_PAGE = 50
  687. def _get_collection(self, endpoint, collection_id, **query):
  688. limit = min(
  689. query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
  690. self._MAX_RESULTS_PER_PAGE)
  691. query.update({
  692. 'limit': limit,
  693. 'linked_partitioning': 1,
  694. 'offset': 0,
  695. })
  696. next_url = update_url_query(self._API_V2_BASE + endpoint, query)
  697. collected_results = 0
  698. for i in itertools.count(1):
  699. response = self._download_json(
  700. next_url, collection_id, 'Downloading page {0}'.format(i),
  701. 'Unable to download API page')
  702. collection = response.get('collection', [])
  703. if not collection:
  704. break
  705. collection = list(filter(bool, collection))
  706. collected_results += len(collection)
  707. for item in collection:
  708. yield self.url_result(item['uri'], SoundcloudIE.ie_key())
  709. if not collection or collected_results >= limit:
  710. break
  711. next_url = response.get('next_href')
  712. if not next_url:
  713. break
  714. def _get_n_results(self, query, n):
  715. tracks = self._get_collection('search/tracks', query, limit=n, q=query)
  716. return self.playlist_result(tracks, playlist_title=query)