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.

211 lines
8.0 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. @classmethod
  57. def suitable(cls, url):
  58. return re.match(cls._VALID_URL, url, flags=re.VERBOSE) is not None
  59. def report_resolve(self, video_id):
  60. """Report information extraction."""
  61. self.to_screen(u'%s: Resolving id' % video_id)
  62. @classmethod
  63. def _resolv_url(cls, url):
  64. return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  65. def _extract_info_dict(self, info, full_title=None, quiet=False):
  66. track_id = compat_str(info['id'])
  67. name = full_title or track_id
  68. if quiet == False:
  69. self.report_extraction(name)
  70. thumbnail = info['artwork_url']
  71. if thumbnail is not None:
  72. thumbnail = thumbnail.replace('-large', '-t500x500')
  73. result = {
  74. 'id': track_id,
  75. 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
  76. 'uploader': info['user']['username'],
  77. 'upload_date': unified_strdate(info['created_at']),
  78. 'title': info['title'],
  79. 'ext': u'mp3',
  80. 'description': info['description'],
  81. 'thumbnail': thumbnail,
  82. }
  83. if info.get('downloadable', False):
  84. result['url'] = 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(track_id, self._CLIENT_ID)
  85. if not info.get('streamable', False):
  86. # We have to get the rtmp url
  87. stream_json = self._download_webpage(
  88. 'http://api.soundcloud.com/i1/tracks/{0}/streams?client_id={1}'.format(track_id, self._CLIENT_ID),
  89. track_id, u'Downloading track url')
  90. rtmp_url = json.loads(stream_json)['rtmp_mp3_128_url']
  91. # The url doesn't have an rtmp app, we have to extract the playpath
  92. url, path = rtmp_url.split('mp3:', 1)
  93. result.update({
  94. 'url': url,
  95. 'play_path': 'mp3:' + path,
  96. })
  97. return result
  98. def _real_extract(self, url):
  99. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  100. if mobj is None:
  101. raise ExtractorError(u'Invalid URL: %s' % url)
  102. track_id = mobj.group('track_id')
  103. if track_id is not None:
  104. info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  105. full_title = track_id
  106. elif mobj.group('widget'):
  107. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  108. return self.url_result(query['url'][0], ie='Soundcloud')
  109. else:
  110. # extract uploader (which is in the url)
  111. uploader = mobj.group(1)
  112. # extract simple title (uploader + slug of song title)
  113. slug_title = mobj.group(2)
  114. full_title = '%s/%s' % (uploader, slug_title)
  115. self.report_resolve(full_title)
  116. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  117. info_json_url = self._resolv_url(url)
  118. info_json = self._download_webpage(info_json_url, full_title, u'Downloading info JSON')
  119. info = json.loads(info_json)
  120. return self._extract_info_dict(info, full_title)
  121. class SoundcloudSetIE(SoundcloudIE):
  122. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)(?:[?].*)?$'
  123. IE_NAME = u'soundcloud:set'
  124. # it's in tests/test_playlists.py
  125. _TESTS = []
  126. def _real_extract(self, url):
  127. mobj = re.match(self._VALID_URL, url)
  128. if mobj is None:
  129. raise ExtractorError(u'Invalid URL: %s' % url)
  130. # extract uploader (which is in the url)
  131. uploader = mobj.group(1)
  132. # extract simple title (uploader + slug of song title)
  133. slug_title = mobj.group(2)
  134. full_title = '%s/sets/%s' % (uploader, slug_title)
  135. self.report_resolve(full_title)
  136. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  137. resolv_url = self._resolv_url(url)
  138. info_json = self._download_webpage(resolv_url, full_title)
  139. videos = []
  140. info = json.loads(info_json)
  141. if 'errors' in info:
  142. for err in info['errors']:
  143. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
  144. return
  145. self.report_extraction(full_title)
  146. return {'_type': 'playlist',
  147. 'entries': [self._extract_info_dict(track) for track in info['tracks']],
  148. 'id': info['id'],
  149. 'title': info['title'],
  150. }
  151. class SoundcloudUserIE(SoundcloudIE):
  152. _VALID_URL = r'https?://(www\.)?soundcloud.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
  153. IE_NAME = u'soundcloud:user'
  154. # it's in tests/test_playlists.py
  155. _TESTS = []
  156. def _real_extract(self, url):
  157. mobj = re.match(self._VALID_URL, url)
  158. uploader = mobj.group('user')
  159. url = 'http://soundcloud.com/%s/' % uploader
  160. resolv_url = self._resolv_url(url)
  161. user_json = self._download_webpage(resolv_url, uploader,
  162. u'Downloading user info')
  163. user = json.loads(user_json)
  164. tracks = []
  165. for i in itertools.count():
  166. data = compat_urllib_parse.urlencode({'offset': i*50,
  167. 'client_id': self._CLIENT_ID,
  168. })
  169. tracks_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % user['id'] + data
  170. response = self._download_webpage(tracks_url, uploader,
  171. u'Downloading tracks page %s' % (i+1))
  172. new_tracks = json.loads(response)
  173. tracks.extend(self._extract_info_dict(track, quiet=True) for track in new_tracks)
  174. if len(new_tracks) < 50:
  175. break
  176. return {
  177. '_type': 'playlist',
  178. 'id': compat_str(user['id']),
  179. 'title': user['username'],
  180. 'entries': tracks,
  181. }