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.

316 lines
11 KiB

  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import re
  5. import itertools
  6. from .common import InfoExtractor
  7. from ..utils import (
  8. compat_str,
  9. compat_urlparse,
  10. compat_urllib_parse,
  11. ExtractorError,
  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/)(?P<title>[\w\d-]+)/?
  26. (?P<token>[^?]+?)?(?:[?].*)?$)
  27. |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
  28. |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
  29. )
  30. '''
  31. IE_NAME = 'soundcloud'
  32. _TESTS = [
  33. {
  34. 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
  35. 'file': '62986583.mp3',
  36. 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
  37. 'info_dict': {
  38. "upload_date": "20121011",
  39. "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",
  40. "uploader": "E.T. ExTerrestrial Music",
  41. "title": "Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1"
  42. }
  43. },
  44. # not streamable song
  45. {
  46. 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
  47. 'info_dict': {
  48. 'id': '47127627',
  49. 'ext': 'mp3',
  50. 'title': 'Goldrushed',
  51. 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
  52. 'uploader': 'The Royal Concept',
  53. 'upload_date': '20120521',
  54. },
  55. 'params': {
  56. # rtmp
  57. 'skip_download': True,
  58. },
  59. },
  60. # private link
  61. {
  62. 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
  63. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  64. 'info_dict': {
  65. 'id': '123998367',
  66. 'ext': 'mp3',
  67. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  68. 'uploader': 'jaimeMF',
  69. 'description': 'test chars: \"\'/\\ä↭',
  70. 'upload_date': '20131209',
  71. },
  72. },
  73. # downloadable song
  74. {
  75. 'url': 'https://soundcloud.com/simgretina/just-your-problem-baby-1',
  76. 'md5': '56a8b69568acaa967b4c49f9d1d52d19',
  77. 'info_dict': {
  78. 'id': '105614606',
  79. 'ext': 'wav',
  80. 'title': 'Just Your Problem Baby (Acapella)',
  81. 'description': 'Vocals',
  82. 'uploader': 'Sim Gretina',
  83. 'upload_date': '20130815',
  84. },
  85. },
  86. ]
  87. _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
  88. _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
  89. def report_resolve(self, video_id):
  90. """Report information extraction."""
  91. self.to_screen('%s: Resolving id' % video_id)
  92. @classmethod
  93. def _resolv_url(cls, url):
  94. return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  95. def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
  96. track_id = compat_str(info['id'])
  97. name = full_title or track_id
  98. if quiet:
  99. self.report_extraction(name)
  100. thumbnail = info['artwork_url']
  101. if thumbnail is not None:
  102. thumbnail = thumbnail.replace('-large', '-t500x500')
  103. ext = 'mp3'
  104. result = {
  105. 'id': track_id,
  106. 'uploader': info['user']['username'],
  107. 'upload_date': unified_strdate(info['created_at']),
  108. 'title': info['title'],
  109. 'description': info['description'],
  110. 'thumbnail': thumbnail,
  111. }
  112. formats = []
  113. if info.get('downloadable', False):
  114. # We can build a direct link to the song
  115. format_url = (
  116. 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
  117. track_id, self._CLIENT_ID))
  118. formats.append({
  119. 'format_id': 'download',
  120. 'ext': info.get('original_format', 'mp3'),
  121. 'url': format_url,
  122. 'vcodec': 'none',
  123. 'preference': 10,
  124. })
  125. # We have to retrieve the url
  126. streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
  127. 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
  128. format_dict = self._download_json(
  129. streams_url,
  130. track_id, 'Downloading track url')
  131. for key, stream_url in format_dict.items():
  132. if key.startswith('http'):
  133. formats.append({
  134. 'format_id': key,
  135. 'ext': ext,
  136. 'url': stream_url,
  137. 'vcodec': 'none',
  138. })
  139. elif key.startswith('rtmp'):
  140. # The url doesn't have an rtmp app, we have to extract the playpath
  141. url, path = stream_url.split('mp3:', 1)
  142. formats.append({
  143. 'format_id': key,
  144. 'url': url,
  145. 'play_path': 'mp3:' + path,
  146. 'ext': ext,
  147. 'vcodec': 'none',
  148. })
  149. if not formats:
  150. # We fallback to the stream_url in the original info, this
  151. # cannot be always used, sometimes it can give an HTTP 404 error
  152. formats.append({
  153. 'format_id': 'fallback',
  154. 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
  155. 'ext': ext,
  156. 'vcodec': 'none',
  157. })
  158. for f in formats:
  159. if f['format_id'].startswith('http'):
  160. f['protocol'] = 'http'
  161. if f['format_id'].startswith('rtmp'):
  162. f['protocol'] = 'rtmp'
  163. self._sort_formats(formats)
  164. result['formats'] = formats
  165. return result
  166. def _real_extract(self, url):
  167. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  168. if mobj is None:
  169. raise ExtractorError('Invalid URL: %s' % url)
  170. track_id = mobj.group('track_id')
  171. token = None
  172. if track_id is not None:
  173. info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  174. full_title = track_id
  175. elif mobj.group('player'):
  176. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  177. return self.url_result(query['url'][0])
  178. else:
  179. # extract uploader (which is in the url)
  180. uploader = mobj.group('uploader')
  181. # extract simple title (uploader + slug of song title)
  182. slug_title = mobj.group('title')
  183. token = mobj.group('token')
  184. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  185. if token:
  186. resolve_title += '/%s' % token
  187. self.report_resolve(full_title)
  188. url = 'http://soundcloud.com/%s' % resolve_title
  189. info_json_url = self._resolv_url(url)
  190. info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
  191. return self._extract_info_dict(info, full_title, secret_token=token)
  192. class SoundcloudSetIE(SoundcloudIE):
  193. _VALID_URL = r'https?://(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
  194. IE_NAME = 'soundcloud:set'
  195. # it's in tests/test_playlists.py
  196. _TESTS = []
  197. def _real_extract(self, url):
  198. mobj = re.match(self._VALID_URL, url)
  199. if mobj is None:
  200. raise ExtractorError('Invalid URL: %s' % url)
  201. # extract uploader (which is in the url)
  202. uploader = mobj.group(1)
  203. # extract simple title (uploader + slug of song title)
  204. slug_title = mobj.group(2)
  205. full_title = '%s/sets/%s' % (uploader, slug_title)
  206. self.report_resolve(full_title)
  207. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  208. resolv_url = self._resolv_url(url)
  209. info = self._download_json(resolv_url, full_title)
  210. if 'errors' in info:
  211. for err in info['errors']:
  212. self._downloader.report_error('unable to download video webpage: %s' % compat_str(err['error_message']))
  213. return
  214. self.report_extraction(full_title)
  215. return {'_type': 'playlist',
  216. 'entries': [self._extract_info_dict(track) for track in info['tracks']],
  217. 'id': info['id'],
  218. 'title': info['title'],
  219. }
  220. class SoundcloudUserIE(SoundcloudIE):
  221. _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
  222. IE_NAME = 'soundcloud:user'
  223. # it's in tests/test_playlists.py
  224. _TESTS = []
  225. def _real_extract(self, url):
  226. mobj = re.match(self._VALID_URL, url)
  227. uploader = mobj.group('user')
  228. url = 'http://soundcloud.com/%s/' % uploader
  229. resolv_url = self._resolv_url(url)
  230. user = self._download_json(
  231. resolv_url, uploader, 'Downloading user info')
  232. base_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % uploader
  233. entries = []
  234. for i in itertools.count():
  235. data = compat_urllib_parse.urlencode({
  236. 'offset': i * 50,
  237. 'client_id': self._CLIENT_ID,
  238. })
  239. new_entries = self._download_json(
  240. base_url + data, uploader, 'Downloading track page %s' % (i + 1))
  241. entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
  242. if len(new_entries) < 50:
  243. break
  244. return {
  245. '_type': 'playlist',
  246. 'id': compat_str(user['id']),
  247. 'title': user['username'],
  248. 'entries': entries,
  249. }
  250. class SoundcloudPlaylistIE(SoundcloudIE):
  251. _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)'
  252. IE_NAME = 'soundcloud:playlist'
  253. # it's in tests/test_playlists.py
  254. _TESTS = []
  255. def _real_extract(self, url):
  256. mobj = re.match(self._VALID_URL, url)
  257. playlist_id = mobj.group('id')
  258. base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
  259. data = compat_urllib_parse.urlencode({
  260. 'client_id': self._CLIENT_ID,
  261. })
  262. data = self._download_json(
  263. base_url + data, playlist_id, 'Downloading playlist')
  264. entries = [
  265. self._extract_info_dict(t, quiet=True) for t in data['tracks']]
  266. return {
  267. '_type': 'playlist',
  268. 'id': playlist_id,
  269. 'title': data.get('title'),
  270. 'description': data.get('description'),
  271. 'entries': entries,
  272. }