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.

276 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-]+)/(?P<title>[\w\d-]+)/?
  24. (?P<token>[^?]+?)?(?:[?].*)?$)
  25. |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
  26. |(?P<widget>w\.soundcloud\.com/player/?.*?url=.*)
  27. )
  28. '''
  29. IE_NAME = u'soundcloud'
  30. _TESTS = [
  31. {
  32. u'url': u'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
  33. u'file': u'62986583.mp3',
  34. u'md5': u'ebef0a451b909710ed1d7787dddbf0d7',
  35. u'info_dict': {
  36. u"upload_date": u"20121011",
  37. 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",
  38. u"uploader": u"E.T. ExTerrestrial Music",
  39. u"title": u"Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1"
  40. }
  41. },
  42. # not streamable song
  43. {
  44. u'url': u'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
  45. u'info_dict': {
  46. u'id': u'47127627',
  47. u'ext': u'mp3',
  48. u'title': u'Goldrushed',
  49. u'uploader': u'The Royal Concept',
  50. u'upload_date': u'20120521',
  51. },
  52. u'params': {
  53. # rtmp
  54. u'skip_download': True,
  55. },
  56. },
  57. # private link
  58. {
  59. u'url': u'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
  60. u'md5': u'aa0dd32bfea9b0c5ef4f02aacd080604',
  61. u'info_dict': {
  62. u'id': u'123998367',
  63. u'ext': u'mp3',
  64. u'title': u'Youtube - Dl Test Video \'\' Ä↭',
  65. u'uploader': u'jaimeMF',
  66. u'description': u'test chars: \"\'/\\ä↭',
  67. u'upload_date': u'20131209',
  68. },
  69. },
  70. ]
  71. _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
  72. _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
  73. @classmethod
  74. def suitable(cls, url):
  75. return re.match(cls._VALID_URL, url, flags=re.VERBOSE) is not None
  76. def report_resolve(self, video_id):
  77. """Report information extraction."""
  78. self.to_screen(u'%s: Resolving id' % video_id)
  79. @classmethod
  80. def _resolv_url(cls, url):
  81. return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
  82. def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
  83. track_id = compat_str(info['id'])
  84. name = full_title or track_id
  85. if quiet:
  86. self.report_extraction(name)
  87. thumbnail = info['artwork_url']
  88. if thumbnail is not None:
  89. thumbnail = thumbnail.replace('-large', '-t500x500')
  90. ext = info.get('original_format', u'mp3')
  91. result = {
  92. 'id': track_id,
  93. 'uploader': info['user']['username'],
  94. 'upload_date': unified_strdate(info['created_at']),
  95. 'title': info['title'],
  96. 'description': info['description'],
  97. 'thumbnail': thumbnail,
  98. }
  99. if info.get('downloadable', False):
  100. # We can build a direct link to the song
  101. format_url = (
  102. u'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
  103. track_id, self._CLIENT_ID))
  104. result['formats'] = [{
  105. 'format_id': 'download',
  106. 'ext': ext,
  107. 'url': format_url,
  108. 'vcodec': 'none',
  109. }]
  110. else:
  111. # We have to retrieve the url
  112. streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
  113. 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
  114. stream_json = self._download_webpage(
  115. streams_url,
  116. track_id, u'Downloading track url')
  117. formats = []
  118. format_dict = json.loads(stream_json)
  119. for key, stream_url in format_dict.items():
  120. if key.startswith(u'http'):
  121. formats.append({
  122. 'format_id': key,
  123. 'ext': ext,
  124. 'url': stream_url,
  125. 'vcodec': 'none',
  126. })
  127. elif key.startswith(u'rtmp'):
  128. # The url doesn't have an rtmp app, we have to extract the playpath
  129. url, path = stream_url.split('mp3:', 1)
  130. formats.append({
  131. 'format_id': key,
  132. 'url': url,
  133. 'play_path': 'mp3:' + path,
  134. 'ext': ext,
  135. 'vcodec': 'none',
  136. })
  137. if not formats:
  138. # We fallback to the stream_url in the original info, this
  139. # cannot be always used, sometimes it can give an HTTP 404 error
  140. formats.append({
  141. 'format_id': u'fallback',
  142. 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
  143. 'ext': ext,
  144. 'vcodec': 'none',
  145. })
  146. def format_pref(f):
  147. if f['format_id'].startswith('http'):
  148. return 2
  149. if f['format_id'].startswith('rtmp'):
  150. return 1
  151. return 0
  152. formats.sort(key=format_pref)
  153. result['formats'] = formats
  154. return result
  155. def _real_extract(self, url):
  156. mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
  157. if mobj is None:
  158. raise ExtractorError(u'Invalid URL: %s' % url)
  159. track_id = mobj.group('track_id')
  160. token = None
  161. if track_id is not None:
  162. info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
  163. full_title = track_id
  164. elif mobj.group('widget'):
  165. query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  166. return self.url_result(query['url'][0], ie='Soundcloud')
  167. else:
  168. # extract uploader (which is in the url)
  169. uploader = mobj.group('uploader')
  170. # extract simple title (uploader + slug of song title)
  171. slug_title = mobj.group('title')
  172. token = mobj.group('token')
  173. full_title = resolve_title = '%s/%s' % (uploader, slug_title)
  174. if token:
  175. resolve_title += '/%s' % token
  176. self.report_resolve(full_title)
  177. url = 'http://soundcloud.com/%s' % resolve_title
  178. info_json_url = self._resolv_url(url)
  179. info_json = self._download_webpage(info_json_url, full_title, u'Downloading info JSON')
  180. info = json.loads(info_json)
  181. return self._extract_info_dict(info, full_title, secret_token=token)
  182. class SoundcloudSetIE(SoundcloudIE):
  183. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)(?:[?].*)?$'
  184. IE_NAME = u'soundcloud:set'
  185. # it's in tests/test_playlists.py
  186. _TESTS = []
  187. def _real_extract(self, url):
  188. mobj = re.match(self._VALID_URL, url)
  189. if mobj is None:
  190. raise ExtractorError(u'Invalid URL: %s' % url)
  191. # extract uploader (which is in the url)
  192. uploader = mobj.group(1)
  193. # extract simple title (uploader + slug of song title)
  194. slug_title = mobj.group(2)
  195. full_title = '%s/sets/%s' % (uploader, slug_title)
  196. self.report_resolve(full_title)
  197. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  198. resolv_url = self._resolv_url(url)
  199. info_json = self._download_webpage(resolv_url, full_title)
  200. info = json.loads(info_json)
  201. if 'errors' in info:
  202. for err in info['errors']:
  203. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
  204. return
  205. self.report_extraction(full_title)
  206. return {'_type': 'playlist',
  207. 'entries': [self._extract_info_dict(track) for track in info['tracks']],
  208. 'id': info['id'],
  209. 'title': info['title'],
  210. }
  211. class SoundcloudUserIE(SoundcloudIE):
  212. _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
  213. IE_NAME = u'soundcloud:user'
  214. # it's in tests/test_playlists.py
  215. _TESTS = []
  216. def _real_extract(self, url):
  217. mobj = re.match(self._VALID_URL, url)
  218. uploader = mobj.group('user')
  219. url = 'http://soundcloud.com/%s/' % uploader
  220. resolv_url = self._resolv_url(url)
  221. user_json = self._download_webpage(resolv_url, uploader,
  222. u'Downloading user info')
  223. user = json.loads(user_json)
  224. tracks = []
  225. for i in itertools.count():
  226. data = compat_urllib_parse.urlencode({'offset': i*50,
  227. 'client_id': self._CLIENT_ID,
  228. })
  229. tracks_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % user['id'] + data
  230. response = self._download_webpage(tracks_url, uploader,
  231. u'Downloading tracks page %s' % (i+1))
  232. new_tracks = json.loads(response)
  233. tracks.extend(self._extract_info_dict(track, quiet=True) for track in new_tracks)
  234. if len(new_tracks) < 50:
  235. break
  236. return {
  237. '_type': 'playlist',
  238. 'id': compat_str(user['id']),
  239. 'title': user['username'],
  240. 'entries': tracks,
  241. }