soundcloud.py 28 KB

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