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.

471 lines
17 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 InfoExtractor
  6. from ..compat import (
  7. compat_str,
  8. compat_urlparse,
  9. compat_urllib_parse,
  10. )
  11. from ..utils import (
  12. ExtractorError,
  13. int_or_none,
  14. unified_strdate,
  15. )
  16. class SoundcloudIE(InfoExtractor):
  17. """Information extractor for soundcloud.com
  18. To access the media, the uid of the song and a stream token
  19. must be extracted from the page source and the script must make
  20. a request to media.soundcloud.com/crossdomain.xml. Then
  21. the media can be grabbed by requesting from an url composed
  22. of the stream token and uid
  23. """
  24. _VALID_URL = r'''(?x)^(?:https?://)?
  25. (?:(?:(?:www\.|m\.)?soundcloud\.com/
  26. (?P<uploader>[\w\d-]+)/
  27. (?!(?:tracks|sets(?:/[^/?#]+)?|reposts|likes|spotlight)/?(?:$|[?#]))
  28. (?P<title>[\w\d-]+)/?
  29. (?P<token>[^?]+?)?(?:[?].*)?$)
  30. |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
  31. (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
  32. |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
  33. )
  34. '''
  35. IE_NAME = 'soundcloud'
  36. _TESTS = [
  37. {
  38. 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
  39. 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
  40. 'info_dict': {
  41. 'id': '62986583',
  42. 'ext': 'mp3',
  43. 'upload_date': '20121011',
  44. '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',
  45. 'uploader': 'E.T. ExTerrestrial Music',
  46. 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
  47. 'duration': 143,
  48. }
  49. },
  50. # not streamable song
  51. {
  52. 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
  53. 'info_dict': {
  54. 'id': '47127627',
  55. 'ext': 'mp3',
  56. 'title': 'Goldrushed',
  57. 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
  58. 'uploader': 'The Royal Concept',
  59. 'upload_date': '20120521',
  60. 'duration': 227,
  61. },
  62. 'params': {
  63. # rtmp
  64. 'skip_download': True,
  65. },
  66. },
  67. # private link
  68. {
  69. 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
  70. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  71. 'info_dict': {
  72. 'id': '123998367',
  73. 'ext': 'mp3',
  74. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  75. 'uploader': 'jaimeMF',
  76. 'description': 'test chars: \"\'/\\ä↭',
  77. 'upload_date': '20131209',
  78. 'duration': 9,
  79. },
  80. },
  81. # private link (alt format)
  82. {
  83. 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
  84. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  85. 'info_dict': {
  86. 'id': '123998367',
  87. 'ext': 'mp3',
  88. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  89. 'uploader': 'jaimeMF',
  90. 'description': 'test chars: \"\'/\\ä↭',
  91. 'upload_date': '20131209',
  92. 'duration': 9,
  93. },
  94. },
  95. # downloadable song
  96. {
  97. 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
  98. 'md5': '7624f2351f8a3b2e7cd51522496e7631',
  99. 'info_dict': {
  100. 'id': '128590877',
  101. 'ext': 'mp3',
  102. 'title': 'Bus Brakes',
  103. 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
  104. 'uploader': 'oddsamples',
  105. 'upload_date': '20140109',
  106. 'duration': 17,
  107. },
  108. },
  109. ]
  110. _CLIENT_ID = '02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea'
  111. _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
  112. def report_resolve(self, video_id):
  113. """Report information extraction."""
  114. self.to_screen('%s: Resolving id' % video_id)
  115. @classmethod
  116. def _resolv_url(cls, url):
  117. return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  118. def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
  119. track_id = compat_str(info['id'])
  120. name = full_title or track_id
  121. if quiet:
  122. self.report_extraction(name)
  123. thumbnail = info['artwork_url']
  124. if thumbnail is not None:
  125. thumbnail = thumbnail.replace('-large', '-t500x500')
  126. ext = 'mp3'
  127. result = {
  128. 'id': track_id,
  129. 'uploader': info['user']['username'],
  130. 'upload_date': unified_strdate(info['created_at']),
  131. 'title': info['title'],
  132. 'description': info['description'],
  133. 'thumbnail': thumbnail,
  134. 'duration': int_or_none(info.get('duration'), 1000),
  135. 'webpage_url': info.get('permalink_url'),
  136. }
  137. formats = []
  138. if info.get('downloadable', False):
  139. # We can build a direct link to the song
  140. format_url = (
  141. 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
  142. track_id, self._CLIENT_ID))
  143. formats.append({
  144. 'format_id': 'download',
  145. 'ext': info.get('original_format', 'mp3'),
  146. 'url': format_url,
  147. 'vcodec': 'none',
  148. 'preference': 10,
  149. })
  150. # We have to retrieve the url
  151. streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
  152. 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
  153. format_dict = self._download_json(
  154. streams_url,
  155. track_id, 'Downloading track url')
  156. for key, stream_url in format_dict.items():
  157. if key.startswith('http'):
  158. formats.append({
  159. 'format_id': key,
  160. 'ext': ext,
  161. 'url': stream_url,
  162. 'vcodec': 'none',
  163. })
  164. elif key.startswith('rtmp'):
  165. # The url doesn't have an rtmp app, we have to extract the playpath
  166. url, path = stream_url.split('mp3:', 1)
  167. formats.append({
  168. 'format_id': key,
  169. 'url': url,
  170. 'play_path': 'mp3:' + path,
  171. 'ext': 'flv',
  172. 'vcodec': 'none',
  173. })
  174. if not formats:
  175. # We fallback to the stream_url in the original info, this
  176. # cannot be always used, sometimes it can give an HTTP 404 error
  177. formats.append({
  178. 'format_id': 'fallback',
  179. 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
  180. 'ext': ext,
  181. 'vcodec': 'none',
  182. })
  183. for f in formats:
  184. if f['format_id'].startswith('http'):
  185. f['protocol'] = 'http'
  186. if f['format_id'].startswith('rtmp'):
  187. f['protocol'] = 'rtmp'
  188. self._check_formats(formats, track_id)
  189. self._sort_formats(formats)
  190. result['formats'] = formats
  191. return result
  192. def _real_extract(self, url):
  193. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  194. if mobj is None:
  195. raise ExtractorError('Invalid URL: %s' % url)
  196. track_id = mobj.group('track_id')
  197. token = None
  198. if track_id is not None:
  199. info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  200. full_title = track_id
  201. token = mobj.group('secret_token')
  202. if token:
  203. info_json_url += "&secret_token=" + token
  204. elif mobj.group('player'):
  205. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  206. real_url = query['url'][0]
  207. # If the token is in the query of the original url we have to
  208. # manually add it
  209. if 'secret_token' in query:
  210. real_url += '?secret_token=' + query['secret_token'][0]
  211. return self.url_result(real_url)
  212. else:
  213. # extract uploader (which is in the url)
  214. uploader = mobj.group('uploader')
  215. # extract simple title (uploader + slug of song title)
  216. slug_title = mobj.group('title')
  217. token = mobj.group('token')
  218. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  219. if token:
  220. resolve_title += '/%s' % token
  221. self.report_resolve(full_title)
  222. url = 'http://soundcloud.com/%s' % resolve_title
  223. info_json_url = self._resolv_url(url)
  224. info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
  225. return self._extract_info_dict(info, full_title, secret_token=token)
  226. class SoundcloudSetIE(SoundcloudIE):
  227. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  228. IE_NAME = 'soundcloud:set'
  229. _TESTS = [{
  230. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  231. 'info_dict': {
  232. 'id': '2284613',
  233. 'title': 'The Royal Concept EP',
  234. },
  235. 'playlist_mincount': 6,
  236. }]
  237. def _real_extract(self, url):
  238. mobj = re.match(self._VALID_URL, url)
  239. # extract uploader (which is in the url)
  240. uploader = mobj.group('uploader')
  241. # extract simple title (uploader + slug of song title)
  242. slug_title = mobj.group('slug_title')
  243. full_title = '%s/sets/%s' % (uploader, slug_title)
  244. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  245. token = mobj.group('token')
  246. if token:
  247. full_title += '/' + token
  248. url += '/' + token
  249. self.report_resolve(full_title)
  250. resolv_url = self._resolv_url(url)
  251. info = self._download_json(resolv_url, full_title)
  252. if 'errors' in info:
  253. msgs = (compat_str(err['error_message']) for err in info['errors'])
  254. raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
  255. entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in info['tracks']]
  256. return {
  257. '_type': 'playlist',
  258. 'entries': entries,
  259. 'id': '%s' % info['id'],
  260. 'title': info['title'],
  261. }
  262. class SoundcloudUserIE(SoundcloudIE):
  263. _VALID_URL = r'''(?x)
  264. https?://
  265. (?:(?:www|m)\.)?soundcloud\.com/
  266. (?P<user>[^/]+)
  267. (?:/
  268. (?P<rsrc>tracks|sets|reposts|likes|spotlight)
  269. )?
  270. /?(?:[?#].*)?$
  271. '''
  272. IE_NAME = 'soundcloud:user'
  273. _TESTS = [{
  274. 'url': 'https://soundcloud.com/the-akashic-chronicler',
  275. 'info_dict': {
  276. 'id': '114582580',
  277. 'title': 'The Akashic Chronicler (All)',
  278. },
  279. 'playlist_mincount': 111,
  280. }, {
  281. 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
  282. 'info_dict': {
  283. 'id': '114582580',
  284. 'title': 'The Akashic Chronicler (Tracks)',
  285. },
  286. 'playlist_mincount': 50,
  287. }, {
  288. 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
  289. 'info_dict': {
  290. 'id': '114582580',
  291. 'title': 'The Akashic Chronicler (Playlists)',
  292. },
  293. 'playlist_mincount': 3,
  294. }, {
  295. 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
  296. 'info_dict': {
  297. 'id': '114582580',
  298. 'title': 'The Akashic Chronicler (Reposts)',
  299. },
  300. 'playlist_mincount': 7,
  301. }, {
  302. 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
  303. 'info_dict': {
  304. 'id': '114582580',
  305. 'title': 'The Akashic Chronicler (Likes)',
  306. },
  307. 'playlist_mincount': 321,
  308. }, {
  309. 'url': 'https://soundcloud.com/grynpyret/spotlight',
  310. 'info_dict': {
  311. 'id': '7098329',
  312. 'title': 'Grynpyret (Spotlight)',
  313. },
  314. 'playlist_mincount': 1,
  315. }]
  316. _API_BASE = 'https://api.soundcloud.com'
  317. _API_V2_BASE = 'https://api-v2.soundcloud.com'
  318. _BASE_URL_MAP = {
  319. 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE,
  320. 'tracks': '%s/users/%%s/tracks' % _API_BASE,
  321. 'sets': '%s/users/%%s/playlists' % _API_V2_BASE,
  322. 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE,
  323. 'likes': '%s/users/%%s/likes' % _API_V2_BASE,
  324. 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE,
  325. }
  326. _TITLE_MAP = {
  327. 'all': 'All',
  328. 'tracks': 'Tracks',
  329. 'sets': 'Playlists',
  330. 'reposts': 'Reposts',
  331. 'likes': 'Likes',
  332. 'spotlight': 'Spotlight',
  333. }
  334. def _real_extract(self, url):
  335. mobj = re.match(self._VALID_URL, url)
  336. uploader = mobj.group('user')
  337. url = 'http://soundcloud.com/%s/' % uploader
  338. resolv_url = self._resolv_url(url)
  339. user = self._download_json(
  340. resolv_url, uploader, 'Downloading user info')
  341. resource = mobj.group('rsrc') or 'all'
  342. base_url = self._BASE_URL_MAP[resource] % user['id']
  343. next_href = None
  344. entries = []
  345. for i in itertools.count():
  346. if not next_href:
  347. data = compat_urllib_parse.urlencode({
  348. 'offset': i * 50,
  349. 'limit': 50,
  350. 'client_id': self._CLIENT_ID,
  351. 'linked_partitioning': '1',
  352. 'representation': 'speedy',
  353. })
  354. next_href = base_url + '?' + data
  355. response = self._download_json(
  356. next_href, uploader, 'Downloading track page %s' % (i + 1))
  357. collection = response['collection']
  358. if not collection:
  359. self.to_screen('%s: End page received' % uploader)
  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. if 'next_href' in response:
  372. next_href = response['next_href']
  373. if not next_href:
  374. break
  375. else:
  376. next_href = None
  377. return {
  378. '_type': 'playlist',
  379. 'id': compat_str(user['id']),
  380. 'title': '%s (%s)' % (user['username'], self._TITLE_MAP[resource]),
  381. 'entries': entries,
  382. }
  383. class SoundcloudPlaylistIE(SoundcloudIE):
  384. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  385. IE_NAME = 'soundcloud:playlist'
  386. _TESTS = [{
  387. 'url': 'http://api.soundcloud.com/playlists/4110309',
  388. 'info_dict': {
  389. 'id': '4110309',
  390. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  391. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  392. },
  393. 'playlist_count': 6,
  394. }]
  395. def _real_extract(self, url):
  396. mobj = re.match(self._VALID_URL, url)
  397. playlist_id = mobj.group('id')
  398. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  399. data_dict = {
  400. 'client_id': self._CLIENT_ID,
  401. }
  402. token = mobj.group('token')
  403. if token:
  404. data_dict['secret_token'] = token
  405. data = compat_urllib_parse.urlencode(data_dict)
  406. data = self._download_json(
  407. base_url + data, playlist_id, 'Downloading playlist')
  408. entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in data['tracks']]
  409. return {
  410. '_type': 'playlist',
  411. 'id': playlist_id,
  412. 'title': data.get('title'),
  413. 'description': data.get('description'),
  414. 'entries': entries,
  415. }