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.

291 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'''^(?: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. 'uploader': 'The Royal Concept',
  52. 'upload_date': '20120521',
  53. },
  54. 'params': {
  55. # rtmp
  56. 'skip_download': True,
  57. },
  58. },
  59. # private link
  60. {
  61. 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
  62. 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
  63. 'info_dict': {
  64. 'id': '123998367',
  65. 'ext': 'mp3',
  66. 'title': 'Youtube - Dl Test Video \'\' Ä↭',
  67. 'uploader': 'jaimeMF',
  68. 'description': 'test chars: \"\'/\\ä↭',
  69. 'upload_date': '20131209',
  70. },
  71. },
  72. # downloadable song
  73. {
  74. 'url': 'https://soundcloud.com/simgretina/just-your-problem-baby-1',
  75. 'md5': '56a8b69568acaa967b4c49f9d1d52d19',
  76. 'info_dict': {
  77. 'id': '105614606',
  78. 'ext': 'wav',
  79. 'title': 'Just Your Problem Baby (Acapella)',
  80. 'description': 'Vocals',
  81. 'uploader': 'Sim Gretina',
  82. 'upload_date': '20130815',
  83. },
  84. },
  85. ]
  86. _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
  87. _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
  88. @classmethod
  89. def suitable(cls, url):
  90. return re.match(cls._VALID_URL, url, flags=re.VERBOSE) is not None
  91. def report_resolve(self, video_id):
  92. """Report information extraction."""
  93. self.to_screen(u'%s: Resolving id' % video_id)
  94. @classmethod
  95. def _resolv_url(cls, url):
  96. return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  97. def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
  98. track_id = compat_str(info['id'])
  99. name = full_title or track_id
  100. if quiet:
  101. self.report_extraction(name)
  102. thumbnail = info['artwork_url']
  103. if thumbnail is not None:
  104. thumbnail = thumbnail.replace('-large', '-t500x500')
  105. ext = 'mp3'
  106. result = {
  107. 'id': track_id,
  108. 'uploader': info['user']['username'],
  109. 'upload_date': unified_strdate(info['created_at']),
  110. 'title': info['title'],
  111. 'description': info['description'],
  112. 'thumbnail': thumbnail,
  113. }
  114. if info.get('downloadable', False):
  115. # We can build a direct link to the song
  116. format_url = (
  117. 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
  118. track_id, self._CLIENT_ID))
  119. result['formats'] = [{
  120. 'format_id': 'download',
  121. 'ext': info.get('original_format', 'mp3'),
  122. 'url': format_url,
  123. 'vcodec': 'none',
  124. }]
  125. else:
  126. # We have to retrieve the url
  127. streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
  128. 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
  129. stream_json = self._download_webpage(
  130. streams_url,
  131. track_id, 'Downloading track url')
  132. formats = []
  133. format_dict = json.loads(stream_json)
  134. for key, stream_url in format_dict.items():
  135. if key.startswith(u'http'):
  136. formats.append({
  137. 'format_id': key,
  138. 'ext': ext,
  139. 'url': stream_url,
  140. 'vcodec': 'none',
  141. })
  142. elif key.startswith(u'rtmp'):
  143. # The url doesn't have an rtmp app, we have to extract the playpath
  144. url, path = stream_url.split('mp3:', 1)
  145. formats.append({
  146. 'format_id': key,
  147. 'url': url,
  148. 'play_path': 'mp3:' + path,
  149. 'ext': ext,
  150. 'vcodec': 'none',
  151. })
  152. if not formats:
  153. # We fallback to the stream_url in the original info, this
  154. # cannot be always used, sometimes it can give an HTTP 404 error
  155. formats.append({
  156. 'format_id': 'fallback',
  157. 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
  158. 'ext': ext,
  159. 'vcodec': 'none',
  160. })
  161. for f in formats:
  162. if f['format_id'].startswith('http'):
  163. f['protocol'] = 'http'
  164. if f['format_id'].startswith('rtmp'):
  165. f['protocol'] = 'rtmp'
  166. self._sort_formats(formats)
  167. result['formats'] = formats
  168. return result
  169. def _real_extract(self, url):
  170. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  171. if mobj is None:
  172. raise ExtractorError(u'Invalid URL: %s' % url)
  173. track_id = mobj.group('track_id')
  174. token = None
  175. if track_id is not None:
  176. info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  177. full_title = track_id
  178. elif mobj.group('player'):
  179. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  180. return self.url_result(query['url'][0], ie='Soundcloud')
  181. else:
  182. # extract uploader (which is in the url)
  183. uploader = mobj.group('uploader')
  184. # extract simple title (uploader + slug of song title)
  185. slug_title = mobj.group('title')
  186. token = mobj.group('token')
  187. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  188. if token:
  189. resolve_title += '/%s' % token
  190. self.report_resolve(full_title)
  191. url = 'http://soundcloud.com/%s' % resolve_title
  192. info_json_url = self._resolv_url(url)
  193. info_json = self._download_webpage(info_json_url, full_title, 'Downloading info JSON')
  194. info = json.loads(info_json)
  195. return self._extract_info_dict(info, full_title, secret_token=token)
  196. class SoundcloudSetIE(SoundcloudIE):
  197. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)(?:[?].*)?$'
  198. IE_NAME = 'soundcloud:set'
  199. # it's in tests/test_playlists.py
  200. _TESTS = []
  201. def _real_extract(self, url):
  202. mobj = re.match(self._VALID_URL, url)
  203. if mobj is None:
  204. raise ExtractorError(u'Invalid URL: %s' % url)
  205. # extract uploader (which is in the url)
  206. uploader = mobj.group(1)
  207. # extract simple title (uploader + slug of song title)
  208. slug_title = mobj.group(2)
  209. full_title = '%s/sets/%s' % (uploader, slug_title)
  210. self.report_resolve(full_title)
  211. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  212. resolv_url = self._resolv_url(url)
  213. info_json = self._download_webpage(resolv_url, full_title)
  214. info = json.loads(info_json)
  215. if 'errors' in info:
  216. for err in info['errors']:
  217. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
  218. return
  219. self.report_extraction(full_title)
  220. return {'_type': 'playlist',
  221. 'entries': [self._extract_info_dict(track) for track in info['tracks']],
  222. 'id': info['id'],
  223. 'title': info['title'],
  224. }
  225. class SoundcloudUserIE(SoundcloudIE):
  226. _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
  227. IE_NAME = 'soundcloud:user'
  228. # it's in tests/test_playlists.py
  229. _TESTS = []
  230. def _real_extract(self, url):
  231. mobj = re.match(self._VALID_URL, url)
  232. uploader = mobj.group('user')
  233. url = 'http://soundcloud.com/%s/' % uploader
  234. resolv_url = self._resolv_url(url)
  235. user_json = self._download_webpage(resolv_url, uploader,
  236. 'Downloading user info')
  237. user = json.loads(user_json)
  238. tracks = []
  239. for i in itertools.count():
  240. data = compat_urllib_parse.urlencode({'offset': i*50,
  241. 'client_id': self._CLIENT_ID,
  242. })
  243. tracks_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % user['id'] + data
  244. response = self._download_webpage(tracks_url, uploader,
  245. 'Downloading tracks page %s' % (i+1))
  246. new_tracks = json.loads(response)
  247. tracks.extend(self._extract_info_dict(track, quiet=True) for track in new_tracks)
  248. if len(new_tracks) < 50:
  249. break
  250. return {
  251. '_type': 'playlist',
  252. 'id': compat_str(user['id']),
  253. 'title': user['username'],
  254. 'entries': tracks,
  255. }