2 from __future__ import unicode_literals
11 from ..compat import (
14 compat_urllib_parse_urlencode,
23 class SoundcloudIE(InfoExtractor):
24 """Information extractor for soundcloud.com
25 To access the media, the uid of the song and a stream token
26 must be extracted from the page source and the script must make
27 a request to media.soundcloud.com/crossdomain.xml. Then
28 the media can be grabbed by requesting from an url composed
29 of the stream token and uid
32 _VALID_URL = r'''(?x)^(?:https?://)?
33 (?:(?:(?:www\.|m\.)?soundcloud\.com/
34 (?P<uploader>[\w\d-]+)/
35 (?!(?:tracks|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
37 (?P<token>[^?]+?)?(?:[?].*)?$)
38 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
39 (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
40 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
43 IE_NAME = 'soundcloud'
46 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
47 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
51 'upload_date': '20121011',
52 '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',
53 'uploader': 'E.T. ExTerrestrial Music',
54 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
60 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
64 'title': 'Goldrushed',
65 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
66 'uploader': 'The Royal Concept',
67 'upload_date': '20120521',
72 'skip_download': True,
77 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
78 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
82 'title': 'Youtube - Dl Test Video \'\' Ä↭',
83 'uploader': 'jaimeMF',
84 'description': 'test chars: \"\'/\\ä↭',
85 'upload_date': '20131209',
89 # private link (alt format)
91 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
92 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
96 'title': 'Youtube - Dl Test Video \'\' Ä↭',
97 'uploader': 'jaimeMF',
98 'description': 'test chars: \"\'/\\ä↭',
99 'upload_date': '20131209',
105 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
106 'md5': '7624f2351f8a3b2e7cd51522496e7631',
110 'title': 'Bus Brakes',
111 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
112 'uploader': 'oddsamples',
113 'upload_date': '20140109',
119 _CLIENT_ID = '02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea'
120 _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
123 def _extract_urls(webpage):
124 return [m.group('url') for m in re.finditer(
125 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
128 def report_resolve(self, video_id):
129 """Report information extraction."""
130 self.to_screen('%s: Resolving id' % video_id)
133 def _resolv_url(cls, url):
134 return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
136 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
137 track_id = compat_str(info['id'])
138 name = full_title or track_id
140 self.report_extraction(name)
142 thumbnail = info['artwork_url']
143 if thumbnail is not None:
144 thumbnail = thumbnail.replace('-large', '-t500x500')
148 'uploader': info['user']['username'],
149 'upload_date': unified_strdate(info['created_at']),
150 'title': info['title'],
151 'description': info['description'],
152 'thumbnail': thumbnail,
153 'duration': int_or_none(info.get('duration'), 1000),
154 'webpage_url': info.get('permalink_url'),
157 if info.get('downloadable', False):
158 # We can build a direct link to the song
160 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
161 track_id, self._CLIENT_ID))
163 'format_id': 'download',
164 'ext': info.get('original_format', 'mp3'),
170 # We have to retrieve the url
171 streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
172 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
173 format_dict = self._download_json(
175 track_id, 'Downloading track url')
177 for key, stream_url in format_dict.items():
178 if key.startswith('http'):
185 elif key.startswith('rtmp'):
186 # The url doesn't have an rtmp app, we have to extract the playpath
187 url, path = stream_url.split('mp3:', 1)
191 'play_path': 'mp3:' + path,
197 # We fallback to the stream_url in the original info, this
198 # cannot be always used, sometimes it can give an HTTP 404 error
200 'format_id': 'fallback',
201 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
207 if f['format_id'].startswith('http'):
208 f['protocol'] = 'http'
209 if f['format_id'].startswith('rtmp'):
210 f['protocol'] = 'rtmp'
212 self._check_formats(formats, track_id)
213 self._sort_formats(formats)
214 result['formats'] = formats
218 def _real_extract(self, url):
219 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
221 raise ExtractorError('Invalid URL: %s' % url)
223 track_id = mobj.group('track_id')
225 if track_id is not None:
226 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
227 full_title = track_id
228 token = mobj.group('secret_token')
230 info_json_url += '&secret_token=' + token
231 elif mobj.group('player'):
232 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
233 real_url = query['url'][0]
234 # If the token is in the query of the original url we have to
236 if 'secret_token' in query:
237 real_url += '?secret_token=' + query['secret_token'][0]
238 return self.url_result(real_url)
240 # extract uploader (which is in the url)
241 uploader = mobj.group('uploader')
242 # extract simple title (uploader + slug of song title)
243 slug_title = mobj.group('title')
244 token = mobj.group('token')
245 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
247 resolve_title += '/%s' % token
249 self.report_resolve(full_title)
251 url = 'http://soundcloud.com/%s' % resolve_title
252 info_json_url = self._resolv_url(url)
253 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
255 return self._extract_info_dict(info, full_title, secret_token=token)
258 class SoundcloudSetIE(SoundcloudIE):
259 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
260 IE_NAME = 'soundcloud:set'
262 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
265 'title': 'The Royal Concept EP',
267 'playlist_mincount': 6,
269 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
270 'only_matching': True,
273 def _real_extract(self, url):
274 mobj = re.match(self._VALID_URL, url)
276 # extract uploader (which is in the url)
277 uploader = mobj.group('uploader')
278 # extract simple title (uploader + slug of song title)
279 slug_title = mobj.group('slug_title')
280 full_title = '%s/sets/%s' % (uploader, slug_title)
281 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
283 token = mobj.group('token')
285 full_title += '/' + token
288 self.report_resolve(full_title)
290 resolv_url = self._resolv_url(url)
291 info = self._download_json(resolv_url, full_title)
294 msgs = (compat_str(err['error_message']) for err in info['errors'])
295 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
297 entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in info['tracks']]
302 'id': '%s' % info['id'],
303 'title': info['title'],
307 class SoundcloudUserIE(SoundcloudIE):
308 _VALID_URL = r'''(?x)
310 (?:(?:www|m)\.)?soundcloud\.com/
313 (?P<rsrc>tracks|sets|reposts|likes|spotlight)
317 IE_NAME = 'soundcloud:user'
319 'url': 'https://soundcloud.com/the-akashic-chronicler',
322 'title': 'The Akashic Chronicler (All)',
324 'playlist_mincount': 111,
326 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
329 'title': 'The Akashic Chronicler (Tracks)',
331 'playlist_mincount': 50,
333 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
336 'title': 'The Akashic Chronicler (Playlists)',
338 'playlist_mincount': 3,
340 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
343 'title': 'The Akashic Chronicler (Reposts)',
345 'playlist_mincount': 7,
347 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
350 'title': 'The Akashic Chronicler (Likes)',
352 'playlist_mincount': 321,
354 'url': 'https://soundcloud.com/grynpyret/spotlight',
357 'title': 'Grynpyret (Spotlight)',
359 'playlist_mincount': 1,
362 _API_BASE = 'https://api.soundcloud.com'
363 _API_V2_BASE = 'https://api-v2.soundcloud.com'
366 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE,
367 'tracks': '%s/users/%%s/tracks' % _API_BASE,
368 'sets': '%s/users/%%s/playlists' % _API_V2_BASE,
369 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE,
370 'likes': '%s/users/%%s/likes' % _API_V2_BASE,
371 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE,
378 'reposts': 'Reposts',
380 'spotlight': 'Spotlight',
383 def _real_extract(self, url):
384 mobj = re.match(self._VALID_URL, url)
385 uploader = mobj.group('user')
387 url = 'http://soundcloud.com/%s/' % uploader
388 resolv_url = self._resolv_url(url)
389 user = self._download_json(
390 resolv_url, uploader, 'Downloading user info')
392 resource = mobj.group('rsrc') or 'all'
393 base_url = self._BASE_URL_MAP[resource] % user['id']
397 'client_id': self._CLIENT_ID,
398 'linked_partitioning': '1',
401 query = COMMON_QUERY.copy()
404 next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
407 for i in itertools.count():
408 response = self._download_json(
409 next_href, uploader, 'Downloading track page %s' % (i + 1))
411 collection = response['collection']
415 def resolve_permalink_url(candidates):
416 for cand in candidates:
417 if isinstance(cand, dict):
418 permalink_url = cand.get('permalink_url')
419 if permalink_url and permalink_url.startswith('http'):
423 permalink_url = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
425 entries.append(self.url_result(permalink_url))
427 next_href = response.get('next_href')
431 parsed_next_href = compat_urlparse.urlparse(response['next_href'])
432 qs = compat_urlparse.parse_qs(parsed_next_href.query)
433 qs.update(COMMON_QUERY)
434 next_href = compat_urlparse.urlunparse(
435 parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
439 'id': compat_str(user['id']),
440 'title': '%s (%s)' % (user['username'], self._TITLE_MAP[resource]),
445 class SoundcloudPlaylistIE(SoundcloudIE):
446 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
447 IE_NAME = 'soundcloud:playlist'
449 'url': 'http://api.soundcloud.com/playlists/4110309',
452 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
453 'description': 're:.*?TILT Brass - Bowery Poetry Club',
458 def _real_extract(self, url):
459 mobj = re.match(self._VALID_URL, url)
460 playlist_id = mobj.group('id')
461 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
464 'client_id': self._CLIENT_ID,
466 token = mobj.group('token')
469 data_dict['secret_token'] = token
471 data = compat_urllib_parse_urlencode(data_dict)
472 data = self._download_json(
473 base_url + data, playlist_id, 'Downloading playlist')
475 entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in data['tracks']]
480 'title': data.get('title'),
481 'description': data.get('description'),
486 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
487 IE_NAME = 'soundcloud:search'
488 IE_DESC = 'Soundcloud search'
489 _MAX_RESULTS = float('inf')
491 'url': 'scsearch15:post-avant jazzcore',
493 'title': 'post-avant jazzcore',
495 'playlist_count': 15,
498 _SEARCH_KEY = 'scsearch'
499 _MAX_RESULTS_PER_PAGE = 200
500 _DEFAULT_RESULTS_PER_PAGE = 50
501 _API_V2_BASE = 'https://api-v2.soundcloud.com'
503 def _get_collection(self, endpoint, collection_id, **query):
505 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
506 self._MAX_RESULTS_PER_PAGE)
507 query['limit'] = limit
508 query['client_id'] = self._CLIENT_ID
509 query['linked_partitioning'] = '1'
511 data = compat_urllib_parse_urlencode(query)
512 next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
514 collected_results = 0
516 for i in itertools.count(1):
517 response = self._download_json(
518 next_url, collection_id, 'Downloading page {0}'.format(i),
519 'Unable to download API page')
521 collection = response.get('collection', [])
525 collection = list(filter(bool, collection))
526 collected_results += len(collection)
528 for item in collection:
529 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
531 if not collection or collected_results >= limit:
534 next_url = response.get('next_href')
538 def _get_n_results(self, query, n):
539 tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
540 return self.playlist_result(tracks, playlist_title=query)