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.

380 lines
14 KiB

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