2 from __future__ import unicode_literals
7 from .common import InfoExtractor
19 class SoundcloudIE(InfoExtractor):
20 """Information extractor for soundcloud.com
21 To access the media, the uid of the song and a stream token
22 must be extracted from the page source and the script must make
23 a request to media.soundcloud.com/crossdomain.xml. Then
24 the media can be grabbed by requesting from an url composed
25 of the stream token and uid
28 _VALID_URL = r'''(?x)^(?:https?://)?
29 (?:(?:(?:www\.|m\.)?soundcloud\.com/
30 (?P<uploader>[\w\d-]+)/
31 (?!sets/|likes/?(?:$|[?#]))
33 (?P<token>[^?]+?)?(?:[?].*)?$)
34 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
35 (?:/?\?secret_token=(?P<secret_token>[^&]+?))?$)
36 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
39 IE_NAME = 'soundcloud'
42 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
43 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
47 'upload_date': '20121011',
48 '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',
49 'uploader': 'E.T. ExTerrestrial Music',
50 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
56 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
60 'title': 'Goldrushed',
61 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
62 'uploader': 'The Royal Concept',
63 'upload_date': '20120521',
68 'skip_download': True,
73 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
74 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
78 'title': 'Youtube - Dl Test Video \'\' Ä↭',
79 'uploader': 'jaimeMF',
80 'description': 'test chars: \"\'/\\ä↭',
81 'upload_date': '20131209',
85 # private link (alt format)
87 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
88 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
92 'title': 'Youtube - Dl Test Video \'\' Ä↭',
93 'uploader': 'jaimeMF',
94 'description': 'test chars: \"\'/\\ä↭',
95 'upload_date': '20131209',
101 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
102 'md5': '7624f2351f8a3b2e7cd51522496e7631',
106 'title': 'Bus Brakes',
107 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
108 'uploader': 'oddsamples',
109 'upload_date': '20140109',
115 _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
116 _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
118 def report_resolve(self, video_id):
119 """Report information extraction."""
120 self.to_screen('%s: Resolving id' % video_id)
123 def _resolv_url(cls, url):
124 return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
126 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
127 track_id = compat_str(info['id'])
128 name = full_title or track_id
130 self.report_extraction(name)
132 thumbnail = info['artwork_url']
133 if thumbnail is not None:
134 thumbnail = thumbnail.replace('-large', '-t500x500')
138 'uploader': info['user']['username'],
139 'upload_date': unified_strdate(info['created_at']),
140 'title': info['title'],
141 'description': info['description'],
142 'thumbnail': thumbnail,
143 'duration': int_or_none(info.get('duration'), 1000),
146 if info.get('downloadable', False):
147 # We can build a direct link to the song
149 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
150 track_id, self._CLIENT_ID))
152 'format_id': 'download',
153 'ext': info.get('original_format', 'mp3'),
159 # We have to retrieve the url
160 streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
161 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
162 format_dict = self._download_json(
164 track_id, 'Downloading track url')
166 for key, stream_url in format_dict.items():
167 if key.startswith('http'):
174 elif key.startswith('rtmp'):
175 # The url doesn't have an rtmp app, we have to extract the playpath
176 url, path = stream_url.split('mp3:', 1)
180 'play_path': 'mp3:' + path,
186 # We fallback to the stream_url in the original info, this
187 # cannot be always used, sometimes it can give an HTTP 404 error
189 'format_id': 'fallback',
190 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
196 if f['format_id'].startswith('http'):
197 f['protocol'] = 'http'
198 if f['format_id'].startswith('rtmp'):
199 f['protocol'] = 'rtmp'
201 self._sort_formats(formats)
202 result['formats'] = formats
206 def _real_extract(self, url):
207 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
209 raise ExtractorError('Invalid URL: %s' % url)
211 track_id = mobj.group('track_id')
213 if track_id is not None:
214 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
215 full_title = track_id
216 token = mobj.group('secret_token')
218 info_json_url += "&secret_token=" + token
219 elif mobj.group('player'):
220 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
221 return self.url_result(query['url'][0])
223 # extract uploader (which is in the url)
224 uploader = mobj.group('uploader')
225 # extract simple title (uploader + slug of song title)
226 slug_title = mobj.group('title')
227 token = mobj.group('token')
228 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
230 resolve_title += '/%s' % token
232 self.report_resolve(full_title)
234 url = 'http://soundcloud.com/%s' % resolve_title
235 info_json_url = self._resolv_url(url)
236 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
238 return self._extract_info_dict(info, full_title, secret_token=token)
241 class SoundcloudSetIE(SoundcloudIE):
242 _VALID_URL = r'https?://(?:www\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
243 IE_NAME = 'soundcloud:set'
245 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
247 'title': 'The Royal Concept EP',
249 'playlist_mincount': 6,
252 def _real_extract(self, url):
253 mobj = re.match(self._VALID_URL, url)
255 # extract uploader (which is in the url)
256 uploader = mobj.group('uploader')
257 # extract simple title (uploader + slug of song title)
258 slug_title = mobj.group('slug_title')
259 full_title = '%s/sets/%s' % (uploader, slug_title)
260 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
262 token = mobj.group('token')
264 full_title += '/' + token
267 self.report_resolve(full_title)
269 resolv_url = self._resolv_url(url)
270 info = self._download_json(resolv_url, full_title)
273 for err in info['errors']:
274 self._downloader.report_error('unable to download video webpage: %s' % compat_str(err['error_message']))
279 'entries': [self._extract_info_dict(track, secret_token=token) for track in info['tracks']],
281 'title': info['title'],
285 class SoundcloudUserIE(SoundcloudIE):
286 _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)/?((?P<rsrc>tracks|likes)/?)?(\?.*)?$'
287 IE_NAME = 'soundcloud:user'
289 'url': 'https://soundcloud.com/the-concept-band',
292 'title': 'The Royal Concept',
294 'playlist_mincount': 12
296 'url': 'https://soundcloud.com/the-concept-band/likes',
299 'title': 'The Royal Concept',
301 'playlist_mincount': 1,
304 def _real_extract(self, url):
305 mobj = re.match(self._VALID_URL, url)
306 uploader = mobj.group('user')
307 resource = mobj.group('rsrc')
310 elif resource == 'likes':
311 resource = 'favorites'
313 url = 'http://soundcloud.com/%s/' % uploader
314 resolv_url = self._resolv_url(url)
315 user = self._download_json(
316 resolv_url, uploader, 'Downloading user info')
317 base_url = 'http://api.soundcloud.com/users/%s/%s.json?' % (uploader, resource)
320 for i in itertools.count():
321 data = compat_urllib_parse.urlencode({
324 'client_id': self._CLIENT_ID,
326 new_entries = self._download_json(
327 base_url + data, uploader, 'Downloading track page %s' % (i + 1))
328 if len(new_entries) == 0:
329 self.to_screen('%s: End page received' % uploader)
331 entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
335 'id': compat_str(user['id']),
336 'title': user['username'],
341 class SoundcloudPlaylistIE(SoundcloudIE):
342 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
343 IE_NAME = 'soundcloud:playlist'
345 'url': 'http://api.soundcloud.com/playlists/4110309',
348 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
349 'description': 're:.*?TILT Brass - Bowery Poetry Club',
354 def _real_extract(self, url):
355 mobj = re.match(self._VALID_URL, url)
356 playlist_id = mobj.group('id')
357 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
360 'client_id': self._CLIENT_ID,
362 token = mobj.group('token')
365 data_dict['secret_token'] = token
367 data = compat_urllib_parse.urlencode(data_dict)
368 data = self._download_json(
369 base_url + data, playlist_id, 'Downloading playlist')
372 self._extract_info_dict(t, quiet=True, secret_token=token)
373 for t in data['tracks']]
378 'title': data.get('title'),
379 'description': data.get('description'),