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.

545 lines
19 KiB

10 years ago
10 years ago
  1. # encoding: 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 = '02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea'
  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 SoundcloudSetIE(SoundcloudIE):
  240. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  241. IE_NAME = 'soundcloud:set'
  242. _TESTS = [{
  243. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  244. 'info_dict': {
  245. 'id': '2284613',
  246. 'title': 'The Royal Concept EP',
  247. },
  248. 'playlist_mincount': 6,
  249. }, {
  250. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
  251. 'only_matching': True,
  252. }]
  253. def _real_extract(self, url):
  254. mobj = re.match(self._VALID_URL, url)
  255. # extract uploader (which is in the url)
  256. uploader = mobj.group('uploader')
  257. # extract simple title (uploader + slug of song title)
  258. slug_title = mobj.group('slug_title')
  259. full_title = '%s/sets/%s' % (uploader, slug_title)
  260. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  261. token = mobj.group('token')
  262. if token:
  263. full_title += '/' + token
  264. url += '/' + token
  265. self.report_resolve(full_title)
  266. resolv_url = self._resolv_url(url)
  267. info = self._download_json(resolv_url, full_title)
  268. if 'errors' in info:
  269. msgs = (compat_str(err['error_message']) for err in info['errors'])
  270. raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
  271. entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in info['tracks']]
  272. return {
  273. '_type': 'playlist',
  274. 'entries': entries,
  275. 'id': '%s' % info['id'],
  276. 'title': info['title'],
  277. }
  278. class SoundcloudUserIE(SoundcloudIE):
  279. _VALID_URL = r'''(?x)
  280. https?://
  281. (?:(?:www|m)\.)?soundcloud\.com/
  282. (?P<user>[^/]+)
  283. (?:/
  284. (?P<rsrc>tracks|sets|reposts|likes|spotlight)
  285. )?
  286. /?(?:[?#].*)?$
  287. '''
  288. IE_NAME = 'soundcloud:user'
  289. _TESTS = [{
  290. 'url': 'https://soundcloud.com/the-akashic-chronicler',
  291. 'info_dict': {
  292. 'id': '114582580',
  293. 'title': 'The Akashic Chronicler (All)',
  294. },
  295. 'playlist_mincount': 111,
  296. }, {
  297. 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
  298. 'info_dict': {
  299. 'id': '114582580',
  300. 'title': 'The Akashic Chronicler (Tracks)',
  301. },
  302. 'playlist_mincount': 50,
  303. }, {
  304. 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
  305. 'info_dict': {
  306. 'id': '114582580',
  307. 'title': 'The Akashic Chronicler (Playlists)',
  308. },
  309. 'playlist_mincount': 3,
  310. }, {
  311. 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
  312. 'info_dict': {
  313. 'id': '114582580',
  314. 'title': 'The Akashic Chronicler (Reposts)',
  315. },
  316. 'playlist_mincount': 7,
  317. }, {
  318. 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
  319. 'info_dict': {
  320. 'id': '114582580',
  321. 'title': 'The Akashic Chronicler (Likes)',
  322. },
  323. 'playlist_mincount': 321,
  324. }, {
  325. 'url': 'https://soundcloud.com/grynpyret/spotlight',
  326. 'info_dict': {
  327. 'id': '7098329',
  328. 'title': 'Grynpyret (Spotlight)',
  329. },
  330. 'playlist_mincount': 1,
  331. }]
  332. _API_BASE = 'https://api.soundcloud.com'
  333. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  334. _BASE_URL_MAP = {
  335. 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE,
  336. 'tracks': '%s/users/%%s/tracks' % _API_BASE,
  337. 'sets': '%s/users/%%s/playlists' % _API_V2_BASE,
  338. 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE,
  339. 'likes': '%s/users/%%s/likes' % _API_V2_BASE,
  340. 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE,
  341. }
  342. _TITLE_MAP = {
  343. 'all': 'All',
  344. 'tracks': 'Tracks',
  345. 'sets': 'Playlists',
  346. 'reposts': 'Reposts',
  347. 'likes': 'Likes',
  348. 'spotlight': 'Spotlight',
  349. }
  350. def _real_extract(self, url):
  351. mobj = re.match(self._VALID_URL, url)
  352. uploader = mobj.group('user')
  353. url = 'http://soundcloud.com/%s/' % uploader
  354. resolv_url = self._resolv_url(url)
  355. user = self._download_json(
  356. resolv_url, uploader, 'Downloading user info')
  357. resource = mobj.group('rsrc') or 'all'
  358. base_url = self._BASE_URL_MAP[resource] % user['id']
  359. COMMON_QUERY = {
  360. 'limit': 50,
  361. 'client_id': self._CLIENT_ID,
  362. 'linked_partitioning': '1',
  363. }
  364. query = COMMON_QUERY.copy()
  365. query['offset'] = 0
  366. next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
  367. entries = []
  368. for i in itertools.count():
  369. response = self._download_json(
  370. next_href, uploader, 'Downloading track page %s' % (i + 1))
  371. collection = response['collection']
  372. if not collection:
  373. break
  374. def resolve_permalink_url(candidates):
  375. for cand in candidates:
  376. if isinstance(cand, dict):
  377. permalink_url = cand.get('permalink_url')
  378. if permalink_url and permalink_url.startswith('http'):
  379. return permalink_url
  380. for e in collection:
  381. permalink_url = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
  382. if permalink_url:
  383. entries.append(self.url_result(permalink_url))
  384. next_href = response.get('next_href')
  385. if not next_href:
  386. break
  387. parsed_next_href = compat_urlparse.urlparse(response['next_href'])
  388. qs = compat_urlparse.parse_qs(parsed_next_href.query)
  389. qs.update(COMMON_QUERY)
  390. next_href = compat_urlparse.urlunparse(
  391. parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
  392. return {
  393. '_type': 'playlist',
  394. 'id': compat_str(user['id']),
  395. 'title': '%s (%s)' % (user['username'], self._TITLE_MAP[resource]),
  396. 'entries': entries,
  397. }
  398. class SoundcloudPlaylistIE(SoundcloudIE):
  399. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  400. IE_NAME = 'soundcloud:playlist'
  401. _TESTS = [{
  402. 'url': 'http://api.soundcloud.com/playlists/4110309',
  403. 'info_dict': {
  404. 'id': '4110309',
  405. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  406. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  407. },
  408. 'playlist_count': 6,
  409. }]
  410. def _real_extract(self, url):
  411. mobj = re.match(self._VALID_URL, url)
  412. playlist_id = mobj.group('id')
  413. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  414. data_dict = {
  415. 'client_id': self._CLIENT_ID,
  416. }
  417. token = mobj.group('token')
  418. if token:
  419. data_dict['secret_token'] = token
  420. data = compat_urllib_parse_urlencode(data_dict)
  421. data = self._download_json(
  422. base_url + data, playlist_id, 'Downloading playlist')
  423. entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in data['tracks']]
  424. return {
  425. '_type': 'playlist',
  426. 'id': playlist_id,
  427. 'title': data.get('title'),
  428. 'description': data.get('description'),
  429. 'entries': entries,
  430. }
  431. class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
  432. IE_NAME = 'soundcloud:search'
  433. IE_DESC = 'Soundcloud search'
  434. _MAX_RESULTS = float('inf')
  435. _TESTS = [{
  436. 'url': 'scsearch15:post-avant jazzcore',
  437. 'info_dict': {
  438. 'title': 'post-avant jazzcore',
  439. },
  440. 'playlist_count': 15,
  441. }]
  442. _SEARCH_KEY = 'scsearch'
  443. _MAX_RESULTS_PER_PAGE = 200
  444. _DEFAULT_RESULTS_PER_PAGE = 50
  445. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  446. def _get_collection(self, endpoint, collection_id, **query):
  447. limit = min(
  448. query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
  449. self._MAX_RESULTS_PER_PAGE)
  450. query['limit'] = limit
  451. query['client_id'] = self._CLIENT_ID
  452. query['linked_partitioning'] = '1'
  453. query['offset'] = 0
  454. data = compat_urllib_parse_urlencode(query)
  455. next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
  456. collected_results = 0
  457. for i in itertools.count(1):
  458. response = self._download_json(
  459. next_url, collection_id, 'Downloading page {0}'.format(i),
  460. 'Unable to download API page')
  461. collection = response.get('collection', [])
  462. if not collection:
  463. break
  464. collection = list(filter(bool, collection))
  465. collected_results += len(collection)
  466. for item in collection:
  467. yield self.url_result(item['uri'], SoundcloudIE.ie_key())
  468. if not collection or collected_results >= limit:
  469. break
  470. next_url = response.get('next_href')
  471. if not next_url:
  472. break
  473. def _get_n_results(self, query, n):
  474. tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
  475. return self.playlist_result(tracks, playlist_title=query)