soundcloud.py 30 KB

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