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.

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