soundcloud.py 23 KB

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