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.

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