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.

567 lines
20 KiB

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