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.

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