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.

220 lines
8.5 KiB

  1. import json
  2. import re
  3. import itertools
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. compat_str,
  7. compat_urlparse,
  8. compat_urllib_parse,
  9. ExtractorError,
  10. unified_strdate,
  11. )
  12. class SoundcloudIE(InfoExtractor):
  13. """Information extractor for soundcloud.com
  14. To access the media, the uid of the song and a stream token
  15. must be extracted from the page source and the script must make
  16. a request to media.soundcloud.com/crossdomain.xml. Then
  17. the media can be grabbed by requesting from an url composed
  18. of the stream token and uid
  19. """
  20. _VALID_URL = r'''^(?:https?://)?
  21. (?:(?:(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)/?(?:[?].*)?$)
  22. |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
  23. |(?P<widget>w.soundcloud.com/player/?.*?url=.*)
  24. )
  25. '''
  26. IE_NAME = u'soundcloud'
  27. _TESTS = [
  28. {
  29. u'url': u'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
  30. u'file': u'62986583.mp3',
  31. u'md5': u'ebef0a451b909710ed1d7787dddbf0d7',
  32. u'info_dict': {
  33. u"upload_date": u"20121011",
  34. 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",
  35. u"uploader": u"E.T. ExTerrestrial Music",
  36. u"title": u"Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1"
  37. }
  38. },
  39. # not streamable song
  40. {
  41. u'url': u'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
  42. u'info_dict': {
  43. u'id': u'47127627',
  44. u'ext': u'mp3',
  45. u'title': u'Goldrushed',
  46. u'uploader': u'The Royal Concept',
  47. u'upload_date': u'20120521',
  48. },
  49. u'params': {
  50. # rtmp
  51. u'skip_download': True,
  52. },
  53. },
  54. ]
  55. _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
  56. _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
  57. @classmethod
  58. def suitable(cls, url):
  59. return re.match(cls._VALID_URL, url, flags=re.VERBOSE) is not None
  60. def report_resolve(self, video_id):
  61. """Report information extraction."""
  62. self.to_screen(u'%s: Resolving id' % video_id)
  63. @classmethod
  64. def _resolv_url(cls, url):
  65. return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  66. def _extract_info_dict(self, info, full_title=None, quiet=False):
  67. track_id = compat_str(info['id'])
  68. name = full_title or track_id
  69. if quiet == False:
  70. self.report_extraction(name)
  71. thumbnail = info['artwork_url']
  72. if thumbnail is not None:
  73. thumbnail = thumbnail.replace('-large', '-t500x500')
  74. result = {
  75. 'id': track_id,
  76. 'uploader': info['user']['username'],
  77. 'upload_date': unified_strdate(info['created_at']),
  78. 'title': info['title'],
  79. 'ext': info.get('original_format', u'mp3'),
  80. 'description': info['description'],
  81. 'thumbnail': thumbnail,
  82. }
  83. if info.get('downloadable', False):
  84. # We can build a direct link to the song
  85. result['url'] = 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(track_id, self._CLIENT_ID)
  86. else:
  87. # We have to retrieve the url
  88. stream_json = self._download_webpage(
  89. 'http://api.soundcloud.com/i1/tracks/{0}/streams?client_id={1}'.format(track_id, self._IPHONE_CLIENT_ID),
  90. track_id, u'Downloading track url')
  91. # There should be only one entry in the dictionary
  92. key, stream_url = list(json.loads(stream_json).items())[0]
  93. if key.startswith(u'http'):
  94. result['url'] = stream_url
  95. elif key.startswith(u'rtmp'):
  96. # The url doesn't have an rtmp app, we have to extract the playpath
  97. url, path = stream_url.split('mp3:', 1)
  98. result.update({
  99. 'url': url,
  100. 'play_path': 'mp3:' + path,
  101. })
  102. else:
  103. # We fallback to the stream_url in the original info, this
  104. # cannot be always used, sometimes it can give an HTTP 404 error
  105. result['url'] = info['stream_url'] + '?client_id=' + self._CLIENT_ID,
  106. return result
  107. def _real_extract(self, url):
  108. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  109. if mobj is None:
  110. raise ExtractorError(u'Invalid URL: %s' % url)
  111. track_id = mobj.group('track_id')
  112. if track_id is not None:
  113. info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  114. full_title = track_id
  115. elif mobj.group('widget'):
  116. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  117. return self.url_result(query['url'][0], ie='Soundcloud')
  118. else:
  119. # extract uploader (which is in the url)
  120. uploader = mobj.group(1)
  121. # extract simple title (uploader + slug of song title)
  122. slug_title = mobj.group(2)
  123. full_title = '%s/%s' % (uploader, slug_title)
  124. self.report_resolve(full_title)
  125. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  126. info_json_url = self._resolv_url(url)
  127. info_json = self._download_webpage(info_json_url, full_title, u'Downloading info JSON')
  128. info = json.loads(info_json)
  129. return self._extract_info_dict(info, full_title)
  130. class SoundcloudSetIE(SoundcloudIE):
  131. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)(?:[?].*)?$'
  132. IE_NAME = u'soundcloud:set'
  133. # it's in tests/test_playlists.py
  134. _TESTS = []
  135. def _real_extract(self, url):
  136. mobj = re.match(self._VALID_URL, url)
  137. if mobj is None:
  138. raise ExtractorError(u'Invalid URL: %s' % url)
  139. # extract uploader (which is in the url)
  140. uploader = mobj.group(1)
  141. # extract simple title (uploader + slug of song title)
  142. slug_title = mobj.group(2)
  143. full_title = '%s/sets/%s' % (uploader, slug_title)
  144. self.report_resolve(full_title)
  145. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  146. resolv_url = self._resolv_url(url)
  147. info_json = self._download_webpage(resolv_url, full_title)
  148. info = json.loads(info_json)
  149. if 'errors' in info:
  150. for err in info['errors']:
  151. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
  152. return
  153. self.report_extraction(full_title)
  154. return {'_type': 'playlist',
  155. 'entries': [self._extract_info_dict(track) for track in info['tracks']],
  156. 'id': info['id'],
  157. 'title': info['title'],
  158. }
  159. class SoundcloudUserIE(SoundcloudIE):
  160. _VALID_URL = r'https?://(www\.)?soundcloud.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
  161. IE_NAME = u'soundcloud:user'
  162. # it's in tests/test_playlists.py
  163. _TESTS = []
  164. def _real_extract(self, url):
  165. mobj = re.match(self._VALID_URL, url)
  166. uploader = mobj.group('user')
  167. url = 'http://soundcloud.com/%s/' % uploader
  168. resolv_url = self._resolv_url(url)
  169. user_json = self._download_webpage(resolv_url, uploader,
  170. u'Downloading user info')
  171. user = json.loads(user_json)
  172. tracks = []
  173. for i in itertools.count():
  174. data = compat_urllib_parse.urlencode({'offset': i*50,
  175. 'client_id': self._CLIENT_ID,
  176. })
  177. tracks_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % user['id'] + data
  178. response = self._download_webpage(tracks_url, uploader,
  179. u'Downloading tracks page %s' % (i+1))
  180. new_tracks = json.loads(response)
  181. tracks.extend(self._extract_info_dict(track, quiet=True) for track in new_tracks)
  182. if len(new_tracks) < 50:
  183. break
  184. return {
  185. '_type': 'playlist',
  186. 'id': compat_str(user['id']),
  187. 'title': user['username'],
  188. 'entries': tracks,
  189. }