2 from __future__ import unicode_literals
11 from ..compat import (
14 compat_urllib_parse_urlencode,
25 class SoundcloudIE(InfoExtractor):
26 """Information extractor for soundcloud.com
27 To access the media, the uid of the song and a stream token
28 must be extracted from the page source and the script must make
29 a request to media.soundcloud.com/crossdomain.xml. Then
30 the media can be grabbed by requesting from an url composed
31 of the stream token and uid
34 _VALID_URL = r'''(?x)^(?:https?://)?
35 (?:(?:(?:www\.|m\.)?soundcloud\.com/
37 (?P<uploader>[\w\d-]+)/
38 (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
40 (?P<token>[^?]+?)?(?:[?].*)?$)
41 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
42 (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
43 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
46 IE_NAME = 'soundcloud'
49 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
50 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
54 'upload_date': '20121011',
55 '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',
56 'uploader': 'E.T. ExTerrestrial Music',
57 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
59 'license': 'all-rights-reserved',
64 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
68 'title': 'Goldrushed',
69 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
70 'uploader': 'The Royal Concept',
71 'upload_date': '20120521',
73 'license': 'all-rights-reserved',
77 'skip_download': True,
82 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
83 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
87 'title': 'Youtube - Dl Test Video \'\' Ä↭',
88 'uploader': 'jaimeMF',
89 'description': 'test chars: \"\'/\\ä↭',
90 'upload_date': '20131209',
92 'license': 'all-rights-reserved',
95 # private link (alt format)
97 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
98 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
102 'title': 'Youtube - Dl Test Video \'\' Ä↭',
103 'uploader': 'jaimeMF',
104 'description': 'test chars: \"\'/\\ä↭',
105 'upload_date': '20131209',
107 'license': 'all-rights-reserved',
112 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
113 'md5': '7624f2351f8a3b2e7cd51522496e7631',
117 'title': 'Bus Brakes',
118 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
119 'uploader': 'oddsamples',
120 'upload_date': '20140109',
122 'license': 'cc-by-sa',
125 # private link, downloadable format
127 'url': 'https://soundcloud.com/oriuplift/uponly-238-no-talking-wav/s-AyZUd',
128 'md5': '64a60b16e617d41d0bef032b7f55441e',
132 'title': 'Uplifting Only 238 [No Talking] (incl. Alex Feed Guestmix) (Aug 31, 2017) [wav]',
133 'description': 'md5:fa20ee0fca76a3d6df8c7e57f3715366',
134 'uploader': 'Ori Uplift Music',
135 'upload_date': '20170831',
137 'license': 'all-rights-reserved',
140 # no album art, use avatar pic for thumbnail
142 'url': 'https://soundcloud.com/garyvee/sideways-prod-mad-real',
143 'md5': '59c7872bc44e5d99b7211891664760c2',
147 'title': 'Sideways (Prod. Mad Real)',
148 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
149 'uploader': 'garyvee',
150 'upload_date': '20170226',
152 'thumbnail': r're:https?://.*\.jpg',
153 'license': 'all-rights-reserved',
156 'skip_download': True,
161 _CLIENT_ID = 'NmW1FlPaiL94ueEu7oziOWjYEzZzQDcK'
164 def _extract_urls(webpage):
165 return [m.group('url') for m in re.finditer(
166 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
169 def report_resolve(self, video_id):
170 """Report information extraction."""
171 self.to_screen('%s: Resolving id' % video_id)
174 def _resolv_url(cls, url):
175 return 'https://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
177 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
178 track_id = compat_str(info['id'])
179 name = full_title or track_id
181 self.report_extraction(name)
182 thumbnail = info.get('artwork_url') or info.get('user', {}).get('avatar_url')
183 if isinstance(thumbnail, compat_str):
184 thumbnail = thumbnail.replace('-large', '-t500x500')
187 'uploader': info.get('user', {}).get('username'),
188 'upload_date': unified_strdate(info.get('created_at')),
189 'title': info['title'],
190 'description': info.get('description'),
191 'thumbnail': thumbnail,
192 'duration': int_or_none(info.get('duration'), 1000),
193 'webpage_url': info.get('permalink_url'),
194 'license': info.get('license'),
197 query = {'client_id': self._CLIENT_ID}
198 if secret_token is not None:
199 query['secret_token'] = secret_token
200 if info.get('downloadable', False):
201 # We can build a direct link to the song
202 format_url = update_url_query(
203 'https://api.soundcloud.com/tracks/%s/download' % track_id, query)
205 'format_id': 'download',
206 'ext': info.get('original_format', 'mp3'),
212 # We have to retrieve the url
213 format_dict = self._download_json(
214 'https://api.soundcloud.com/i1/tracks/%s/streams' % track_id,
215 track_id, 'Downloading track url', query=query)
217 for key, stream_url in format_dict.items():
218 ext, abr = 'mp3', None
219 mobj = re.search(r'_([^_]+)_(\d+)_url', key)
221 ext, abr = mobj.groups()
223 if key.startswith('http'):
229 elif key.startswith('rtmp'):
230 # The url doesn't have an rtmp app, we have to extract the playpath
231 url, path = stream_url.split('mp3:', 1)
235 'play_path': 'mp3:' + path,
238 elif key.startswith('hls'):
239 stream_formats = self._extract_m3u8_formats(
240 stream_url, track_id, ext, entry_protocol='m3u8_native',
241 m3u8_id=key, fatal=False)
246 for f in stream_formats:
249 formats.extend(stream_formats)
252 # We fallback to the stream_url in the original info, this
253 # cannot be always used, sometimes it can give an HTTP 404 error
255 'format_id': 'fallback',
256 'url': update_url_query(info['stream_url'], query),
263 self._check_formats(formats, track_id)
264 self._sort_formats(formats)
265 result['formats'] = formats
269 def _real_extract(self, url):
270 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
272 raise ExtractorError('Invalid URL: %s' % url)
274 track_id = mobj.group('track_id')
276 if track_id is not None:
277 info_json_url = 'https://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
278 full_title = track_id
279 token = mobj.group('secret_token')
281 info_json_url += '&secret_token=' + token
282 elif mobj.group('player'):
283 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
284 real_url = query['url'][0]
285 # If the token is in the query of the original url we have to
287 if 'secret_token' in query:
288 real_url += '?secret_token=' + query['secret_token'][0]
289 return self.url_result(real_url)
291 # extract uploader (which is in the url)
292 uploader = mobj.group('uploader')
293 # extract simple title (uploader + slug of song title)
294 slug_title = mobj.group('title')
295 token = mobj.group('token')
296 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
298 resolve_title += '/%s' % token
300 self.report_resolve(full_title)
302 url = 'https://soundcloud.com/%s' % resolve_title
303 info_json_url = self._resolv_url(url)
304 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
306 return self._extract_info_dict(info, full_title, secret_token=token)
309 class SoundcloudPlaylistBaseIE(SoundcloudIE):
312 return compat_str(e['id']) if e.get('id') else None
314 def _extract_track_entries(self, tracks):
317 track['permalink_url'], SoundcloudIE.ie_key(),
318 video_id=self._extract_id(track))
319 for track in tracks if track.get('permalink_url')]
322 class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
323 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
324 IE_NAME = 'soundcloud:set'
326 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
329 'title': 'The Royal Concept EP',
331 'playlist_mincount': 5,
333 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
334 'only_matching': True,
337 def _real_extract(self, url):
338 mobj = re.match(self._VALID_URL, url)
340 # extract uploader (which is in the url)
341 uploader = mobj.group('uploader')
342 # extract simple title (uploader + slug of song title)
343 slug_title = mobj.group('slug_title')
344 full_title = '%s/sets/%s' % (uploader, slug_title)
345 url = 'https://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
347 token = mobj.group('token')
349 full_title += '/' + token
352 self.report_resolve(full_title)
354 resolv_url = self._resolv_url(url)
355 info = self._download_json(resolv_url, full_title)
358 msgs = (compat_str(err['error_message']) for err in info['errors'])
359 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
361 entries = self._extract_track_entries(info['tracks'])
366 'id': '%s' % info['id'],
367 'title': info['title'],
371 class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
372 _API_V2_BASE = 'https://api-v2.soundcloud.com'
374 def _extract_playlist(self, base_url, playlist_id, playlist_title):
377 'client_id': self._CLIENT_ID,
378 'linked_partitioning': '1',
381 query = COMMON_QUERY.copy()
384 next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
387 for i in itertools.count():
388 response = self._download_json(
389 next_href, playlist_id, 'Downloading track page %s' % (i + 1))
391 collection = response['collection']
393 if not isinstance(collection, list):
396 # Empty collection may be returned, in this case we proceed
397 # straight to next_href
399 def resolve_entry(candidates):
400 for cand in candidates:
401 if not isinstance(cand, dict):
403 permalink_url = url_or_none(cand.get('permalink_url'))
404 if not permalink_url:
406 return self.url_result(
408 ie=SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
409 video_id=self._extract_id(cand),
410 video_title=cand.get('title'))
413 entry = resolve_entry((e, e.get('track'), e.get('playlist')))
415 entries.append(entry)
417 next_href = response.get('next_href')
421 parsed_next_href = compat_urlparse.urlparse(response['next_href'])
422 qs = compat_urlparse.parse_qs(parsed_next_href.query)
423 qs.update(COMMON_QUERY)
424 next_href = compat_urlparse.urlunparse(
425 parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
430 'title': playlist_title,
435 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
436 _VALID_URL = r'''(?x)
438 (?:(?:www|m)\.)?soundcloud\.com/
441 (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
445 IE_NAME = 'soundcloud:user'
447 'url': 'https://soundcloud.com/soft-cell-official',
450 'title': 'Soft Cell (All)',
452 'playlist_mincount': 28,
454 'url': 'https://soundcloud.com/soft-cell-official/tracks',
457 'title': 'Soft Cell (Tracks)',
459 'playlist_mincount': 27,
461 'url': 'https://soundcloud.com/soft-cell-official/albums',
464 'title': 'Soft Cell (Albums)',
466 'playlist_mincount': 1,
468 'url': 'https://soundcloud.com/jcv246/sets',
471 'title': 'Jordi / cv (Playlists)',
473 'playlist_mincount': 2,
475 'url': 'https://soundcloud.com/jcv246/reposts',
478 'title': 'Jordi / cv (Reposts)',
480 'playlist_mincount': 6,
482 'url': 'https://soundcloud.com/clalberg/likes',
485 'title': 'clalberg (Likes)',
487 'playlist_mincount': 5,
489 'url': 'https://soundcloud.com/grynpyret/spotlight',
492 'title': 'Grynpyret (Spotlight)',
494 'playlist_mincount': 1,
498 'all': '%s/stream/users/%%s' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
499 'tracks': '%s/users/%%s/tracks' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
500 'albums': '%s/users/%%s/albums' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
501 'sets': '%s/users/%%s/playlists' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
502 'reposts': '%s/stream/users/%%s/reposts' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
503 'likes': '%s/users/%%s/likes' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
504 'spotlight': '%s/users/%%s/spotlight' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
512 'reposts': 'Reposts',
514 'spotlight': 'Spotlight',
517 def _real_extract(self, url):
518 mobj = re.match(self._VALID_URL, url)
519 uploader = mobj.group('user')
521 url = 'https://soundcloud.com/%s/' % uploader
522 resolv_url = self._resolv_url(url)
523 user = self._download_json(
524 resolv_url, uploader, 'Downloading user info')
526 resource = mobj.group('rsrc') or 'all'
528 return self._extract_playlist(
529 self._BASE_URL_MAP[resource] % user['id'], compat_str(user['id']),
530 '%s (%s)' % (user['username'], self._TITLE_MAP[resource]))
533 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
534 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
535 IE_NAME = 'soundcloud:trackstation'
537 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
540 'title': 'Track station: your-text',
542 'playlist_mincount': 47,
545 def _real_extract(self, url):
546 track_name = self._match_id(url)
548 webpage = self._download_webpage(url, track_name)
550 track_id = self._search_regex(
551 r'soundcloud:track-stations:(\d+)', webpage, 'track id')
553 return self._extract_playlist(
554 '%s/stations/soundcloud:track-stations:%s/tracks'
555 % (self._API_V2_BASE, track_id),
556 track_id, 'Track station: %s' % track_name)
559 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
560 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
561 IE_NAME = 'soundcloud:playlist'
563 'url': 'https://api.soundcloud.com/playlists/4110309',
566 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
567 'description': 're:.*?TILT Brass - Bowery Poetry Club',
572 def _real_extract(self, url):
573 mobj = re.match(self._VALID_URL, url)
574 playlist_id = mobj.group('id')
575 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
578 'client_id': self._CLIENT_ID,
580 token = mobj.group('token')
583 data_dict['secret_token'] = token
585 data = compat_urllib_parse_urlencode(data_dict)
586 data = self._download_json(
587 base_url + data, playlist_id, 'Downloading playlist')
589 entries = self._extract_track_entries(data['tracks'])
594 'title': data.get('title'),
595 'description': data.get('description'),
600 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
601 IE_NAME = 'soundcloud:search'
602 IE_DESC = 'Soundcloud search'
603 _MAX_RESULTS = float('inf')
605 'url': 'scsearch15:post-avant jazzcore',
607 'title': 'post-avant jazzcore',
609 'playlist_count': 15,
612 _SEARCH_KEY = 'scsearch'
613 _MAX_RESULTS_PER_PAGE = 200
614 _DEFAULT_RESULTS_PER_PAGE = 50
615 _API_V2_BASE = 'https://api-v2.soundcloud.com'
617 def _get_collection(self, endpoint, collection_id, **query):
619 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
620 self._MAX_RESULTS_PER_PAGE)
621 query['limit'] = limit
622 query['client_id'] = self._CLIENT_ID
623 query['linked_partitioning'] = '1'
625 data = compat_urllib_parse_urlencode(query)
626 next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
628 collected_results = 0
630 for i in itertools.count(1):
631 response = self._download_json(
632 next_url, collection_id, 'Downloading page {0}'.format(i),
633 'Unable to download API page')
635 collection = response.get('collection', [])
639 collection = list(filter(bool, collection))
640 collected_results += len(collection)
642 for item in collection:
643 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
645 if not collection or collected_results >= limit:
648 next_url = response.get('next_href')
652 def _get_n_results(self, query, n):
653 tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
654 return self.playlist_result(tracks, playlist_title=query)