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.

615 lines
22 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. 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|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. ]
  135. _CLIENT_ID = 'c6CU49JDMapyrQo06UxU9xouB9ZVzqCn'
  136. _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
  137. @staticmethod
  138. def _extract_urls(webpage):
  139. return [m.group('url') for m in re.finditer(
  140. r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
  141. webpage)]
  142. def report_resolve(self, video_id):
  143. """Report information extraction."""
  144. self.to_screen('%s: Resolving id' % video_id)
  145. @classmethod
  146. def _resolv_url(cls, url):
  147. return 'https://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  148. def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
  149. track_id = compat_str(info['id'])
  150. name = full_title or track_id
  151. if quiet:
  152. self.report_extraction(name)
  153. thumbnail = info.get('artwork_url')
  154. if isinstance(thumbnail, compat_str):
  155. thumbnail = thumbnail.replace('-large', '-t500x500')
  156. ext = 'mp3'
  157. result = {
  158. 'id': track_id,
  159. 'uploader': info.get('user', {}).get('username'),
  160. 'upload_date': unified_strdate(info.get('created_at')),
  161. 'title': info['title'],
  162. 'description': info.get('description'),
  163. 'thumbnail': thumbnail,
  164. 'duration': int_or_none(info.get('duration'), 1000),
  165. 'webpage_url': info.get('permalink_url'),
  166. 'license': info.get('license'),
  167. }
  168. formats = []
  169. query = {'client_id': self._CLIENT_ID}
  170. if secret_token is not None:
  171. query['secret_token'] = secret_token
  172. if info.get('downloadable', False):
  173. # We can build a direct link to the song
  174. format_url = update_url_query(
  175. 'https://api.soundcloud.com/tracks/%s/download' % track_id, query)
  176. formats.append({
  177. 'format_id': 'download',
  178. 'ext': info.get('original_format', 'mp3'),
  179. 'url': format_url,
  180. 'vcodec': 'none',
  181. 'preference': 10,
  182. })
  183. # We have to retrieve the url
  184. format_dict = self._download_json(
  185. 'https://api.soundcloud.com/i1/tracks/%s/streams' % track_id,
  186. track_id, 'Downloading track url', query=query)
  187. for key, stream_url in format_dict.items():
  188. abr = int_or_none(self._search_regex(
  189. r'_(\d+)_url', key, 'audio bitrate', default=None))
  190. if key.startswith('http'):
  191. stream_formats = [{
  192. 'format_id': key,
  193. 'ext': ext,
  194. 'url': stream_url,
  195. }]
  196. elif key.startswith('rtmp'):
  197. # The url doesn't have an rtmp app, we have to extract the playpath
  198. url, path = stream_url.split('mp3:', 1)
  199. stream_formats = [{
  200. 'format_id': key,
  201. 'url': url,
  202. 'play_path': 'mp3:' + path,
  203. 'ext': 'flv',
  204. }]
  205. elif key.startswith('hls'):
  206. stream_formats = self._extract_m3u8_formats(
  207. stream_url, track_id, 'mp3', entry_protocol='m3u8_native',
  208. m3u8_id=key, fatal=False)
  209. else:
  210. continue
  211. for f in stream_formats:
  212. f['abr'] = abr
  213. formats.extend(stream_formats)
  214. if not formats:
  215. # We fallback to the stream_url in the original info, this
  216. # cannot be always used, sometimes it can give an HTTP 404 error
  217. formats.append({
  218. 'format_id': 'fallback',
  219. 'url': update_url_query(info['stream_url'], query),
  220. 'ext': ext,
  221. })
  222. for f in formats:
  223. f['vcodec'] = 'none'
  224. self._check_formats(formats, track_id)
  225. self._sort_formats(formats)
  226. result['formats'] = formats
  227. return result
  228. def _real_extract(self, url):
  229. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  230. if mobj is None:
  231. raise ExtractorError('Invalid URL: %s' % url)
  232. track_id = mobj.group('track_id')
  233. if track_id is not None:
  234. info_json_url = 'https://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  235. full_title = track_id
  236. token = mobj.group('secret_token')
  237. if token:
  238. info_json_url += '&secret_token=' + token
  239. elif mobj.group('player'):
  240. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  241. real_url = query['url'][0]
  242. # If the token is in the query of the original url we have to
  243. # manually add it
  244. if 'secret_token' in query:
  245. real_url += '?secret_token=' + query['secret_token'][0]
  246. return self.url_result(real_url)
  247. else:
  248. # extract uploader (which is in the url)
  249. uploader = mobj.group('uploader')
  250. # extract simple title (uploader + slug of song title)
  251. slug_title = mobj.group('title')
  252. token = mobj.group('token')
  253. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  254. if token:
  255. resolve_title += '/%s' % token
  256. self.report_resolve(full_title)
  257. url = 'https://soundcloud.com/%s' % resolve_title
  258. info_json_url = self._resolv_url(url)
  259. info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
  260. return self._extract_info_dict(info, full_title, secret_token=token)
  261. class SoundcloudPlaylistBaseIE(SoundcloudIE):
  262. @staticmethod
  263. def _extract_id(e):
  264. return compat_str(e['id']) if e.get('id') else None
  265. def _extract_track_entries(self, tracks):
  266. return [
  267. self.url_result(
  268. track['permalink_url'], SoundcloudIE.ie_key(),
  269. video_id=self._extract_id(track))
  270. for track in tracks if track.get('permalink_url')]
  271. class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
  272. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  273. IE_NAME = 'soundcloud:set'
  274. _TESTS = [{
  275. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  276. 'info_dict': {
  277. 'id': '2284613',
  278. 'title': 'The Royal Concept EP',
  279. },
  280. 'playlist_mincount': 5,
  281. }, {
  282. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
  283. 'only_matching': True,
  284. }]
  285. def _real_extract(self, url):
  286. mobj = re.match(self._VALID_URL, url)
  287. # extract uploader (which is in the url)
  288. uploader = mobj.group('uploader')
  289. # extract simple title (uploader + slug of song title)
  290. slug_title = mobj.group('slug_title')
  291. full_title = '%s/sets/%s' % (uploader, slug_title)
  292. url = 'https://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  293. token = mobj.group('token')
  294. if token:
  295. full_title += '/' + token
  296. url += '/' + token
  297. self.report_resolve(full_title)
  298. resolv_url = self._resolv_url(url)
  299. info = self._download_json(resolv_url, full_title)
  300. if 'errors' in info:
  301. msgs = (compat_str(err['error_message']) for err in info['errors'])
  302. raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
  303. entries = self._extract_track_entries(info['tracks'])
  304. return {
  305. '_type': 'playlist',
  306. 'entries': entries,
  307. 'id': '%s' % info['id'],
  308. 'title': info['title'],
  309. }
  310. class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
  311. _API_BASE = 'https://api.soundcloud.com'
  312. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  313. def _extract_playlist(self, base_url, playlist_id, playlist_title):
  314. COMMON_QUERY = {
  315. 'limit': 50,
  316. 'client_id': self._CLIENT_ID,
  317. 'linked_partitioning': '1',
  318. }
  319. query = COMMON_QUERY.copy()
  320. query['offset'] = 0
  321. next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
  322. entries = []
  323. for i in itertools.count():
  324. response = self._download_json(
  325. next_href, playlist_id, 'Downloading track page %s' % (i + 1))
  326. collection = response['collection']
  327. if not collection:
  328. break
  329. def resolve_permalink_url(candidates):
  330. for cand in candidates:
  331. if isinstance(cand, dict):
  332. permalink_url = cand.get('permalink_url')
  333. entry_id = self._extract_id(cand)
  334. if permalink_url and permalink_url.startswith('http'):
  335. return permalink_url, entry_id
  336. for e in collection:
  337. permalink_url, entry_id = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
  338. if permalink_url:
  339. entries.append(self.url_result(permalink_url, video_id=entry_id))
  340. next_href = response.get('next_href')
  341. if not next_href:
  342. break
  343. parsed_next_href = compat_urlparse.urlparse(response['next_href'])
  344. qs = compat_urlparse.parse_qs(parsed_next_href.query)
  345. qs.update(COMMON_QUERY)
  346. next_href = compat_urlparse.urlunparse(
  347. parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
  348. return {
  349. '_type': 'playlist',
  350. 'id': playlist_id,
  351. 'title': playlist_title,
  352. 'entries': entries,
  353. }
  354. class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
  355. _VALID_URL = r'''(?x)
  356. https?://
  357. (?:(?:www|m)\.)?soundcloud\.com/
  358. (?P<user>[^/]+)
  359. (?:/
  360. (?P<rsrc>tracks|sets|reposts|likes|spotlight)
  361. )?
  362. /?(?:[?#].*)?$
  363. '''
  364. IE_NAME = 'soundcloud:user'
  365. _TESTS = [{
  366. 'url': 'https://soundcloud.com/the-akashic-chronicler',
  367. 'info_dict': {
  368. 'id': '114582580',
  369. 'title': 'The Akashic Chronicler (All)',
  370. },
  371. 'playlist_mincount': 74,
  372. }, {
  373. 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
  374. 'info_dict': {
  375. 'id': '114582580',
  376. 'title': 'The Akashic Chronicler (Tracks)',
  377. },
  378. 'playlist_mincount': 37,
  379. }, {
  380. 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
  381. 'info_dict': {
  382. 'id': '114582580',
  383. 'title': 'The Akashic Chronicler (Playlists)',
  384. },
  385. 'playlist_mincount': 2,
  386. }, {
  387. 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
  388. 'info_dict': {
  389. 'id': '114582580',
  390. 'title': 'The Akashic Chronicler (Reposts)',
  391. },
  392. 'playlist_mincount': 7,
  393. }, {
  394. 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
  395. 'info_dict': {
  396. 'id': '114582580',
  397. 'title': 'The Akashic Chronicler (Likes)',
  398. },
  399. 'playlist_mincount': 321,
  400. }, {
  401. 'url': 'https://soundcloud.com/grynpyret/spotlight',
  402. 'info_dict': {
  403. 'id': '7098329',
  404. 'title': 'Grynpyret (Spotlight)',
  405. },
  406. 'playlist_mincount': 1,
  407. }]
  408. _BASE_URL_MAP = {
  409. 'all': '%s/profile/soundcloud:users:%%s' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  410. 'tracks': '%s/users/%%s/tracks' % SoundcloudPagedPlaylistBaseIE._API_BASE,
  411. 'sets': '%s/users/%%s/playlists' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  412. 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  413. 'likes': '%s/users/%%s/likes' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  414. 'spotlight': '%s/users/%%s/spotlight' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
  415. }
  416. _TITLE_MAP = {
  417. 'all': 'All',
  418. 'tracks': 'Tracks',
  419. 'sets': 'Playlists',
  420. 'reposts': 'Reposts',
  421. 'likes': 'Likes',
  422. 'spotlight': 'Spotlight',
  423. }
  424. def _real_extract(self, url):
  425. mobj = re.match(self._VALID_URL, url)
  426. uploader = mobj.group('user')
  427. url = 'https://soundcloud.com/%s/' % uploader
  428. resolv_url = self._resolv_url(url)
  429. user = self._download_json(
  430. resolv_url, uploader, 'Downloading user info')
  431. resource = mobj.group('rsrc') or 'all'
  432. return self._extract_playlist(
  433. self._BASE_URL_MAP[resource] % user['id'], compat_str(user['id']),
  434. '%s (%s)' % (user['username'], self._TITLE_MAP[resource]))
  435. class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
  436. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
  437. IE_NAME = 'soundcloud:trackstation'
  438. _TESTS = [{
  439. 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
  440. 'info_dict': {
  441. 'id': '286017854',
  442. 'title': 'Track station: your-text',
  443. },
  444. 'playlist_mincount': 47,
  445. }]
  446. def _real_extract(self, url):
  447. track_name = self._match_id(url)
  448. webpage = self._download_webpage(url, track_name)
  449. track_id = self._search_regex(
  450. r'soundcloud:track-stations:(\d+)', webpage, 'track id')
  451. return self._extract_playlist(
  452. '%s/stations/soundcloud:track-stations:%s/tracks'
  453. % (self._API_V2_BASE, track_id),
  454. track_id, 'Track station: %s' % track_name)
  455. class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
  456. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  457. IE_NAME = 'soundcloud:playlist'
  458. _TESTS = [{
  459. 'url': 'https://api.soundcloud.com/playlists/4110309',
  460. 'info_dict': {
  461. 'id': '4110309',
  462. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  463. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  464. },
  465. 'playlist_count': 6,
  466. }]
  467. def _real_extract(self, url):
  468. mobj = re.match(self._VALID_URL, url)
  469. playlist_id = mobj.group('id')
  470. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  471. data_dict = {
  472. 'client_id': self._CLIENT_ID,
  473. }
  474. token = mobj.group('token')
  475. if token:
  476. data_dict['secret_token'] = token
  477. data = compat_urllib_parse_urlencode(data_dict)
  478. data = self._download_json(
  479. base_url + data, playlist_id, 'Downloading playlist')
  480. entries = self._extract_track_entries(data['tracks'])
  481. return {
  482. '_type': 'playlist',
  483. 'id': playlist_id,
  484. 'title': data.get('title'),
  485. 'description': data.get('description'),
  486. 'entries': entries,
  487. }
  488. class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
  489. IE_NAME = 'soundcloud:search'
  490. IE_DESC = 'Soundcloud search'
  491. _MAX_RESULTS = float('inf')
  492. _TESTS = [{
  493. 'url': 'scsearch15:post-avant jazzcore',
  494. 'info_dict': {
  495. 'title': 'post-avant jazzcore',
  496. },
  497. 'playlist_count': 15,
  498. }]
  499. _SEARCH_KEY = 'scsearch'
  500. _MAX_RESULTS_PER_PAGE = 200
  501. _DEFAULT_RESULTS_PER_PAGE = 50
  502. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  503. def _get_collection(self, endpoint, collection_id, **query):
  504. limit = min(
  505. query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
  506. self._MAX_RESULTS_PER_PAGE)
  507. query['limit'] = limit
  508. query['client_id'] = self._CLIENT_ID
  509. query['linked_partitioning'] = '1'
  510. query['offset'] = 0
  511. data = compat_urllib_parse_urlencode(query)
  512. next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
  513. collected_results = 0
  514. for i in itertools.count(1):
  515. response = self._download_json(
  516. next_url, collection_id, 'Downloading page {0}'.format(i),
  517. 'Unable to download API page')
  518. collection = response.get('collection', [])
  519. if not collection:
  520. break
  521. collection = list(filter(bool, collection))
  522. collected_results += len(collection)
  523. for item in collection:
  524. yield self.url_result(item['uri'], SoundcloudIE.ie_key())
  525. if not collection or collected_results >= limit:
  526. break
  527. next_url = response.get('next_href')
  528. if not next_url:
  529. break
  530. def _get_n_results(self, query, n):
  531. tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
  532. return self.playlist_result(tracks, playlist_title=query)