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.

389 lines
14 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. (?!sets/|likes/?(?:$|[?#]))
  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 = 'b45b1aa10f1ac2941910a7f0d10f8e28'
  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. return {
  256. '_type': 'playlist',
  257. 'entries': [self._extract_info_dict(track, secret_token=token) for track in info['tracks']],
  258. 'id': '%s' % info['id'],
  259. 'title': info['title'],
  260. }
  261. class SoundcloudUserIE(SoundcloudIE):
  262. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<user>[^/]+)/?((?P<rsrc>tracks|likes)/?)?(\?.*)?$'
  263. IE_NAME = 'soundcloud:user'
  264. _TESTS = [{
  265. 'url': 'https://soundcloud.com/the-concept-band',
  266. 'info_dict': {
  267. 'id': '9615865',
  268. 'title': 'The Royal Concept',
  269. },
  270. 'playlist_mincount': 12
  271. }, {
  272. 'url': 'https://soundcloud.com/the-concept-band/likes',
  273. 'info_dict': {
  274. 'id': '9615865',
  275. 'title': 'The Royal Concept',
  276. },
  277. 'playlist_mincount': 1,
  278. }]
  279. def _real_extract(self, url):
  280. mobj = re.match(self._VALID_URL, url)
  281. uploader = mobj.group('user')
  282. resource = mobj.group('rsrc')
  283. if resource is None:
  284. resource = 'tracks'
  285. elif resource == 'likes':
  286. resource = 'favorites'
  287. url = 'http://soundcloud.com/%s/' % uploader
  288. resolv_url = self._resolv_url(url)
  289. user = self._download_json(
  290. resolv_url, uploader, 'Downloading user info')
  291. base_url = 'http://api.soundcloud.com/users/%s/%s.json?' % (uploader, resource)
  292. entries = []
  293. for i in itertools.count():
  294. data = compat_urllib_parse.urlencode({
  295. 'offset': i * 50,
  296. 'limit': 50,
  297. 'client_id': self._CLIENT_ID,
  298. })
  299. new_entries = self._download_json(
  300. base_url + data, uploader, 'Downloading track page %s' % (i + 1))
  301. if len(new_entries) == 0:
  302. self.to_screen('%s: End page received' % uploader)
  303. break
  304. entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
  305. return {
  306. '_type': 'playlist',
  307. 'id': compat_str(user['id']),
  308. 'title': user['username'],
  309. 'entries': entries,
  310. }
  311. class SoundcloudPlaylistIE(SoundcloudIE):
  312. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  313. IE_NAME = 'soundcloud:playlist'
  314. _TESTS = [{
  315. 'url': 'http://api.soundcloud.com/playlists/4110309',
  316. 'info_dict': {
  317. 'id': '4110309',
  318. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  319. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  320. },
  321. 'playlist_count': 6,
  322. }]
  323. def _real_extract(self, url):
  324. mobj = re.match(self._VALID_URL, url)
  325. playlist_id = mobj.group('id')
  326. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  327. data_dict = {
  328. 'client_id': self._CLIENT_ID,
  329. }
  330. token = mobj.group('token')
  331. if token:
  332. data_dict['secret_token'] = token
  333. data = compat_urllib_parse.urlencode(data_dict)
  334. data = self._download_json(
  335. base_url + data, playlist_id, 'Downloading playlist')
  336. entries = [
  337. self._extract_info_dict(t, quiet=True, secret_token=token)
  338. for t in data['tracks']]
  339. return {
  340. '_type': 'playlist',
  341. 'id': playlist_id,
  342. 'title': data.get('title'),
  343. 'description': data.get('description'),
  344. 'entries': entries,
  345. }