2 from __future__ import unicode_literals
11 from ..compat import (
14 compat_urllib_parse_urlencode,
26 class SoundcloudIE(InfoExtractor):
27 """Information extractor for soundcloud.com
28 To access the media, the uid of the song and a stream token
29 must be extracted from the page source and the script must make
30 a request to media.soundcloud.com/crossdomain.xml. Then
31 the media can be grabbed by requesting from an url composed
32 of the stream token and uid
35 _VALID_URL = r'''(?x)^(?:https?://)?
36 (?:(?:(?:www\.|m\.)?soundcloud\.com/
38 (?P<uploader>[\w\d-]+)/
39 (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
41 (?P<token>[^?]+?)?(?:[?].*)?$)
42 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
43 (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
44 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
47 IE_NAME = 'soundcloud'
50 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
51 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
55 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
56 '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',
57 'uploader': 'E.T. ExTerrestrial Music',
58 'timestamp': 1349920598,
59 'upload_date': '20121011',
61 'license': 'all-rights-reserved',
70 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
74 'title': 'Goldrushed',
75 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
76 'uploader': 'The Royal Concept',
77 'timestamp': 1337635207,
78 'upload_date': '20120521',
80 'license': 'all-rights-reserved',
88 'skip_download': True,
93 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
94 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
98 'title': 'Youtube - Dl Test Video \'\' Ä↭',
99 'description': 'test chars: \"\'/\\ä↭',
100 'uploader': 'jaimeMF',
101 'timestamp': 1386604920,
102 'upload_date': '20131209',
104 'license': 'all-rights-reserved',
107 'comment_count': int,
111 # private link (alt format)
113 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
114 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
118 'title': 'Youtube - Dl Test Video \'\' Ä↭',
119 'description': 'test chars: \"\'/\\ä↭',
120 'uploader': 'jaimeMF',
121 'timestamp': 1386604920,
122 'upload_date': '20131209',
124 'license': 'all-rights-reserved',
127 'comment_count': int,
133 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
134 'md5': '7624f2351f8a3b2e7cd51522496e7631',
138 'title': 'Bus Brakes',
139 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
140 'uploader': 'oddsamples',
141 'timestamp': 1389232924,
142 'upload_date': '20140109',
144 'license': 'cc-by-sa',
147 'comment_count': int,
151 # private link, downloadable format
153 'url': 'https://soundcloud.com/oriuplift/uponly-238-no-talking-wav/s-AyZUd',
154 'md5': '64a60b16e617d41d0bef032b7f55441e',
158 'title': 'Uplifting Only 238 [No Talking] (incl. Alex Feed Guestmix) (Aug 31, 2017) [wav]',
159 'description': 'md5:fa20ee0fca76a3d6df8c7e57f3715366',
160 'uploader': 'Ori Uplift Music',
161 'timestamp': 1504206263,
162 'upload_date': '20170831',
164 'license': 'all-rights-reserved',
167 'comment_count': int,
171 # no album art, use avatar pic for thumbnail
173 'url': 'https://soundcloud.com/garyvee/sideways-prod-mad-real',
174 'md5': '59c7872bc44e5d99b7211891664760c2',
178 'title': 'Sideways (Prod. Mad Real)',
179 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
180 'uploader': 'garyvee',
181 'timestamp': 1488152409,
182 'upload_date': '20170226',
184 'thumbnail': r're:https?://.*\.jpg',
185 'license': 'all-rights-reserved',
188 'comment_count': int,
192 'skip_download': True,
197 _CLIENT_ID = 'NmW1FlPaiL94ueEu7oziOWjYEzZzQDcK'
200 def _extract_urls(webpage):
201 return [m.group('url') for m in re.finditer(
202 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
205 def report_resolve(self, video_id):
206 """Report information extraction."""
207 self.to_screen('%s: Resolving id' % video_id)
210 def _resolv_url(cls, url):
211 return 'https://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
213 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
214 track_id = compat_str(info['id'])
215 title = info['title']
216 name = full_title or track_id
218 self.report_extraction(name)
219 thumbnail = info.get('artwork_url') or info.get('user', {}).get('avatar_url')
220 if isinstance(thumbnail, compat_str):
221 thumbnail = thumbnail.replace('-large', '-t500x500')
222 username = try_get(info, lambda x: x['user']['username'], compat_str)
224 def extract_count(key):
225 return int_or_none(info.get('%s_count' % key))
229 'uploader': username,
230 'timestamp': unified_timestamp(info.get('created_at')),
232 'description': info.get('description'),
233 'thumbnail': thumbnail,
234 'duration': int_or_none(info.get('duration'), 1000),
235 'webpage_url': info.get('permalink_url'),
236 'license': info.get('license'),
237 'view_count': extract_count('playback'),
238 'like_count': extract_count('favoritings'),
239 'comment_count': extract_count('comment'),
240 'repost_count': extract_count('reposts'),
241 'genre': info.get('genre'),
244 query = {'client_id': self._CLIENT_ID}
245 if secret_token is not None:
246 query['secret_token'] = secret_token
247 if info.get('downloadable', False):
248 # We can build a direct link to the song
249 format_url = update_url_query(
250 'https://api.soundcloud.com/tracks/%s/download' % track_id, query)
252 'format_id': 'download',
253 'ext': info.get('original_format', 'mp3'),
259 # We have to retrieve the url
260 format_dict = self._download_json(
261 'https://api.soundcloud.com/i1/tracks/%s/streams' % track_id,
262 track_id, 'Downloading track url', query=query)
264 for key, stream_url in format_dict.items():
265 ext, abr = 'mp3', None
266 mobj = re.search(r'_([^_]+)_(\d+)_url', key)
268 ext, abr = mobj.groups()
270 if key.startswith('http'):
276 elif key.startswith('rtmp'):
277 # The url doesn't have an rtmp app, we have to extract the playpath
278 url, path = stream_url.split('mp3:', 1)
282 'play_path': 'mp3:' + path,
285 elif key.startswith('hls'):
286 stream_formats = self._extract_m3u8_formats(
287 stream_url, track_id, ext, entry_protocol='m3u8_native',
288 m3u8_id=key, fatal=False)
293 for f in stream_formats:
296 formats.extend(stream_formats)
299 # We fallback to the stream_url in the original info, this
300 # cannot be always used, sometimes it can give an HTTP 404 error
302 'format_id': 'fallback',
303 'url': update_url_query(info['stream_url'], query),
310 self._check_formats(formats, track_id)
311 self._sort_formats(formats)
312 result['formats'] = formats
316 def _real_extract(self, url):
317 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
319 raise ExtractorError('Invalid URL: %s' % url)
321 track_id = mobj.group('track_id')
323 if track_id is not None:
324 info_json_url = 'https://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
325 full_title = track_id
326 token = mobj.group('secret_token')
328 info_json_url += '&secret_token=' + token
329 elif mobj.group('player'):
330 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
331 real_url = query['url'][0]
332 # If the token is in the query of the original url we have to
334 if 'secret_token' in query:
335 real_url += '?secret_token=' + query['secret_token'][0]
336 return self.url_result(real_url)
338 # extract uploader (which is in the url)
339 uploader = mobj.group('uploader')
340 # extract simple title (uploader + slug of song title)
341 slug_title = mobj.group('title')
342 token = mobj.group('token')
343 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
345 resolve_title += '/%s' % token
347 self.report_resolve(full_title)
349 url = 'https://soundcloud.com/%s' % resolve_title
350 info_json_url = self._resolv_url(url)
351 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
353 return self._extract_info_dict(info, full_title, secret_token=token)
356 class SoundcloudPlaylistBaseIE(SoundcloudIE):
359 return compat_str(e['id']) if e.get('id') else None
361 def _extract_track_entries(self, tracks):
364 track['permalink_url'], SoundcloudIE.ie_key(),
365 video_id=self._extract_id(track))
366 for track in tracks if track.get('permalink_url')]
369 class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
370 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
371 IE_NAME = 'soundcloud:set'
373 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
376 'title': 'The Royal Concept EP',
378 'playlist_mincount': 5,
380 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
381 'only_matching': True,
384 def _real_extract(self, url):
385 mobj = re.match(self._VALID_URL, url)
387 # extract uploader (which is in the url)
388 uploader = mobj.group('uploader')
389 # extract simple title (uploader + slug of song title)
390 slug_title = mobj.group('slug_title')
391 full_title = '%s/sets/%s' % (uploader, slug_title)
392 url = 'https://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
394 token = mobj.group('token')
396 full_title += '/' + token
399 self.report_resolve(full_title)
401 resolv_url = self._resolv_url(url)
402 info = self._download_json(resolv_url, full_title)
405 msgs = (compat_str(err['error_message']) for err in info['errors'])
406 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
408 entries = self._extract_track_entries(info['tracks'])
413 'id': '%s' % info['id'],
414 'title': info['title'],
418 class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
419 _API_V2_BASE = 'https://api-v2.soundcloud.com'
421 def _extract_playlist(self, base_url, playlist_id, playlist_title):
424 'client_id': self._CLIENT_ID,
425 'linked_partitioning': '1',
428 query = COMMON_QUERY.copy()
431 next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
434 for i in itertools.count():
435 response = self._download_json(
436 next_href, playlist_id, 'Downloading track page %s' % (i + 1))
438 collection = response['collection']
440 if not isinstance(collection, list):
443 # Empty collection may be returned, in this case we proceed
444 # straight to next_href
446 def resolve_entry(candidates):
447 for cand in candidates:
448 if not isinstance(cand, dict):
450 permalink_url = url_or_none(cand.get('permalink_url'))
451 if not permalink_url:
453 return self.url_result(
455 ie=SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
456 video_id=self._extract_id(cand),
457 video_title=cand.get('title'))
460 entry = resolve_entry((e, e.get('track'), e.get('playlist')))
462 entries.append(entry)
464 next_href = response.get('next_href')
468 parsed_next_href = compat_urlparse.urlparse(response['next_href'])
469 qs = compat_urlparse.parse_qs(parsed_next_href.query)
470 qs.update(COMMON_QUERY)
471 next_href = compat_urlparse.urlunparse(
472 parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
477 'title': playlist_title,
482 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
483 _VALID_URL = r'''(?x)
485 (?:(?:www|m)\.)?soundcloud\.com/
488 (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
492 IE_NAME = 'soundcloud:user'
494 'url': 'https://soundcloud.com/soft-cell-official',
497 'title': 'Soft Cell (All)',
499 'playlist_mincount': 28,
501 'url': 'https://soundcloud.com/soft-cell-official/tracks',
504 'title': 'Soft Cell (Tracks)',
506 'playlist_mincount': 27,
508 'url': 'https://soundcloud.com/soft-cell-official/albums',
511 'title': 'Soft Cell (Albums)',
513 'playlist_mincount': 1,
515 'url': 'https://soundcloud.com/jcv246/sets',
518 'title': 'Jordi / cv (Playlists)',
520 'playlist_mincount': 2,
522 'url': 'https://soundcloud.com/jcv246/reposts',
525 'title': 'Jordi / cv (Reposts)',
527 'playlist_mincount': 6,
529 'url': 'https://soundcloud.com/clalberg/likes',
532 'title': 'clalberg (Likes)',
534 'playlist_mincount': 5,
536 'url': 'https://soundcloud.com/grynpyret/spotlight',
539 'title': 'Grynpyret (Spotlight)',
541 'playlist_mincount': 1,
545 'all': '%s/stream/users/%%s' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
546 'tracks': '%s/users/%%s/tracks' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
547 'albums': '%s/users/%%s/albums' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
548 'sets': '%s/users/%%s/playlists' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
549 'reposts': '%s/stream/users/%%s/reposts' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
550 'likes': '%s/users/%%s/likes' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
551 'spotlight': '%s/users/%%s/spotlight' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
559 'reposts': 'Reposts',
561 'spotlight': 'Spotlight',
564 def _real_extract(self, url):
565 mobj = re.match(self._VALID_URL, url)
566 uploader = mobj.group('user')
568 url = 'https://soundcloud.com/%s/' % uploader
569 resolv_url = self._resolv_url(url)
570 user = self._download_json(
571 resolv_url, uploader, 'Downloading user info')
573 resource = mobj.group('rsrc') or 'all'
575 return self._extract_playlist(
576 self._BASE_URL_MAP[resource] % user['id'], compat_str(user['id']),
577 '%s (%s)' % (user['username'], self._TITLE_MAP[resource]))
580 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
581 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
582 IE_NAME = 'soundcloud:trackstation'
584 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
587 'title': 'Track station: your-text',
589 'playlist_mincount': 47,
592 def _real_extract(self, url):
593 track_name = self._match_id(url)
595 webpage = self._download_webpage(url, track_name)
597 track_id = self._search_regex(
598 r'soundcloud:track-stations:(\d+)', webpage, 'track id')
600 return self._extract_playlist(
601 '%s/stations/soundcloud:track-stations:%s/tracks'
602 % (self._API_V2_BASE, track_id),
603 track_id, 'Track station: %s' % track_name)
606 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
607 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
608 IE_NAME = 'soundcloud:playlist'
610 'url': 'https://api.soundcloud.com/playlists/4110309',
613 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
614 'description': 're:.*?TILT Brass - Bowery Poetry Club',
619 def _real_extract(self, url):
620 mobj = re.match(self._VALID_URL, url)
621 playlist_id = mobj.group('id')
622 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
625 'client_id': self._CLIENT_ID,
627 token = mobj.group('token')
630 data_dict['secret_token'] = token
632 data = compat_urllib_parse_urlencode(data_dict)
633 data = self._download_json(
634 base_url + data, playlist_id, 'Downloading playlist')
636 entries = self._extract_track_entries(data['tracks'])
641 'title': data.get('title'),
642 'description': data.get('description'),
647 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
648 IE_NAME = 'soundcloud:search'
649 IE_DESC = 'Soundcloud search'
650 _MAX_RESULTS = float('inf')
652 'url': 'scsearch15:post-avant jazzcore',
654 'title': 'post-avant jazzcore',
656 'playlist_count': 15,
659 _SEARCH_KEY = 'scsearch'
660 _MAX_RESULTS_PER_PAGE = 200
661 _DEFAULT_RESULTS_PER_PAGE = 50
662 _API_V2_BASE = 'https://api-v2.soundcloud.com'
664 def _get_collection(self, endpoint, collection_id, **query):
666 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
667 self._MAX_RESULTS_PER_PAGE)
668 query['limit'] = limit
669 query['client_id'] = self._CLIENT_ID
670 query['linked_partitioning'] = '1'
672 data = compat_urllib_parse_urlencode(query)
673 next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
675 collected_results = 0
677 for i in itertools.count(1):
678 response = self._download_json(
679 next_url, collection_id, 'Downloading page {0}'.format(i),
680 'Unable to download API page')
682 collection = response.get('collection', [])
686 collection = list(filter(bool, collection))
687 collected_results += len(collection)
689 for item in collection:
690 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
692 if not collection or collected_results >= limit:
695 next_url = response.get('next_href')
699 def _get_n_results(self, query, n):
700 tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
701 return self.playlist_result(tracks, playlist_title=query)