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/
35 (?P<uploader>[\w\d-]+)/
36 (?!(?:tracks|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
38 (?P<token>[^?]+?)?(?:[?].*)?$)
39 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
40 (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
41 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
44 IE_NAME = 'soundcloud'
47 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
48 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
52 'upload_date': '20121011',
53 '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',
54 'uploader': 'E.T. ExTerrestrial Music',
55 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
57 'license': 'all-rights-reserved',
62 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
66 'title': 'Goldrushed',
67 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
68 'uploader': 'The Royal Concept',
69 'upload_date': '20120521',
71 'license': 'all-rights-reserved',
75 'skip_download': True,
80 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
81 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
85 'title': 'Youtube - Dl Test Video \'\' Ä↭',
86 'uploader': 'jaimeMF',
87 'description': 'test chars: \"\'/\\ä↭',
88 'upload_date': '20131209',
90 'license': 'all-rights-reserved',
93 # private link (alt format)
95 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
96 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
100 'title': 'Youtube - Dl Test Video \'\' Ä↭',
101 'uploader': 'jaimeMF',
102 'description': 'test chars: \"\'/\\ä↭',
103 'upload_date': '20131209',
105 'license': 'all-rights-reserved',
110 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
111 'md5': '7624f2351f8a3b2e7cd51522496e7631',
115 'title': 'Bus Brakes',
116 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
117 'uploader': 'oddsamples',
118 'upload_date': '20140109',
120 'license': 'cc-by-sa',
125 _CLIENT_ID = 'JlZIsxg2hY5WnBgtn3jfS0UYCl0K8DOg'
126 _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
129 def _extract_urls(webpage):
130 return [m.group('url') for m in re.finditer(
131 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
134 def report_resolve(self, video_id):
135 """Report information extraction."""
136 self.to_screen('%s: Resolving id' % video_id)
139 def _resolv_url(cls, url):
140 return 'https://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
142 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
143 track_id = compat_str(info['id'])
144 name = full_title or track_id
146 self.report_extraction(name)
147 thumbnail = info.get('artwork_url')
148 if isinstance(thumbnail, compat_str):
149 thumbnail = thumbnail.replace('-large', '-t500x500')
153 'uploader': info.get('user', {}).get('username'),
154 'upload_date': unified_strdate(info.get('created_at')),
155 'title': info['title'],
156 'description': info.get('description'),
157 'thumbnail': thumbnail,
158 'duration': int_or_none(info.get('duration'), 1000),
159 'webpage_url': info.get('permalink_url'),
160 'license': info.get('license'),
163 if info.get('downloadable', False):
164 # We can build a direct link to the song
166 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
167 track_id, self._CLIENT_ID))
169 'format_id': 'download',
170 'ext': info.get('original_format', 'mp3'),
176 # We have to retrieve the url
177 format_dict = self._download_json(
178 'https://api.soundcloud.com/i1/tracks/%s/streams' % track_id,
179 track_id, 'Downloading track url', query={
180 'client_id': self._CLIENT_ID,
181 'secret_token': secret_token,
184 for key, stream_url in format_dict.items():
185 abr = int_or_none(self._search_regex(
186 r'_(\d+)_url', key, 'audio bitrate', default=None))
187 if key.startswith('http'):
193 elif key.startswith('rtmp'):
194 # The url doesn't have an rtmp app, we have to extract the playpath
195 url, path = stream_url.split('mp3:', 1)
199 'play_path': 'mp3:' + path,
202 elif key.startswith('hls'):
203 stream_formats = self._extract_m3u8_formats(
204 stream_url, track_id, 'mp3', entry_protocol='m3u8_native',
205 m3u8_id=key, fatal=False)
209 for f in stream_formats:
212 formats.extend(stream_formats)
215 # We fallback to the stream_url in the original info, this
216 # cannot be always used, sometimes it can give an HTTP 404 error
218 'format_id': 'fallback',
219 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
226 self._check_formats(formats, track_id)
227 self._sort_formats(formats)
228 result['formats'] = formats
232 def _real_extract(self, url):
233 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
235 raise ExtractorError('Invalid URL: %s' % url)
237 track_id = mobj.group('track_id')
239 if track_id is not None:
240 info_json_url = 'https://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
241 full_title = track_id
242 token = mobj.group('secret_token')
244 info_json_url += '&secret_token=' + token
245 elif mobj.group('player'):
246 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
247 real_url = query['url'][0]
248 # If the token is in the query of the original url we have to
250 if 'secret_token' in query:
251 real_url += '?secret_token=' + query['secret_token'][0]
252 return self.url_result(real_url)
254 # extract uploader (which is in the url)
255 uploader = mobj.group('uploader')
256 # extract simple title (uploader + slug of song title)
257 slug_title = mobj.group('title')
258 token = mobj.group('token')
259 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
261 resolve_title += '/%s' % token
263 self.report_resolve(full_title)
265 url = 'https://soundcloud.com/%s' % resolve_title
266 info_json_url = self._resolv_url(url)
267 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
269 return self._extract_info_dict(info, full_title, secret_token=token)
272 class SoundcloudPlaylistBaseIE(SoundcloudIE):
275 return compat_str(e['id']) if e.get('id') else None
277 def _extract_track_entries(self, tracks):
280 track['permalink_url'], SoundcloudIE.ie_key(),
281 video_id=self._extract_id(track))
282 for track in tracks if track.get('permalink_url')]
285 class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
286 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
287 IE_NAME = 'soundcloud:set'
289 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
292 'title': 'The Royal Concept EP',
294 'playlist_mincount': 5,
296 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
297 'only_matching': True,
300 def _real_extract(self, url):
301 mobj = re.match(self._VALID_URL, url)
303 # extract uploader (which is in the url)
304 uploader = mobj.group('uploader')
305 # extract simple title (uploader + slug of song title)
306 slug_title = mobj.group('slug_title')
307 full_title = '%s/sets/%s' % (uploader, slug_title)
308 url = 'https://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
310 token = mobj.group('token')
312 full_title += '/' + token
315 self.report_resolve(full_title)
317 resolv_url = self._resolv_url(url)
318 info = self._download_json(resolv_url, full_title)
321 msgs = (compat_str(err['error_message']) for err in info['errors'])
322 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
324 entries = self._extract_track_entries(info['tracks'])
329 'id': '%s' % info['id'],
330 'title': info['title'],
334 class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
335 _API_BASE = 'https://api.soundcloud.com'
336 _API_V2_BASE = 'https://api-v2.soundcloud.com'
338 def _extract_playlist(self, base_url, playlist_id, playlist_title):
341 'client_id': self._CLIENT_ID,
342 'linked_partitioning': '1',
345 query = COMMON_QUERY.copy()
348 next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
351 for i in itertools.count():
352 response = self._download_json(
353 next_href, playlist_id, 'Downloading track page %s' % (i + 1))
355 collection = response['collection']
359 def resolve_permalink_url(candidates):
360 for cand in candidates:
361 if isinstance(cand, dict):
362 permalink_url = cand.get('permalink_url')
363 entry_id = self._extract_id(cand)
364 if permalink_url and permalink_url.startswith('http'):
365 return permalink_url, entry_id
368 permalink_url, entry_id = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
370 entries.append(self.url_result(permalink_url, video_id=entry_id))
372 next_href = response.get('next_href')
376 parsed_next_href = compat_urlparse.urlparse(response['next_href'])
377 qs = compat_urlparse.parse_qs(parsed_next_href.query)
378 qs.update(COMMON_QUERY)
379 next_href = compat_urlparse.urlunparse(
380 parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
385 'title': playlist_title,
390 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
391 _VALID_URL = r'''(?x)
393 (?:(?:www|m)\.)?soundcloud\.com/
396 (?P<rsrc>tracks|sets|reposts|likes|spotlight)
400 IE_NAME = 'soundcloud:user'
402 'url': 'https://soundcloud.com/the-akashic-chronicler',
405 'title': 'The Akashic Chronicler (All)',
407 'playlist_mincount': 74,
409 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
412 'title': 'The Akashic Chronicler (Tracks)',
414 'playlist_mincount': 37,
416 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
419 'title': 'The Akashic Chronicler (Playlists)',
421 'playlist_mincount': 2,
423 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
426 'title': 'The Akashic Chronicler (Reposts)',
428 'playlist_mincount': 7,
430 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
433 'title': 'The Akashic Chronicler (Likes)',
435 'playlist_mincount': 321,
437 'url': 'https://soundcloud.com/grynpyret/spotlight',
440 'title': 'Grynpyret (Spotlight)',
442 'playlist_mincount': 1,
446 'all': '%s/profile/soundcloud:users:%%s' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
447 'tracks': '%s/users/%%s/tracks' % SoundcloudPagedPlaylistBaseIE._API_BASE,
448 'sets': '%s/users/%%s/playlists' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
449 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
450 'likes': '%s/users/%%s/likes' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
451 'spotlight': '%s/users/%%s/spotlight' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
458 'reposts': 'Reposts',
460 'spotlight': 'Spotlight',
463 def _real_extract(self, url):
464 mobj = re.match(self._VALID_URL, url)
465 uploader = mobj.group('user')
467 url = 'https://soundcloud.com/%s/' % uploader
468 resolv_url = self._resolv_url(url)
469 user = self._download_json(
470 resolv_url, uploader, 'Downloading user info')
472 resource = mobj.group('rsrc') or 'all'
474 return self._extract_playlist(
475 self._BASE_URL_MAP[resource] % user['id'], compat_str(user['id']),
476 '%s (%s)' % (user['username'], self._TITLE_MAP[resource]))
479 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
480 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
481 IE_NAME = 'soundcloud:trackstation'
483 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
486 'title': 'Track station: your-text',
488 'playlist_mincount': 47,
491 def _real_extract(self, url):
492 track_name = self._match_id(url)
494 webpage = self._download_webpage(url, track_name)
496 track_id = self._search_regex(
497 r'soundcloud:track-stations:(\d+)', webpage, 'track id')
499 return self._extract_playlist(
500 '%s/stations/soundcloud:track-stations:%s/tracks'
501 % (self._API_V2_BASE, track_id),
502 track_id, 'Track station: %s' % track_name)
505 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
506 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
507 IE_NAME = 'soundcloud:playlist'
509 'url': 'https://api.soundcloud.com/playlists/4110309',
512 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
513 'description': 're:.*?TILT Brass - Bowery Poetry Club',
518 def _real_extract(self, url):
519 mobj = re.match(self._VALID_URL, url)
520 playlist_id = mobj.group('id')
521 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
524 'client_id': self._CLIENT_ID,
526 token = mobj.group('token')
529 data_dict['secret_token'] = token
531 data = compat_urllib_parse_urlencode(data_dict)
532 data = self._download_json(
533 base_url + data, playlist_id, 'Downloading playlist')
535 entries = self._extract_track_entries(data['tracks'])
540 'title': data.get('title'),
541 'description': data.get('description'),
546 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
547 IE_NAME = 'soundcloud:search'
548 IE_DESC = 'Soundcloud search'
549 _MAX_RESULTS = float('inf')
551 'url': 'scsearch15:post-avant jazzcore',
553 'title': 'post-avant jazzcore',
555 'playlist_count': 15,
558 _SEARCH_KEY = 'scsearch'
559 _MAX_RESULTS_PER_PAGE = 200
560 _DEFAULT_RESULTS_PER_PAGE = 50
561 _API_V2_BASE = 'https://api-v2.soundcloud.com'
563 def _get_collection(self, endpoint, collection_id, **query):
565 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
566 self._MAX_RESULTS_PER_PAGE)
567 query['limit'] = limit
568 query['client_id'] = self._CLIENT_ID
569 query['linked_partitioning'] = '1'
571 data = compat_urllib_parse_urlencode(query)
572 next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
574 collected_results = 0
576 for i in itertools.count(1):
577 response = self._download_json(
578 next_url, collection_id, 'Downloading page {0}'.format(i),
579 'Unable to download API page')
581 collection = response.get('collection', [])
585 collection = list(filter(bool, collection))
586 collected_results += len(collection)
588 for item in collection:
589 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
591 if not collection or collected_results >= limit:
594 next_url = response.get('next_href')
598 def _get_n_results(self, query, n):
599 tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
600 return self.playlist_result(tracks, playlist_title=query)