soundcloud.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. compat_urllib_parse_urlencode,
  13. )
  14. from ..utils import (
  15. ExtractorError,
  16. int_or_none,
  17. unified_strdate,
  18. update_url_query,
  19. url_or_none,
  20. )
  21. class SoundcloudIE(InfoExtractor):
  22. """Information extractor for soundcloud.com
  23. To access the media, the uid of the song and a stream token
  24. must be extracted from the page source and the script must make
  25. a request to media.soundcloud.com/crossdomain.xml. Then
  26. the media can be grabbed by requesting from an url composed
  27. of the stream token and uid
  28. """
  29. _VALID_URL = r'''(?x)^(?:https?://)?
  30. (?:(?:(?:www\.|m\.)?soundcloud\.com/
  31. (?!stations/track)
  32. (?P<uploader>[\w\d-]+)/
  33. (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
  34. (?P<title>[\w\d-]+)/?
  35. (?P<token>[^?]+?)?(?:[?].*)?$)
  36. |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
  37. (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
  38. |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
  39. )
  40. '''
  41. IE_NAME = 'soundcloud'
  42. _TESTS = [
  43. {
  44. 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
  45. 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
  46. 'info_dict': {
  47. 'id': '62986583',
  48. 'ext': 'mp3',
  49. 'upload_date': '20121011',
  50. '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',
  51. 'uploader': 'E.T. ExTerrestrial Music',
  52. 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
  53. 'duration': 143,
  54. 'license': 'all-rights-reserved',
  55. }
  56. },
  57. # not streamable song
  58. {
  59. 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
  60. 'info_dict': {
  61. 'id': '47127627',
  62. 'ext': 'mp3',
  63. 'title': 'Goldrushed',
  64. 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
  65. 'uploader': 'The Royal Concept',
  66. 'upload_date': '20120521',
  67. 'duration': 227,
  68. 'license': 'all-rights-reserved',
  69. },
  70. 'params': {
  71. # rtmp
  72. 'skip_download': True,
  73. },
  74. },
  75. # private link
  76. {
  77. 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
  78. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  79. 'info_dict': {
  80. 'id': '123998367',
  81. 'ext': 'mp3',
  82. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  83. 'uploader': 'jaimeMF',
  84. 'description': 'test chars: \"\'/\\ä↭',
  85. 'upload_date': '20131209',
  86. 'duration': 9,
  87. 'license': 'all-rights-reserved',
  88. },
  89. },
  90. # private link (alt format)
  91. {
  92. 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
  93. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  94. 'info_dict': {
  95. 'id': '123998367',
  96. 'ext': 'mp3',
  97. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  98. 'uploader': 'jaimeMF',
  99. 'description': 'test chars: \"\'/\\ä↭',
  100. 'upload_date': '20131209',
  101. 'duration': 9,
  102. 'license': 'all-rights-reserved',
  103. },
  104. },
  105. # downloadable song
  106. {
  107. 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
  108. 'md5': '7624f2351f8a3b2e7cd51522496e7631',
  109. 'info_dict': {
  110. 'id': '128590877',
  111. 'ext': 'mp3',
  112. 'title': 'Bus Brakes',
  113. 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
  114. 'uploader': 'oddsamples',
  115. 'upload_date': '20140109',
  116. 'duration': 17,
  117. 'license': 'cc-by-sa',
  118. },
  119. },
  120. # private link, downloadable format
  121. {
  122. 'url': 'https://soundcloud.com/oriuplift/uponly-238-no-talking-wav/s-AyZUd',
  123. 'md5': '64a60b16e617d41d0bef032b7f55441e',
  124. 'info_dict': {
  125. 'id': '340344461',
  126. 'ext': 'wav',
  127. 'title': 'Uplifting Only 238 [No Talking] (incl. Alex Feed Guestmix) (Aug 31, 2017) [wav]',
  128. 'description': 'md5:fa20ee0fca76a3d6df8c7e57f3715366',
  129. 'uploader': 'Ori Uplift Music',
  130. 'upload_date': '20170831',
  131. 'duration': 7449,
  132. 'license': 'all-rights-reserved',
  133. },
  134. },
  135. # no album art, use avatar pic for thumbnail
  136. {
  137. 'url': 'https://soundcloud.com/garyvee/sideways-prod-mad-real',
  138. 'md5': '59c7872bc44e5d99b7211891664760c2',
  139. 'info_dict': {
  140. 'id': '309699954',
  141. 'ext': 'mp3',
  142. 'title': 'Sideways (Prod. Mad Real)',
  143. 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
  144. 'uploader': 'garyvee',
  145. 'upload_date': '20170226',
  146. 'duration': 207,
  147. 'thumbnail': r're:https?://.*\.jpg',
  148. 'license': 'all-rights-reserved',
  149. },
  150. 'params': {
  151. 'skip_download': True,
  152. },
  153. },
  154. ]
  155. _CLIENT_ID = 'NmW1FlPaiL94ueEu7oziOWjYEzZzQDcK'
  156. @staticmethod
  157. def _extract_urls(webpage):
  158. return [m.group('url') for m in re.finditer(
  159. r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
  160. webpage)]
  161. def report_resolve(self, video_id):
  162. """Report information extraction."""
  163. self.to_screen('%s: Resolving id' % video_id)
  164. @classmethod
  165. def _resolv_url(cls, url):
  166. return 'https://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  167. def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
  168. track_id = compat_str(info['id'])
  169. name = full_title or track_id
  170. if quiet:
  171. self.report_extraction(name)
  172. thumbnail = info.get('artwork_url') or info.get('user', {}).get('avatar_url')
  173. if isinstance(thumbnail, compat_str):
  174. thumbnail = thumbnail.replace('-large', '-t500x500')
  175. result = {
  176. 'id': track_id,
  177. 'uploader': info.get('user', {}).get('username'),
  178. 'upload_date': unified_strdate(info.get('created_at')),
  179. 'title': info['title'],
  180. 'description': info.get('description'),
  181. 'thumbnail': thumbnail,
  182. 'duration': int_or_none(info.get('duration'), 1000),
  183. 'webpage_url': info.get('permalink_url'),
  184. 'license': info.get('license'),
  185. }
  186. formats = []
  187. query = {'client_id': self._CLIENT_ID}
  188. if secret_token is not None:
  189. query['secret_token'] = secret_token
  190. if info.get('downloadable', False):
  191. # We can build a direct link to the song
  192. format_url = update_url_query(
  193. 'https://api.soundcloud.com/tracks/%s/download' % track_id, query)
  194. formats.append({
  195. 'format_id': 'download',
  196. 'ext': info.get('original_format', 'mp3'),
  197. 'url': format_url,
  198. 'vcodec': 'none',
  199. 'preference': 10,
  200. })
  201. # We have to retrieve the url
  202. format_dict = self._download_json(
  203. 'https://api.soundcloud.com/i1/tracks/%s/streams' % track_id,
  204. track_id, 'Downloading track url', query=query)
  205. for key, stream_url in format_dict.items():
  206. ext, abr = 'mp3', None
  207. mobj = re.search(r'_([^_]+)_(\d+)_url', key)
  208. if mobj:
  209. ext, abr = mobj.groups()
  210. abr = int(abr)
  211. if key.startswith('http'):
  212. stream_formats = [{
  213. 'format_id': key,
  214. 'ext': ext,
  215. 'url': stream_url,
  216. }]
  217. elif key.startswith('rtmp'):
  218. # The url doesn't have an rtmp app, we have to extract the playpath
  219. url, path = stream_url.split('mp3:', 1)
  220. stream_formats = [{
  221. 'format_id': key,
  222. 'url': url,
  223. 'play_path': 'mp3:' + path,
  224. 'ext': 'flv',
  225. }]
  226. elif key.startswith('hls'):
  227. stream_formats = self._extract_m3u8_formats(
  228. stream_url, track_id, ext, entry_protocol='m3u8_native',
  229. m3u8_id=key, fatal=False)
  230. else:
  231. continue
  232. if abr:
  233. for f in stream_formats:
  234. f['abr'] = abr
  235. formats.extend(stream_formats)
  236. if not formats:
  237. # We fallback to the stream_url in the original info, this
  238. # cannot be always used, sometimes it can give an HTTP 404 error
  239. formats.append({
  240. 'format_id': 'fallback',
  241. 'url': update_url_query(info['stream_url'], query),
  242. 'ext': 'mp3',
  243. })
  244. for f in formats:
  245. f['vcodec'] = 'none'
  246. self._check_formats(formats, track_id)
  247. self._sort_formats(formats)
  248. result['formats'] = formats
  249. return result
  250. def _real_extract(self, url):
  251. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  252. if mobj is None:
  253. raise ExtractorError('Invalid URL: %s' % url)
  254. track_id = mobj.group('track_id')
  255. if track_id is not None:
  256. info_json_url = 'https://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  257. full_title = track_id
  258. token = mobj.group('secret_token')
  259. if token:
  260. info_json_url += '&secret_token=' + token
  261. elif mobj.group('player'):
  262. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  263. real_url = query['url'][0]
  264. # If the token is in the query of the original url we have to
  265. # manually add it
  266. if 'secret_token' in query:
  267. real_url += '?secret_token=' + query['secret_token'][0]
  268. return self.url_result(real_url)
  269. else:
  270. # extract uploader (which is in the url)
  271. uploader = mobj.group('uploader')
  272. # extract simple title (uploader + slug of song title)
  273. slug_title = mobj.group('title')
  274. token = mobj.group('token')
  275. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  276. if token:
  277. resolve_title += '/%s' % token
  278. self.report_resolve(full_title)
  279. url = 'https://soundcloud.com/%s' % resolve_title
  280. info_json_url = self._resolv_url(url)
  281. info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
  282. return self._extract_info_dict(info, full_title, secret_token=token)
  283. class SoundcloudPlaylistBaseIE(SoundcloudIE):
  284. @staticmethod
  285. def _extract_id(e):
  286. return compat_str(e['id']) if e.get('id') else None
  287. def _extract_track_entries(self, tracks):
  288. return [
  289. self.url_result(
  290. track['permalink_url'], SoundcloudIE.ie_key(),
  291. video_id=self._extract_id(track))
  292. for track in tracks if track.get('permalink_url')]
  293. class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
  294. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  295. IE_NAME = 'soundcloud:set'
  296. _TESTS = [{
  297. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  298. 'info_dict': {
  299. 'id': '2284613',
  300. 'title': 'The Royal Concept EP',
  301. },
  302. 'playlist_mincount': 5,
  303. }, {
  304. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
  305. 'only_matching': True,
  306. }]
  307. def _real_extract(self, url):
  308. mobj = re.match(self._VALID_URL, url)
  309. # extract uploader (which is in the url)
  310. uploader = mobj.group('uploader')
  311. # extract simple title (uploader + slug of song title)
  312. slug_title = mobj.group('slug_title')
  313. full_title = '%s/sets/%s' % (uploader, slug_title)
  314. url = 'https://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  315. token = mobj.group('token')
  316. if token:
  317. full_title += '/' + token
  318. url += '/' + token
  319. self.report_resolve(full_title)
  320. resolv_url = self._resolv_url(url)
  321. info = self._download_json(resolv_url, full_title)
  322. if 'errors' in info:
  323. msgs = (compat_str(err['error_message']) for err in info['errors'])
  324. raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
  325. entries = self._extract_track_entries(info['tracks'])
  326. return {
  327. '_type': 'playlist',
  328. 'entries': entries,
  329. 'id': '%s' % info['id'],
  330. 'title': info['title'],
  331. }
  332. class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
  333. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  334. def _extract_playlist(self, base_url, playlist_id, playlist_title):
  335. COMMON_QUERY = {
  336. 'limit': 50,
  337. 'client_id': self._CLIENT_ID,
  338. 'linked_partitioning': '1',
  339. }
  340. query = COMMON_QUERY.copy()
  341. query['offset'] = 0
  342. next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
  343. entries = []
  344. for i in itertools.count():
  345. response = self._download_json(
  346. next_href, playlist_id, 'Downloading track page %s' % (i + 1))
  347. collection = response['collection']
  348. if not isinstance(collection, list):
  349. collection = []
  350. # Empty collection may be returned, in this case we proceed
  351. # straight to next_href
  352. def resolve_entry(candidates):
  353. for cand in candidates:
  354. if not isinstance(cand, dict):
  355. continue
  356. permalink_url = url_or_none(cand.get('permalink_url'))
  357. if not permalink_url:
  358. continue
  359. return self.url_result(
  360. permalink_url,
  361. ie=SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
  362. video_id=self._extract_id(cand),
  363. video_title=cand.get('title'))
  364. for e in collection:
  365. entry = resolve_entry((e, e.get('track'), e.get('playlist')))
  366. if entry:
  367. entries.append(entry)
  368. next_href = response.get('next_href')
  369. if not next_href:
  370. break
  371. parsed_next_href = compat_urlparse.urlparse(response['next_href'])
  372. qs = compat_urlparse.parse_qs(parsed_next_href.query)
  373. qs.update(COMMON_QUERY)
  374. next_href = compat_urlparse.urlunparse(
  375. parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
  376. return {
  377. '_type': 'playlist',
  378. 'id': playlist_id,
  379. 'title': playlist_title,
  380. 'entries': entries,
  381. }
  382. class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
  383. _VALID_URL = r'''(?x)
  384. https?://
  385. (?:(?:www|m)\.)?soundcloud\.com/
  386. (?P<user>[^/]+)
  387. (?:/
  388. (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
  389. )?
  390. /?(?:[?#].*)?$
  391. '''
  392. IE_NAME = 'soundcloud:user'
  393. _TESTS = [{
  394. 'url': 'https://soundcloud.com/soft-cell-official',
  395. 'info_dict': {
  396. 'id': '207965082',
  397. 'title': 'Soft Cell (All)',
  398. },
  399. 'playlist_mincount': 28,
  400. }, {
  401. 'url': 'https://soundcloud.com/soft-cell-official/tracks',
  402. 'info_dict': {
  403. 'id': '207965082',
  404. 'title': 'Soft Cell (Tracks)',
  405. },
  406. 'playlist_mincount': 27,
  407. }, {
  408. 'url': 'https://soundcloud.com/soft-cell-official/albums',
  409. 'info_dict': {
  410. 'id': '207965082',
  411. 'title': 'Soft Cell (Albums)',
  412. },
  413. 'playlist_mincount': 1,
  414. }, {
  415. 'url': 'https://soundcloud.com/jcv246/sets',
  416. 'info_dict': {
  417. 'id': '12982173',
  418. 'title': 'Jordi / cv (Playlists)',
  419. },
  420. 'playlist_mincount': 2,
  421. }, {
  422. 'url': 'https://soundcloud.com/jcv246/reposts',
  423. 'info_dict': {
  424. 'id': '12982173',
  425. 'title': 'Jordi / cv (Reposts)',
  426. },
  427. 'playlist_mincount': 6,
  428. }, {
  429. 'url': 'https://soundcloud.com/clalberg/likes',
  430. 'info_dict': {
  431. 'id': '11817582',
  432. 'title': 'clalberg (Likes)',
  433. },
  434. 'playlist_mincount': 5,
  435. }, {
  436. 'url': 'https://soundcloud.com/grynpyret/spotlight',
  437. 'info_dict': {
  438. 'id': '7098329',
  439. 'title': 'Grynpyret (Spotlight)',
  440. },
  441. 'playlist_mincount': 1,
  442. }]
  443. _BASE_URL_MAP = {
  444. 'all': '%s/stream/users/%%s' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  445. 'tracks': '%s/users/%%s/tracks' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  446. 'albums': '%s/users/%%s/albums' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  447. 'sets': '%s/users/%%s/playlists' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  448. 'reposts': '%s/stream/users/%%s/reposts' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  449. 'likes': '%s/users/%%s/likes' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  450. 'spotlight': '%s/users/%%s/spotlight' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  451. }
  452. _TITLE_MAP = {
  453. 'all': 'All',
  454. 'tracks': 'Tracks',
  455. 'albums': 'Albums',
  456. 'sets': 'Playlists',
  457. 'reposts': 'Reposts',
  458. 'likes': 'Likes',
  459. 'spotlight': 'Spotlight',
  460. }
  461. def _real_extract(self, url):
  462. mobj = re.match(self._VALID_URL, url)
  463. uploader = mobj.group('user')
  464. url = 'https://soundcloud.com/%s/' % uploader
  465. resolv_url = self._resolv_url(url)
  466. user = self._download_json(
  467. resolv_url, uploader, 'Downloading user info')
  468. resource = mobj.group('rsrc') or 'all'
  469. return self._extract_playlist(
  470. self._BASE_URL_MAP[resource] % user['id'], compat_str(user['id']),
  471. '%s (%s)' % (user['username'], self._TITLE_MAP[resource]))
  472. class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
  473. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
  474. IE_NAME = 'soundcloud:trackstation'
  475. _TESTS = [{
  476. 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
  477. 'info_dict': {
  478. 'id': '286017854',
  479. 'title': 'Track station: your-text',
  480. },
  481. 'playlist_mincount': 47,
  482. }]
  483. def _real_extract(self, url):
  484. track_name = self._match_id(url)
  485. webpage = self._download_webpage(url, track_name)
  486. track_id = self._search_regex(
  487. r'soundcloud:track-stations:(\d+)', webpage, 'track id')
  488. return self._extract_playlist(
  489. '%s/stations/soundcloud:track-stations:%s/tracks'
  490. % (self._API_V2_BASE, track_id),
  491. track_id, 'Track station: %s' % track_name)
  492. class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
  493. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  494. IE_NAME = 'soundcloud:playlist'
  495. _TESTS = [{
  496. 'url': 'https://api.soundcloud.com/playlists/4110309',
  497. 'info_dict': {
  498. 'id': '4110309',
  499. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  500. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  501. },
  502. 'playlist_count': 6,
  503. }]
  504. def _real_extract(self, url):
  505. mobj = re.match(self._VALID_URL, url)
  506. playlist_id = mobj.group('id')
  507. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  508. data_dict = {
  509. 'client_id': self._CLIENT_ID,
  510. }
  511. token = mobj.group('token')
  512. if token:
  513. data_dict['secret_token'] = token
  514. data = compat_urllib_parse_urlencode(data_dict)
  515. data = self._download_json(
  516. base_url + data, playlist_id, 'Downloading playlist')
  517. entries = self._extract_track_entries(data['tracks'])
  518. return {
  519. '_type': 'playlist',
  520. 'id': playlist_id,
  521. 'title': data.get('title'),
  522. 'description': data.get('description'),
  523. 'entries': entries,
  524. }
  525. class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
  526. IE_NAME = 'soundcloud:search'
  527. IE_DESC = 'Soundcloud search'
  528. _MAX_RESULTS = float('inf')
  529. _TESTS = [{
  530. 'url': 'scsearch15:post-avant jazzcore',
  531. 'info_dict': {
  532. 'title': 'post-avant jazzcore',
  533. },
  534. 'playlist_count': 15,
  535. }]
  536. _SEARCH_KEY = 'scsearch'
  537. _MAX_RESULTS_PER_PAGE = 200
  538. _DEFAULT_RESULTS_PER_PAGE = 50
  539. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  540. def _get_collection(self, endpoint, collection_id, **query):
  541. limit = min(
  542. query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
  543. self._MAX_RESULTS_PER_PAGE)
  544. query['limit'] = limit
  545. query['client_id'] = self._CLIENT_ID
  546. query['linked_partitioning'] = '1'
  547. query['offset'] = 0
  548. data = compat_urllib_parse_urlencode(query)
  549. next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
  550. collected_results = 0
  551. for i in itertools.count(1):
  552. response = self._download_json(
  553. next_url, collection_id, 'Downloading page {0}'.format(i),
  554. 'Unable to download API page')
  555. collection = response.get('collection', [])
  556. if not collection:
  557. break
  558. collection = list(filter(bool, collection))
  559. collected_results += len(collection)
  560. for item in collection:
  561. yield self.url_result(item['uri'], SoundcloudIE.ie_key())
  562. if not collection or collected_results >= limit:
  563. break
  564. next_url = response.get('next_href')
  565. if not next_url:
  566. break
  567. def _get_n_results(self, query, n):
  568. tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
  569. return self.playlist_result(tracks, playlist_title=query)