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.

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