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.

385 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. return self.url_result(query['url'][0])
  207. else:
  208. # extract uploader (which is in the url)
  209. uploader = mobj.group('uploader')
  210. # extract simple title (uploader + slug of song title)
  211. slug_title = mobj.group('title')
  212. token = mobj.group('token')
  213. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  214. if token:
  215. resolve_title += '/%s' % token
  216. self.report_resolve(full_title)
  217. url = 'http://soundcloud.com/%s' % resolve_title
  218. info_json_url = self._resolv_url(url)
  219. info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
  220. return self._extract_info_dict(info, full_title, secret_token=token)
  221. class SoundcloudSetIE(SoundcloudIE):
  222. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
  223. IE_NAME = 'soundcloud:set'
  224. _TESTS = [{
  225. 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
  226. 'info_dict': {
  227. 'id': '2284613',
  228. 'title': 'The Royal Concept EP',
  229. },
  230. 'playlist_mincount': 6,
  231. }]
  232. def _real_extract(self, url):
  233. mobj = re.match(self._VALID_URL, url)
  234. # extract uploader (which is in the url)
  235. uploader = mobj.group('uploader')
  236. # extract simple title (uploader + slug of song title)
  237. slug_title = mobj.group('slug_title')
  238. full_title = '%s/sets/%s' % (uploader, slug_title)
  239. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  240. token = mobj.group('token')
  241. if token:
  242. full_title += '/' + token
  243. url += '/' + token
  244. self.report_resolve(full_title)
  245. resolv_url = self._resolv_url(url)
  246. info = self._download_json(resolv_url, full_title)
  247. if 'errors' in info:
  248. for err in info['errors']:
  249. self._downloader.report_error('unable to download video webpage: %s' % compat_str(err['error_message']))
  250. return
  251. return {
  252. '_type': 'playlist',
  253. 'entries': [self._extract_info_dict(track, secret_token=token) for track in info['tracks']],
  254. 'id': '%s' % info['id'],
  255. 'title': info['title'],
  256. }
  257. class SoundcloudUserIE(SoundcloudIE):
  258. _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<user>[^/]+)/?((?P<rsrc>tracks|likes)/?)?(\?.*)?$'
  259. IE_NAME = 'soundcloud:user'
  260. _TESTS = [{
  261. 'url': 'https://soundcloud.com/the-concept-band',
  262. 'info_dict': {
  263. 'id': '9615865',
  264. 'title': 'The Royal Concept',
  265. },
  266. 'playlist_mincount': 12
  267. }, {
  268. 'url': 'https://soundcloud.com/the-concept-band/likes',
  269. 'info_dict': {
  270. 'id': '9615865',
  271. 'title': 'The Royal Concept',
  272. },
  273. 'playlist_mincount': 1,
  274. }]
  275. def _real_extract(self, url):
  276. mobj = re.match(self._VALID_URL, url)
  277. uploader = mobj.group('user')
  278. resource = mobj.group('rsrc')
  279. if resource is None:
  280. resource = 'tracks'
  281. elif resource == 'likes':
  282. resource = 'favorites'
  283. url = 'http://soundcloud.com/%s/' % uploader
  284. resolv_url = self._resolv_url(url)
  285. user = self._download_json(
  286. resolv_url, uploader, 'Downloading user info')
  287. base_url = 'http://api.soundcloud.com/users/%s/%s.json?' % (uploader, resource)
  288. entries = []
  289. for i in itertools.count():
  290. data = compat_urllib_parse.urlencode({
  291. 'offset': i * 50,
  292. 'limit': 50,
  293. 'client_id': self._CLIENT_ID,
  294. })
  295. new_entries = self._download_json(
  296. base_url + data, uploader, 'Downloading track page %s' % (i + 1))
  297. if len(new_entries) == 0:
  298. self.to_screen('%s: End page received' % uploader)
  299. break
  300. entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
  301. return {
  302. '_type': 'playlist',
  303. 'id': compat_str(user['id']),
  304. 'title': user['username'],
  305. 'entries': entries,
  306. }
  307. class SoundcloudPlaylistIE(SoundcloudIE):
  308. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
  309. IE_NAME = 'soundcloud:playlist'
  310. _TESTS = [{
  311. 'url': 'http://api.soundcloud.com/playlists/4110309',
  312. 'info_dict': {
  313. 'id': '4110309',
  314. 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
  315. 'description': 're:.*?TILT Brass - Bowery Poetry Club',
  316. },
  317. 'playlist_count': 6,
  318. }]
  319. def _real_extract(self, url):
  320. mobj = re.match(self._VALID_URL, url)
  321. playlist_id = mobj.group('id')
  322. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  323. data_dict = {
  324. 'client_id': self._CLIENT_ID,
  325. }
  326. token = mobj.group('token')
  327. if token:
  328. data_dict['secret_token'] = token
  329. data = compat_urllib_parse.urlencode(data_dict)
  330. data = self._download_json(
  331. base_url + data, playlist_id, 'Downloading playlist')
  332. entries = [
  333. self._extract_info_dict(t, quiet=True, secret_token=token)
  334. for t in data['tracks']]
  335. return {
  336. '_type': 'playlist',
  337. 'id': playlist_id,
  338. 'title': data.get('title'),
  339. 'description': data.get('description'),
  340. 'entries': entries,
  341. }