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.

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