logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

soundcloud.py (30076B)


  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. # with AAC HQ format available via OAuth token
  243. 'url': 'https://soundcloud.com/wandw/the-chainsmokers-ft-daya-dont-let-me-down-ww-remix-1',
  244. 'only_matching': True,
  245. },
  246. ]
  247. _API_V2_BASE = 'https://api-v2.soundcloud.com/'
  248. _BASE_URL = 'https://soundcloud.com/'
  249. _IMAGE_REPL_RE = r'-([0-9a-z]+)\.jpg'
  250. _ARTWORK_MAP = {
  251. 'mini': 16,
  252. 'tiny': 20,
  253. 'small': 32,
  254. 'badge': 47,
  255. 't67x67': 67,
  256. 'large': 100,
  257. 't300x300': 300,
  258. 'crop': 400,
  259. 't500x500': 500,
  260. 'original': 0,
  261. }
  262. def _store_client_id(self, client_id):
  263. self._downloader.cache.store('soundcloud', 'client_id', client_id)
  264. def _update_client_id(self):
  265. webpage = self._download_webpage('https://soundcloud.com/', None)
  266. for src in reversed(re.findall(r'<script[^>]+src="([^"]+)"', webpage)):
  267. script = self._download_webpage(src, None, fatal=False)
  268. if script:
  269. client_id = self._search_regex(
  270. r'client_id\s*:\s*"([0-9a-zA-Z]{32})"',
  271. script, 'client id', default=None)
  272. if client_id:
  273. self._CLIENT_ID = client_id
  274. self._store_client_id(client_id)
  275. return
  276. raise ExtractorError('Unable to extract client id')
  277. def _download_json(self, *args, **kwargs):
  278. non_fatal = kwargs.get('fatal') is False
  279. if non_fatal:
  280. del kwargs['fatal']
  281. query = kwargs.get('query', {}).copy()
  282. for _ in range(2):
  283. query['client_id'] = self._CLIENT_ID
  284. kwargs['query'] = query
  285. try:
  286. return super(SoundcloudIE, self)._download_json(*args, **compat_kwargs(kwargs))
  287. except ExtractorError as e:
  288. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
  289. self._store_client_id(None)
  290. self._update_client_id()
  291. continue
  292. elif non_fatal:
  293. self._downloader.report_warning(error_to_compat_str(e))
  294. return False
  295. raise
  296. def _real_initialize(self):
  297. self._CLIENT_ID = self._downloader.cache.load('soundcloud', 'client_id') or 'YUKXoArFcqrlQn9tfNHvvyfnDISj04zk'
  298. @classmethod
  299. def _resolv_url(cls, url):
  300. return SoundcloudIE._API_V2_BASE + 'resolve?url=' + url
  301. def _extract_info_dict(self, info, full_title=None, secret_token=None):
  302. track_id = compat_str(info['id'])
  303. title = info['title']
  304. format_urls = set()
  305. formats = []
  306. query = {'client_id': self._CLIENT_ID}
  307. if secret_token:
  308. query['secret_token'] = secret_token
  309. if info.get('downloadable') and info.get('has_downloads_left'):
  310. download_url = update_url_query(
  311. self._API_V2_BASE + 'tracks/' + track_id + '/download', query)
  312. redirect_url = (self._download_json(download_url, track_id, fatal=False) or {}).get('redirectUri')
  313. if redirect_url:
  314. urlh = self._request_webpage(
  315. HEADRequest(redirect_url), track_id, fatal=False)
  316. if urlh:
  317. format_url = urlh.geturl()
  318. format_urls.add(format_url)
  319. formats.append({
  320. 'format_id': 'download',
  321. 'ext': urlhandle_detect_ext(urlh) or 'mp3',
  322. 'filesize': int_or_none(urlh.headers.get('Content-Length')),
  323. 'url': format_url,
  324. 'preference': 10,
  325. })
  326. def invalid_url(url):
  327. return not url or url in format_urls
  328. def add_format(f, protocol, is_preview=False):
  329. mobj = re.search(r'\.(?P<abr>\d+)\.(?P<ext>[0-9a-z]{3,4})(?=[/?])', stream_url)
  330. if mobj:
  331. for k, v in mobj.groupdict().items():
  332. if not f.get(k):
  333. f[k] = v
  334. format_id_list = []
  335. if protocol:
  336. format_id_list.append(protocol)
  337. ext = f.get('ext')
  338. if ext == 'aac':
  339. f['abr'] = '256'
  340. for k in ('ext', 'abr'):
  341. v = f.get(k)
  342. if v:
  343. format_id_list.append(v)
  344. preview = is_preview or re.search(r'/(?:preview|playlist)/0/30/', f['url'])
  345. if preview:
  346. format_id_list.append('preview')
  347. abr = f.get('abr')
  348. if abr:
  349. f['abr'] = int(abr)
  350. if protocol == 'hls':
  351. protocol = 'm3u8' if ext == 'aac' else 'm3u8_native'
  352. else:
  353. protocol = 'http'
  354. f.update({
  355. 'format_id': '_'.join(format_id_list),
  356. 'protocol': protocol,
  357. 'preference': -10 if preview else None,
  358. })
  359. formats.append(f)
  360. # New API
  361. transcodings = try_get(
  362. info, lambda x: x['media']['transcodings'], list) or []
  363. for t in transcodings:
  364. if not isinstance(t, dict):
  365. continue
  366. format_url = url_or_none(t.get('url'))
  367. if not format_url:
  368. continue
  369. stream = self._download_json(
  370. format_url, track_id, query=query, fatal=False)
  371. if not isinstance(stream, dict):
  372. continue
  373. stream_url = url_or_none(stream.get('url'))
  374. if invalid_url(stream_url):
  375. continue
  376. format_urls.add(stream_url)
  377. stream_format = t.get('format') or {}
  378. protocol = stream_format.get('protocol')
  379. if protocol != 'hls' and '/hls' in format_url:
  380. protocol = 'hls'
  381. ext = None
  382. preset = str_or_none(t.get('preset'))
  383. if preset:
  384. ext = preset.split('_')[0]
  385. if ext not in KNOWN_EXTENSIONS:
  386. ext = mimetype2ext(stream_format.get('mime_type'))
  387. add_format({
  388. 'url': stream_url,
  389. 'ext': ext,
  390. }, 'http' if protocol == 'progressive' else protocol,
  391. t.get('snipped') or '/preview/' in format_url)
  392. for f in formats:
  393. f['vcodec'] = 'none'
  394. if not formats and info.get('policy') == 'BLOCK':
  395. self.raise_geo_restricted()
  396. self._sort_formats(formats)
  397. user = info.get('user') or {}
  398. thumbnails = []
  399. artwork_url = info.get('artwork_url')
  400. thumbnail = artwork_url or user.get('avatar_url')
  401. if isinstance(thumbnail, compat_str):
  402. if re.search(self._IMAGE_REPL_RE, thumbnail):
  403. for image_id, size in self._ARTWORK_MAP.items():
  404. i = {
  405. 'id': image_id,
  406. 'url': re.sub(self._IMAGE_REPL_RE, '-%s.jpg' % image_id, thumbnail),
  407. }
  408. if image_id == 'tiny' and not artwork_url:
  409. size = 18
  410. elif image_id == 'original':
  411. i['preference'] = 10
  412. if size:
  413. i.update({
  414. 'width': size,
  415. 'height': size,
  416. })
  417. thumbnails.append(i)
  418. else:
  419. thumbnails = [{'url': thumbnail}]
  420. def extract_count(key):
  421. return int_or_none(info.get('%s_count' % key))
  422. return {
  423. 'id': track_id,
  424. 'uploader': user.get('username'),
  425. 'uploader_id': str_or_none(user.get('id')) or user.get('permalink'),
  426. 'uploader_url': user.get('permalink_url'),
  427. 'timestamp': unified_timestamp(info.get('created_at')),
  428. 'title': title,
  429. 'description': info.get('description'),
  430. 'thumbnails': thumbnails,
  431. 'duration': float_or_none(info.get('duration'), 1000),
  432. 'webpage_url': info.get('permalink_url'),
  433. 'license': info.get('license'),
  434. 'view_count': extract_count('playback'),
  435. 'like_count': extract_count('favoritings') or extract_count('likes'),
  436. 'comment_count': extract_count('comment'),
  437. 'repost_count': extract_count('reposts'),
  438. 'genre': info.get('genre'),
  439. 'formats': formats
  440. }
  441. def _real_extract(self, url):
  442. mobj = re.match(self._VALID_URL, url)
  443. track_id = mobj.group('track_id')
  444. query = {}
  445. if track_id:
  446. info_json_url = self._API_V2_BASE + 'tracks/' + track_id
  447. full_title = track_id
  448. token = mobj.group('secret_token')
  449. if token:
  450. query['secret_token'] = token
  451. else:
  452. full_title = resolve_title = '%s/%s' % mobj.group('uploader', 'title')
  453. token = mobj.group('token')
  454. if token:
  455. resolve_title += '/%s' % token
  456. info_json_url = self._resolv_url(self._BASE_URL + resolve_title)
  457. info = self._download_json(
  458. info_json_url, full_title, 'Downloading info JSON', query=query)
  459. return self._extract_info_dict(info, full_title, token)
  460. class SoundcloudPlaylistBaseIE(SoundcloudIE):
  461. def _extract_set(self, playlist, token=None):
  462. playlist_id = compat_str(playlist['id'])
  463. tracks = playlist.get('tracks') or []
  464. if not all([t.get('permalink_url') for t in tracks]) and token:
  465. tracks = self._download_json(
  466. self._API_V2_BASE + 'tracks', playlist_id,
  467. 'Downloading tracks', query={
  468. 'ids': ','.join([compat_str(t['id']) for t in tracks]),
  469. 'playlistId': playlist_id,
  470. 'playlistSecretToken': token,
  471. })
  472. entries = []
  473. for track in tracks:
  474. track_id = str_or_none(track.get('id'))
  475. url = track.get('permalink_url')
  476. if not url:
  477. if not track_id:
  478. continue
  479. url = self._API_V2_BASE + 'tracks/' + track_id
  480. if token:
  481. url += '?secret_token=' + token
  482. entries.append(self.url_result(
  483. url, SoundcloudIE.ie_key(), track_id))
  484. return self.playlist_result(
  485. entries, playlist_id,
  486. playlist.get('title'),
  487. playlist.get('description'))
  488. class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
  489. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  490. IE_NAME = 'soundcloud:set'
  491. _TESTS = [{
  492. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  493. 'info_dict': {
  494. 'id': '2284613',
  495. 'title': 'The Royal Concept EP',
  496. 'description': 'md5:71d07087c7a449e8941a70a29e34671e',
  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. return self._extract_set(info, token)
  515. class SoundcloudPagedPlaylistBaseIE(SoundcloudIE):
  516. def _extract_playlist(self, base_url, playlist_id, playlist_title):
  517. # Per the SoundCloud documentation, the maximum limit for a linked partitioning query is 200.
  518. # https://developers.soundcloud.com/blog/offset-pagination-deprecated
  519. COMMON_QUERY = {
  520. 'limit': 200,
  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. return self._extract_set(data, token)
  687. class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
  688. IE_NAME = 'soundcloud:search'
  689. IE_DESC = 'Soundcloud search'
  690. _MAX_RESULTS = float('inf')
  691. _TESTS = [{
  692. 'url': 'scsearch15:post-avant jazzcore',
  693. 'info_dict': {
  694. 'title': 'post-avant jazzcore',
  695. },
  696. 'playlist_count': 15,
  697. }]
  698. _SEARCH_KEY = 'scsearch'
  699. _MAX_RESULTS_PER_PAGE = 200
  700. _DEFAULT_RESULTS_PER_PAGE = 50
  701. def _get_collection(self, endpoint, collection_id, **query):
  702. limit = min(
  703. query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
  704. self._MAX_RESULTS_PER_PAGE)
  705. query.update({
  706. 'limit': limit,
  707. 'linked_partitioning': 1,
  708. 'offset': 0,
  709. })
  710. next_url = update_url_query(self._API_V2_BASE + endpoint, query)
  711. collected_results = 0
  712. for i in itertools.count(1):
  713. response = self._download_json(
  714. next_url, collection_id, 'Downloading page {0}'.format(i),
  715. 'Unable to download API page')
  716. collection = response.get('collection', [])
  717. if not collection:
  718. break
  719. collection = list(filter(bool, collection))
  720. collected_results += len(collection)
  721. for item in collection:
  722. yield self.url_result(item['uri'], SoundcloudIE.ie_key())
  723. if not collection or collected_results >= limit:
  724. break
  725. next_url = response.get('next_href')
  726. if not next_url:
  727. break
  728. def _get_n_results(self, query, n):
  729. tracks = self._get_collection('search/tracks', query, limit=n, q=query)
  730. return self.playlist_result(tracks, playlist_title=query)