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.

293 lines
11 KiB

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