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.

559 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. streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
  166. 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
  167. format_dict = self._download_json(
  168. streams_url,
  169. track_id, 'Downloading track url')
  170. for key, stream_url in format_dict.items():
  171. if key.startswith('http'):
  172. formats.append({
  173. 'format_id': key,
  174. 'ext': ext,
  175. 'url': stream_url,
  176. 'vcodec': 'none',
  177. })
  178. elif key.startswith('rtmp'):
  179. # The url doesn't have an rtmp app, we have to extract the playpath
  180. url, path = stream_url.split('mp3:', 1)
  181. formats.append({
  182. 'format_id': key,
  183. 'url': url,
  184. 'play_path': 'mp3:' + path,
  185. 'ext': 'flv',
  186. 'vcodec': 'none',
  187. })
  188. if not formats:
  189. # We fallback to the stream_url in the original info, this
  190. # cannot be always used, sometimes it can give an HTTP 404 error
  191. formats.append({
  192. 'format_id': 'fallback',
  193. 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
  194. 'ext': ext,
  195. 'vcodec': 'none',
  196. })
  197. for f in formats:
  198. if f['format_id'].startswith('http'):
  199. f['protocol'] = 'http'
  200. if f['format_id'].startswith('rtmp'):
  201. f['protocol'] = 'rtmp'
  202. self._check_formats(formats, track_id)
  203. self._sort_formats(formats)
  204. result['formats'] = formats
  205. return result
  206. def _real_extract(self, url):
  207. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  208. if mobj is None:
  209. raise ExtractorError('Invalid URL: %s' % url)
  210. track_id = mobj.group('track_id')
  211. if track_id is not None:
  212. info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  213. full_title = track_id
  214. token = mobj.group('secret_token')
  215. if token:
  216. info_json_url += '&secret_token=' + token
  217. elif mobj.group('player'):
  218. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  219. real_url = query['url'][0]
  220. # If the token is in the query of the original url we have to
  221. # manually add it
  222. if 'secret_token' in query:
  223. real_url += '?secret_token=' + query['secret_token'][0]
  224. return self.url_result(real_url)
  225. else:
  226. # extract uploader (which is in the url)
  227. uploader = mobj.group('uploader')
  228. # extract simple title (uploader + slug of song title)
  229. slug_title = mobj.group('title')
  230. token = mobj.group('token')
  231. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  232. if token:
  233. resolve_title += '/%s' % token
  234. self.report_resolve(full_title)
  235. url = 'http://soundcloud.com/%s' % resolve_title
  236. info_json_url = self._resolv_url(url)
  237. info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
  238. return self._extract_info_dict(info, full_title, secret_token=token)
  239. class SoundcloudPlaylistBaseIE(SoundcloudIE):
  240. @staticmethod
  241. def _extract_id(e):
  242. return compat_str(e['id']) if e.get('id') else None
  243. def _extract_track_entries(self, tracks):
  244. return [
  245. self.url_result(
  246. track['permalink_url'], SoundcloudIE.ie_key(),
  247. video_id=self._extract_id(track))
  248. for track in tracks if track.get('permalink_url')]
  249. class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
  250. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  251. IE_NAME = 'soundcloud:set'
  252. _TESTS = [{
  253. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  254. 'info_dict': {
  255. 'id': '2284613',
  256. 'title': 'The Royal Concept EP',
  257. },
  258. 'playlist_mincount': 6,
  259. }, {
  260. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
  261. 'only_matching': True,
  262. }]
  263. def _real_extract(self, url):
  264. mobj = re.match(self._VALID_URL, url)
  265. # extract uploader (which is in the url)
  266. uploader = mobj.group('uploader')
  267. # extract simple title (uploader + slug of song title)
  268. slug_title = mobj.group('slug_title')
  269. full_title = '%s/sets/%s' % (uploader, slug_title)
  270. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  271. token = mobj.group('token')
  272. if token:
  273. full_title += '/' + token
  274. url += '/' + token
  275. self.report_resolve(full_title)
  276. resolv_url = self._resolv_url(url)
  277. info = self._download_json(resolv_url, full_title)
  278. if 'errors' in info:
  279. msgs = (compat_str(err['error_message']) for err in info['errors'])
  280. raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
  281. entries = self._extract_track_entries(info['tracks'])
  282. return {
  283. '_type': 'playlist',
  284. 'entries': entries,
  285. 'id': '%s' % info['id'],
  286. 'title': info['title'],
  287. }
  288. class SoundcloudUserIE(SoundcloudPlaylistBaseIE):
  289. _VALID_URL = r'''(?x)
  290. https?://
  291. (?:(?:www|m)\.)?soundcloud\.com/
  292. (?P<user>[^/]+)
  293. (?:/
  294. (?P<rsrc>tracks|sets|reposts|likes|spotlight)
  295. )?
  296. /?(?:[?#].*)?$
  297. '''
  298. IE_NAME = 'soundcloud:user'
  299. _TESTS = [{
  300. 'url': 'https://soundcloud.com/the-akashic-chronicler',
  301. 'info_dict': {
  302. 'id': '114582580',
  303. 'title': 'The Akashic Chronicler (All)',
  304. },
  305. 'playlist_mincount': 74,
  306. }, {
  307. 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
  308. 'info_dict': {
  309. 'id': '114582580',
  310. 'title': 'The Akashic Chronicler (Tracks)',
  311. },
  312. 'playlist_mincount': 37,
  313. }, {
  314. 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
  315. 'info_dict': {
  316. 'id': '114582580',
  317. 'title': 'The Akashic Chronicler (Playlists)',
  318. },
  319. 'playlist_mincount': 2,
  320. }, {
  321. 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
  322. 'info_dict': {
  323. 'id': '114582580',
  324. 'title': 'The Akashic Chronicler (Reposts)',
  325. },
  326. 'playlist_mincount': 7,
  327. }, {
  328. 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
  329. 'info_dict': {
  330. 'id': '114582580',
  331. 'title': 'The Akashic Chronicler (Likes)',
  332. },
  333. 'playlist_mincount': 321,
  334. }, {
  335. 'url': 'https://soundcloud.com/grynpyret/spotlight',
  336. 'info_dict': {
  337. 'id': '7098329',
  338. 'title': 'GRYNPYRET (Spotlight)',
  339. },
  340. 'playlist_mincount': 1,
  341. }]
  342. _API_BASE = 'https://api.soundcloud.com'
  343. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  344. _BASE_URL_MAP = {
  345. 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE,
  346. 'tracks': '%s/users/%%s/tracks' % _API_BASE,
  347. 'sets': '%s/users/%%s/playlists' % _API_V2_BASE,
  348. 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE,
  349. 'likes': '%s/users/%%s/likes' % _API_V2_BASE,
  350. 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE,
  351. }
  352. _TITLE_MAP = {
  353. 'all': 'All',
  354. 'tracks': 'Tracks',
  355. 'sets': 'Playlists',
  356. 'reposts': 'Reposts',
  357. 'likes': 'Likes',
  358. 'spotlight': 'Spotlight',
  359. }
  360. def _real_extract(self, url):
  361. mobj = re.match(self._VALID_URL, url)
  362. uploader = mobj.group('user')
  363. url = 'http://soundcloud.com/%s/' % uploader
  364. resolv_url = self._resolv_url(url)
  365. user = self._download_json(
  366. resolv_url, uploader, 'Downloading user info')
  367. resource = mobj.group('rsrc') or 'all'
  368. base_url = self._BASE_URL_MAP[resource] % user['id']
  369. COMMON_QUERY = {
  370. 'limit': 50,
  371. 'client_id': self._CLIENT_ID,
  372. 'linked_partitioning': '1',
  373. }
  374. query = COMMON_QUERY.copy()
  375. query['offset'] = 0
  376. next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
  377. entries = []
  378. for i in itertools.count():
  379. response = self._download_json(
  380. next_href, uploader, 'Downloading track page %s' % (i + 1))
  381. collection = response['collection']
  382. if not collection:
  383. break
  384. def resolve_permalink_url(candidates):
  385. for cand in candidates:
  386. if isinstance(cand, dict):
  387. permalink_url = cand.get('permalink_url')
  388. entry_id = self._extract_id(cand)
  389. if permalink_url and permalink_url.startswith('http'):
  390. return permalink_url, entry_id
  391. for e in collection:
  392. permalink_url, entry_id = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
  393. if permalink_url:
  394. entries.append(self.url_result(permalink_url, video_id=entry_id))
  395. next_href = response.get('next_href')
  396. if not next_href:
  397. break
  398. parsed_next_href = compat_urlparse.urlparse(response['next_href'])
  399. qs = compat_urlparse.parse_qs(parsed_next_href.query)
  400. qs.update(COMMON_QUERY)
  401. next_href = compat_urlparse.urlunparse(
  402. parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
  403. return {
  404. '_type': 'playlist',
  405. 'id': compat_str(user['id']),
  406. 'title': '%s (%s)' % (user['username'], self._TITLE_MAP[resource]),
  407. 'entries': entries,
  408. }
  409. class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
  410. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  411. IE_NAME = 'soundcloud:playlist'
  412. _TESTS = [{
  413. 'url': 'http://api.soundcloud.com/playlists/4110309',
  414. 'info_dict': {
  415. 'id': '4110309',
  416. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  417. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  418. },
  419. 'playlist_count': 6,
  420. }]
  421. def _real_extract(self, url):
  422. mobj = re.match(self._VALID_URL, url)
  423. playlist_id = mobj.group('id')
  424. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  425. data_dict = {
  426. 'client_id': self._CLIENT_ID,
  427. }
  428. token = mobj.group('token')
  429. if token:
  430. data_dict['secret_token'] = token
  431. data = compat_urllib_parse_urlencode(data_dict)
  432. data = self._download_json(
  433. base_url + data, playlist_id, 'Downloading playlist')
  434. entries = self._extract_track_entries(data['tracks'])
  435. return {
  436. '_type': 'playlist',
  437. 'id': playlist_id,
  438. 'title': data.get('title'),
  439. 'description': data.get('description'),
  440. 'entries': entries,
  441. }
  442. class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
  443. IE_NAME = 'soundcloud:search'
  444. IE_DESC = 'Soundcloud search'
  445. _MAX_RESULTS = float('inf')
  446. _TESTS = [{
  447. 'url': 'scsearch15:post-avant jazzcore',
  448. 'info_dict': {
  449. 'title': 'post-avant jazzcore',
  450. },
  451. 'playlist_count': 15,
  452. }]
  453. _SEARCH_KEY = 'scsearch'
  454. _MAX_RESULTS_PER_PAGE = 200
  455. _DEFAULT_RESULTS_PER_PAGE = 50
  456. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  457. def _get_collection(self, endpoint, collection_id, **query):
  458. limit = min(
  459. query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
  460. self._MAX_RESULTS_PER_PAGE)
  461. query['limit'] = limit
  462. query['client_id'] = self._CLIENT_ID
  463. query['linked_partitioning'] = '1'
  464. query['offset'] = 0
  465. data = compat_urllib_parse_urlencode(query)
  466. next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
  467. collected_results = 0
  468. for i in itertools.count(1):
  469. response = self._download_json(
  470. next_url, collection_id, 'Downloading page {0}'.format(i),
  471. 'Unable to download API page')
  472. collection = response.get('collection', [])
  473. if not collection:
  474. break
  475. collection = list(filter(bool, collection))
  476. collected_results += len(collection)
  477. for item in collection:
  478. yield self.url_result(item['uri'], SoundcloudIE.ie_key())
  479. if not collection or collected_results >= limit:
  480. break
  481. next_url = response.get('next_href')
  482. if not next_url:
  483. break
  484. def _get_n_results(self, query, n):
  485. tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
  486. return self.playlist_result(tracks, playlist_title=query)