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.

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