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.

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