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.

290 lines
11 KiB

  1. # encoding: utf-8
  2. import json
  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. unified_strdate,
  12. )
  13. class SoundcloudIE(InfoExtractor):
  14. """Information extractor for soundcloud.com
  15. To access the media, the uid of the song and a stream token
  16. must be extracted from the page source and the script must make
  17. a request to media.soundcloud.com/crossdomain.xml. Then
  18. the media can be grabbed by requesting from an url composed
  19. of the stream token and uid
  20. """
  21. _VALID_URL = r'''^(?:https?://)?
  22. (?:(?:(?:www\.)?soundcloud\.com/
  23. (?P<uploader>[\w\d-]+)/
  24. (?!sets/)(?P<title>[\w\d-]+)/?
  25. (?P<token>[^?]+?)?(?:[?].*)?$)
  26. |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
  27. |(?P<widget>w\.soundcloud\.com/player/?.*?url=.*)
  28. )
  29. '''
  30. IE_NAME = u'soundcloud'
  31. _TESTS = [
  32. {
  33. u'url': u'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
  34. u'file': u'62986583.mp3',
  35. u'md5': u'ebef0a451b909710ed1d7787dddbf0d7',
  36. u'info_dict': {
  37. u"upload_date": u"20121011",
  38. u"description": u"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",
  39. u"uploader": u"E.T. ExTerrestrial Music",
  40. u"title": u"Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1"
  41. }
  42. },
  43. # not streamable song
  44. {
  45. u'url': u'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
  46. u'info_dict': {
  47. u'id': u'47127627',
  48. u'ext': u'mp3',
  49. u'title': u'Goldrushed',
  50. u'uploader': u'The Royal Concept',
  51. u'upload_date': u'20120521',
  52. },
  53. u'params': {
  54. # rtmp
  55. u'skip_download': True,
  56. },
  57. },
  58. # private link
  59. {
  60. u'url': u'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
  61. u'md5': u'aa0dd32bfea9b0c5ef4f02aacd080604',
  62. u'info_dict': {
  63. u'id': u'123998367',
  64. u'ext': u'mp3',
  65. u'title': u'Youtube - Dl Test Video \'\' Ä↭',
  66. u'uploader': u'jaimeMF',
  67. u'description': u'test chars: \"\'/\\ä↭',
  68. u'upload_date': u'20131209',
  69. },
  70. },
  71. # downloadable song
  72. {
  73. u'url': u'https://soundcloud.com/simgretina/just-your-problem-baby-1',
  74. u'md5': u'56a8b69568acaa967b4c49f9d1d52d19',
  75. u'info_dict': {
  76. u'id': u'105614606',
  77. u'ext': u'wav',
  78. u'title': u'Just Your Problem Baby (Acapella)',
  79. u'description': u'Vocals',
  80. u'uploader': u'Sim Gretina',
  81. u'upload_date': u'20130815',
  82. },
  83. },
  84. ]
  85. _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
  86. _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
  87. @classmethod
  88. def suitable(cls, url):
  89. return re.match(cls._VALID_URL, url, flags=re.VERBOSE) is not None
  90. def report_resolve(self, video_id):
  91. """Report information extraction."""
  92. self.to_screen(u'%s: Resolving id' % video_id)
  93. @classmethod
  94. def _resolv_url(cls, url):
  95. return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  96. def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
  97. track_id = compat_str(info['id'])
  98. name = full_title or track_id
  99. if quiet:
  100. self.report_extraction(name)
  101. thumbnail = info['artwork_url']
  102. if thumbnail is not None:
  103. thumbnail = thumbnail.replace('-large', '-t500x500')
  104. ext = u'mp3'
  105. result = {
  106. 'id': track_id,
  107. 'uploader': info['user']['username'],
  108. 'upload_date': unified_strdate(info['created_at']),
  109. 'title': info['title'],
  110. 'description': info['description'],
  111. 'thumbnail': thumbnail,
  112. }
  113. if info.get('downloadable', False):
  114. # We can build a direct link to the song
  115. format_url = (
  116. u'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
  117. track_id, self._CLIENT_ID))
  118. result['formats'] = [{
  119. 'format_id': 'download',
  120. 'ext': info.get('original_format', u'mp3'),
  121. 'url': format_url,
  122. 'vcodec': 'none',
  123. }]
  124. else:
  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. stream_json = self._download_webpage(
  129. streams_url,
  130. track_id, u'Downloading track url')
  131. formats = []
  132. format_dict = json.loads(stream_json)
  133. for key, stream_url in format_dict.items():
  134. if key.startswith(u'http'):
  135. formats.append({
  136. 'format_id': key,
  137. 'ext': ext,
  138. 'url': stream_url,
  139. 'vcodec': 'none',
  140. })
  141. elif key.startswith(u'rtmp'):
  142. # The url doesn't have an rtmp app, we have to extract the playpath
  143. url, path = stream_url.split('mp3:', 1)
  144. formats.append({
  145. 'format_id': key,
  146. 'url': url,
  147. 'play_path': 'mp3:' + path,
  148. 'ext': ext,
  149. 'vcodec': 'none',
  150. })
  151. if not formats:
  152. # We fallback to the stream_url in the original info, this
  153. # cannot be always used, sometimes it can give an HTTP 404 error
  154. formats.append({
  155. 'format_id': u'fallback',
  156. 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
  157. 'ext': ext,
  158. 'vcodec': 'none',
  159. })
  160. def format_pref(f):
  161. if f['format_id'].startswith('http'):
  162. return 2
  163. if f['format_id'].startswith('rtmp'):
  164. return 1
  165. return 0
  166. formats.sort(key=format_pref)
  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('widget'):
  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, u'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 = u'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 = u'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. u'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. u'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. }