You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

701 lines
25 KiB

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