]>
jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/soundcloud.py
2 from __future__
import unicode_literals
13 from .. compat
import (
38 class SoundcloudEmbedIE ( InfoExtractor
):
39 _VALID_URL
= r
'https?://(?:w|player|p)\.soundcloud\.com/player/?.*?\burl=(?P<id>.+)'
41 # from https://www.soundi.fi/uutiset/ennakkokuuntelussa-timo-kaukolammen-station-to-station-to-station-julkaisua-juhlitaan-tanaan-g-livelabissa/
42 'url' : 'https://w.soundcloud.com/player/?visual=true&url=https%3A%2F%2Fapi.soundcloud.com%2Fplaylists%2F922213810&show_artwork=true&maxwidth=640&maxheight=960&dnt=1&secret_token=s-ziYey' ,
43 'only_matching' : True ,
47 def _extract_urls ( webpage
):
48 return [ m
. group ( 'url' ) for m
in re
. finditer (
49 r
'<iframe[^>]+src=(["\' ])( ?P
< url
>( ?
: https?
://) ?
( ?
: w\
.) ?soundcloud\
. com
/ player
.+ ?
) \
1 ',
52 def _real_extract(self, url):
54 api_url = query[' url
'][0]
55 secret_token = query.get(' secret_token
')
57 api_url = update_url_query(api_url, {'secret_token': secret_token[0]} )
58 return self.url_result(api_url)
61 class SoundcloudBaseIE(InfoExtractor):
62 _API_V2_BASE = ' https
:// api
- v2
. soundcloud
. com
/ '
63 _BASE_URL = ' https
:// soundcloud
. com
/ '
65 def _store_client_id(self, client_id):
66 self._downloader.cache.store(' soundcloud
', ' client_id
', client_id)
68 def _update_client_id(self):
69 webpage = self._download_webpage(' https
:// soundcloud
. com
/ ', None)
70 for src in reversed(re.findall(r' < script
[ ^
>]+ src
= "([^" ]+) "', webpage)):
71 script = self._download_webpage(src, None, fatal=False)
73 client_id = self._search_regex(
74 r'client_id\s*:\s*" ([ 0 - 9 a
- zA
- Z
] {32}
) "',
75 script, 'client id', default=None)
77 self._CLIENT_ID = client_id
78 self._store_client_id(client_id)
80 raise ExtractorError('Unable to extract client id')
82 def _download_json(self, *args, **kwargs):
83 non_fatal = kwargs.get('fatal') is False
86 query = kwargs.get('query', {}).copy()
88 query['client_id'] = self._CLIENT_ID
89 kwargs['query'] = query
91 return super()._download_json(*args, **compat_kwargs(kwargs))
92 except ExtractorError as e:
93 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (401, 403):
94 self._store_client_id(None)
95 self._update_client_id()
98 self.report_warning(error_to_compat_str(e))
102 def _real_initialize(self):
103 self._CLIENT_ID = self._downloader.cache.load('soundcloud', 'client_id') or 'a3e059563d7fd3372b49b37f00a00bcf'
106 _USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'
107 _API_AUTH_QUERY_TEMPLATE = '?client_id= %s '
108 _API_AUTH_URL_PW = 'https://api-auth.soundcloud.com/web-auth/sign-in/password %s '
109 _API_VERIFY_AUTH_TOKEN = 'https://api-auth.soundcloud.com/connect/session %s '
112 _NETRC_MACHINE = 'soundcloud'
115 username, password = self._get_login_info()
119 if username == 'oauth' and password is not None:
120 self._access_token = password
121 query = self._API_AUTH_QUERY_TEMPLATE % self._CLIENT_ID
122 payload = {'session': {'access_token': self._access_token} }
123 token_verification = sanitized_Request(self._API_VERIFY_AUTH_TOKEN % query, json.dumps(payload).encode('utf-8'))
124 response = self._download_json(token_verification, None, note='Verifying login token...', fatal=False)
125 if response is not False:
126 self._HEADERS = {'Authorization': 'OAuth ' + self._access_token}
129 self.report_warning('Provided authorization token seems to be invalid. Continue as guest')
130 elif username is not None:
132 'Login using username and password is not currently supported. '
133 'Use " -- user oauth
-- password
< oauth_token
> " to login using an oauth token')
138 return ''.join([str(random.randrange(10)) for i in range(6)])
139 return '-'.join([genNumBlock() for i in range(4)])
142 'client_id': self._CLIENT_ID,
143 'recaptcha_pubkey': 'null',
144 'recaptcha_response': 'null',
146 'identifier': username,
149 'signature': self.sign(username, password, self._CLIENT_ID),
150 'device_id': genDevId(),
151 'user_agent': self._USER_AGENT
154 query = self._API_AUTH_QUERY_TEMPLATE % self._CLIENT_ID
155 login = sanitized_Request(self._API_AUTH_URL_PW % query, json.dumps(payload).encode('utf-8'))
156 response = self._download_json(login, None)
157 self._access_token = response.get('session').get('access_token')
158 if not self._access_token:
159 self.report_warning('Unable to get access token, login may has failed')
161 self._HEADERS = {'Authorization': 'OAuth ' + self._access_token}
164 # signature generation
165 def sign(self, user, pw, clid):
175 n = '0763ed7314c69015fd4a0dc16bbf4b90' # _KEY
177 r = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36' # _USER_AGENT
179 t = clid # _CLIENT_ID
181 d = '-'.join([str(mInt) for mInt in [a, i, s, w, u, l, b, k]])
182 p = n + y + d + r + e + t + d + n
188 for f in range(f, len(h)):
189 m = (m >> 1) + ((1 & m) << 23)
193 # c is not even needed
194 out = str(y) + ':' + str(d) + ':' + format(m, 'x') + ':' + str(c)
199 def _resolv_url(cls, url):
200 return cls._API_V2_BASE + 'resolve?url=' + url
203 class SoundcloudIE(SoundcloudBaseIE):
204 """Information extractor for soundcloud.com
205 To access the media, the uid of the song and a stream token
206 must be extracted from the page source and the script must make
207 a request to media.soundcloud.com/crossdomain.xml. Then
208 the media can be grabbed by requesting from an url composed
209 of the stream token and uid
212 _VALID_URL = r'''(?x)^(?:https?://)?
213 (?:(?:(?:www\.|m\.)?soundcloud\.com/
215 (?P<uploader>[\w\d-]+)/
216 (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
218 (?:/(?P<token>(?!(?:albums|sets|recommended))[^?]+?))?
220 |(?:api(?:-v2)?\.soundcloud\.com/tracks/(?P<track_id>\d+)
221 (?:/? \? secret_token=(?P<secret_token>[^&]+))?)
224 IE_NAME = 'soundcloud'
227 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
228 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
232 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
233 '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',
234 'uploader': 'E.T. ExTerrestrial Music',
235 'uploader_id': '1571244',
236 'timestamp': 1349920598,
237 'upload_date': '20121011',
239 'license': 'all-rights-reserved',
242 'comment_count': int,
248 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
252 'title': 'Goldrushed',
253 'description': 'From Stockholm Sweden \r\n Povel / Magnus / Filip / David \r\n www.theroyalconcept.com',
254 'uploader': 'The Royal Concept',
255 'uploader_id': '9615865',
256 'timestamp': 1337635207,
257 'upload_date': '20120521',
259 'license': 'all-rights-reserved',
262 'comment_count': int,
268 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
269 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
273 'title': 'Youtube - Dl Test Video \'\' Äâ†',
274 'description': 'test chars: \"\' / \\ äâ†',
275 'uploader': 'jaimeMF',
276 'uploader_id': '69767071',
277 'timestamp': 1386604920,
278 'upload_date': '20131209',
280 'license': 'all-rights-reserved',
283 'comment_count': int,
287 # private link (alt format)
289 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
290 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
294 'title': 'Youtube - Dl Test Video \'\' Äâ†',
295 'description': 'test chars: \"\' / \\ äâ†',
296 'uploader': 'jaimeMF',
297 'uploader_id': '69767071',
298 'timestamp': 1386604920,
299 'upload_date': '20131209',
301 'license': 'all-rights-reserved',
304 'comment_count': int,
310 'url': 'https://soundcloud.com/the80m/the-following',
311 'md5': '9ffcddb08c87d74fb5808a3c183a1d04',
317 # private link, downloadable format
319 'url': 'https://soundcloud.com/oriuplift/uponly-238-no-talking-wav/s-AyZUd',
320 'md5': '64a60b16e617d41d0bef032b7f55441e',
324 'title': 'Uplifting Only 238 [No Talking] (incl. Alex Feed Guestmix) (Aug 31, 2017) [wav]',
325 'description': 'md5:fa20ee0fca76a3d6df8c7e57f3715366',
326 'uploader': 'Ori Uplift Music',
327 'uploader_id': '12563093',
328 'timestamp': 1504206263,
329 'upload_date': '20170831',
330 'duration': 7449.096,
331 'license': 'all-rights-reserved',
334 'comment_count': int,
338 # no album art, use avatar pic for thumbnail
340 'url': 'https://soundcloud.com/garyvee/sideways-prod-mad-real',
341 'md5': '59c7872bc44e5d99b7211891664760c2',
345 'title': 'Sideways (Prod. Mad Real)',
346 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
347 'uploader': 'garyvee',
348 'uploader_id': '2366352',
349 'timestamp': 1488152409,
350 'upload_date': '20170226',
352 'thumbnail': r're:https?://.*\.jpg',
353 'license': 'all-rights-reserved',
356 'comment_count': int,
360 'skip_download': True,
364 'url': 'https://soundcloud.com/giovannisarani/mezzo-valzer',
365 'md5': 'e22aecd2bc88e0e4e432d7dcc0a1abf7',
369 'title': 'Mezzo Valzer',
370 'description': 'md5:4138d582f81866a530317bae316e8b61',
371 'uploader': 'Micronie',
372 'uploader_id': '3352531',
373 'timestamp': 1551394171,
374 'upload_date': '20190228',
376 'thumbnail': r're:https?://.*\.jpg',
377 'license': 'all-rights-reserved',
380 'comment_count': int,
385 # AAC HQ format available (account with active subscription needed)
386 'url': 'https://soundcloud.com/wandw/the-chainsmokers-ft-daya-dont-let-me-down-ww-remix-1',
387 'only_matching': True,
390 # Go+ (account with active subscription needed)
391 'url': 'https://soundcloud.com/taylorswiftofficial/look-what-you-made-me-do',
392 'only_matching': True,
396 _IMAGE_REPL_RE = r'-([0-9a-z]+)\.jpg'
411 def _extract_info_dict(self, info, full_title=None, secret_token=None):
412 track_id = compat_str(info['id'])
413 title = info['title']
417 query = {'client_id': self._CLIENT_ID}
419 query['secret_token'] = secret_token
421 if info.get('downloadable') and info.get('has_downloads_left'):
422 download_url = update_url_query(
423 self._API_V2_BASE + 'tracks/' + track_id + '/download', query)
424 redirect_url = (self._download_json(download_url, track_id, fatal=False) or {}).get('redirectUri')
426 urlh = self._request_webpage(
427 HEADRequest(redirect_url), track_id, fatal=False)
429 format_url = urlh.geturl()
430 format_urls.add(format_url)
432 'format_id': 'download',
433 'ext': urlhandle_detect_ext(urlh) or 'mp3',
434 'filesize': int_or_none(urlh.headers.get('Content-Length')),
439 def invalid_url(url):
440 return not url or url in format_urls
442 def add_format(f, protocol, is_preview=False):
443 mobj = re.search(r'\.(?P<abr>\d+)\.(?P<ext>[0-9a-z] {3,4} )(?=[/?])', stream_url)
445 for k, v in mobj.groupdict().items():
450 format_id_list.append(protocol)
454 for k in ('ext', 'abr'):
457 format_id_list.append(v)
458 preview = is_preview or re.search(r'/(?:preview|playlist)/0/30/', f['url'])
460 format_id_list.append('preview')
464 if protocol == 'hls':
465 protocol = 'm3u8' if ext == 'aac' else 'm3u8_native'
469 'format_id': '_'.join(format_id_list),
470 'protocol': protocol,
471 'preference': -10 if preview else None,
476 transcodings = try_get(
477 info, lambda x: x['media']['transcodings'], list) or []
478 for t in transcodings:
479 if not isinstance(t, dict):
481 format_url = url_or_none(t.get('url'))
484 stream = self._download_json(
485 format_url, track_id, query=query, fatal=False, headers=self._HEADERS)
486 if not isinstance(stream, dict):
488 stream_url = url_or_none(stream.get('url'))
489 if invalid_url(stream_url):
491 format_urls.add(stream_url)
492 stream_format = t.get('format') or {}
493 protocol = stream_format.get('protocol')
494 if protocol != 'hls' and '/hls' in format_url:
497 preset = str_or_none(t.get('preset'))
499 ext = preset.split('_')[0]
500 if ext not in KNOWN_EXTENSIONS:
501 ext = mimetype2ext(stream_format.get('mime_type'))
505 }, 'http' if protocol == 'progressive' else protocol,
506 t.get('snipped') or '/preview/' in format_url)
511 if not formats and info.get('policy') == 'BLOCK':
512 self.raise_geo_restricted(metadata_available=True)
513 self._sort_formats(formats)
515 user = info.get('user') or {}
518 artwork_url = info.get('artwork_url')
519 thumbnail = artwork_url or user.get('avatar_url')
520 if isinstance(thumbnail, compat_str):
521 if re.search(self._IMAGE_REPL_RE, thumbnail):
522 for image_id, size in self._ARTWORK_MAP.items():
525 'url': re.sub(self._IMAGE_REPL_RE, '- %s .jpg' % image_id, thumbnail),
527 if image_id == 'tiny' and not artwork_url:
529 elif image_id == 'original':
538 thumbnails = [ {'url': thumbnail} ]
540 def extract_count(key):
541 return int_or_none(info.get(' %s _count' % key))
545 'uploader': user.get('username'),
546 'uploader_id': str_or_none(user.get('id')) or user.get('permalink'),
547 'uploader_url': user.get('permalink_url'),
548 'timestamp': unified_timestamp(info.get('created_at')),
550 'description': info.get('description'),
551 'thumbnails': thumbnails,
552 'duration': float_or_none(info.get('duration'), 1000),
553 'webpage_url': info.get('permalink_url'),
554 'license': info.get('license'),
555 'view_count': extract_count('playback'),
556 'like_count': extract_count('favoritings') or extract_count('likes'),
557 'comment_count': extract_count('comment'),
558 'repost_count': extract_count('reposts'),
559 'genre': info.get('genre'),
563 def _real_extract(self, url):
564 mobj = self._match_valid_url(url)
566 track_id = mobj.group('track_id')
570 info_json_url = self._API_V2_BASE + 'tracks/' + track_id
571 full_title = track_id
572 token = mobj.group('secret_token')
574 query['secret_token'] = token
576 full_title = resolve_title = ' %s / %s ' % mobj.group('uploader', 'title')
577 token = mobj.group('token')
579 resolve_title += '/ %s ' % token
580 info_json_url = self._resolv_url(self._BASE_URL + resolve_title)
582 info = self._download_json(
583 info_json_url, full_title, 'Downloading info JSON', query=query, headers=self._HEADERS)
585 return self._extract_info_dict(info, full_title, token)
588 class SoundcloudPlaylistBaseIE(SoundcloudBaseIE):
589 def _extract_set(self, playlist, token=None):
590 playlist_id = compat_str(playlist['id'])
591 tracks = playlist.get('tracks') or []
592 if not all([t.get('permalink_url') for t in tracks]) and token:
593 tracks = self._download_json(
594 self._API_V2_BASE + 'tracks', playlist_id,
595 'Downloading tracks', query={
596 'ids': ','.join([compat_str(t['id']) for t in tracks]),
597 'playlistId': playlist_id,
598 'playlistSecretToken': token,
599 }, headers=self._HEADERS)
602 track_id = str_or_none(track.get('id'))
603 url = track.get('permalink_url')
607 url = self._API_V2_BASE + 'tracks/' + track_id
609 url += '?secret_token=' + token
610 entries.append(self.url_result(
611 url, SoundcloudIE.ie_key(), track_id))
612 return self.playlist_result(
613 entries, playlist_id,
614 playlist.get('title'),
615 playlist.get('description'))
618 class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
619 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[:\w\d-]+)(?:/(?P<token>[^?/]+))?'
620 IE_NAME = 'soundcloud:set'
622 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
625 'title': 'The Royal Concept EP',
626 'description': 'md5:71d07087c7a449e8941a70a29e34671e',
628 'playlist_mincount': 5,
630 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
631 'only_matching': True,
633 'url': 'https://soundcloud.com/discover/sets/weekly::flacmatic',
634 'only_matching': True,
636 'url': 'https://soundcloud.com/discover/sets/charts-top:all-music:de',
637 'only_matching': True,
639 'url': 'https://soundcloud.com/discover/sets/charts-top:hiphoprap:kr',
640 'only_matching': True,
643 def _real_extract(self, url):
644 mobj = self._match_valid_url(url)
646 full_title = ' %s /sets/ %s ' % mobj.group('uploader', 'slug_title')
647 token = mobj.group('token')
649 full_title += '/' + token
651 info = self._download_json(self._resolv_url(
652 self._BASE_URL + full_title), full_title, headers=self._HEADERS)
655 msgs = (compat_str(err['error_message']) for err in info['errors'])
656 raise ExtractorError('unable to download video webpage: %s ' % ','.join(msgs))
658 return self._extract_set(info, token)
661 class SoundcloudPagedPlaylistBaseIE(SoundcloudBaseIE):
662 def _extract_playlist(self, base_url, playlist_id, playlist_title):
666 'title': playlist_title,
667 'entries': self._entries(base_url, playlist_id),
670 def _entries(self, url, playlist_id):
671 # Per the SoundCloud documentation, the maximum limit for a linked partitioning query is 200.
672 # https://developers.soundcloud.com/blog/offset-pagination-deprecated
675 'linked_partitioning': '1',
679 retries = self.get_param('extractor_retries', 3)
681 for i in itertools.count():
682 attempt, last_error = -1, None
683 while attempt < retries:
686 self.report_warning(' %s . Retrying ...' % remove_end(last_error, '.'), playlist_id)
688 response = self._download_json(
689 url, playlist_id, query=query, headers=self._HEADERS,
690 note='Downloading track page %s%s ' % (i + 1, f' (retry # {attempt} )' if attempt else ''))
692 except ExtractorError as e:
693 # Downloading page may result in intermittent 502 HTTP error
694 # See https://github.com/yt-dlp/yt-dlp/issues/872
695 if attempt >= retries or not isinstance(e.cause, compat_HTTPError) or e.cause.code != 502:
697 last_error = str(e.cause or e.msg)
699 def resolve_entry(*candidates):
700 for cand in candidates:
701 if not isinstance(cand, dict):
703 permalink_url = url_or_none(cand.get('permalink_url'))
705 return self.url_result(
707 SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
708 str_or_none(cand.get('id')), cand.get('title'))
710 for e in response['collection'] or []:
711 yield resolve_entry(e, e.get('track'), e.get('playlist'))
713 url = response.get('next_href')
716 query.pop('offset', None)
719 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
720 _VALID_URL = r'''(?x)
722 (?:(?:www|m)\.)?soundcloud\.com/
725 (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
729 IE_NAME = 'soundcloud:user'
731 'url': 'https://soundcloud.com/soft-cell-official',
734 'title': 'Soft Cell (All)',
736 'playlist_mincount': 28,
738 'url': 'https://soundcloud.com/soft-cell-official/tracks',
741 'title': 'Soft Cell (Tracks)',
743 'playlist_mincount': 27,
745 'url': 'https://soundcloud.com/soft-cell-official/albums',
748 'title': 'Soft Cell (Albums)',
750 'playlist_mincount': 1,
752 'url': 'https://soundcloud.com/jcv246/sets',
755 'title': 'Jordi / cv (Sets)',
757 'playlist_mincount': 2,
759 'url': 'https://soundcloud.com/jcv246/reposts',
762 'title': 'Jordi / cv (Reposts)',
764 'playlist_mincount': 6,
766 'url': 'https://soundcloud.com/clalberg/likes',
769 'title': 'clalberg (Likes)',
771 'playlist_mincount': 5,
773 'url': 'https://soundcloud.com/grynpyret/spotlight',
776 'title': 'Grynpyret (Spotlight)',
778 'playlist_mincount': 1,
782 'all': 'stream/users/ %s ',
783 'tracks': 'users/ %s /tracks',
784 'albums': 'users/ %s /albums',
785 'sets': 'users/ %s /playlists',
786 'reposts': 'stream/users/ %s /reposts',
787 'likes': 'users/ %s /likes',
788 'spotlight': 'users/ %s /spotlight',
791 def _real_extract(self, url):
792 mobj = self._match_valid_url(url)
793 uploader = mobj.group('user')
795 user = self._download_json(
796 self._resolv_url(self._BASE_URL + uploader),
797 uploader, 'Downloading user info', headers=self._HEADERS)
799 resource = mobj.group('rsrc') or 'all'
801 return self._extract_playlist(
802 self._API_V2_BASE + self._BASE_URL_MAP[resource] % user['id'],
803 str_or_none(user.get('id')),
804 ' %s ( %s )' % (user['username'], resource.capitalize()))
807 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
808 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
809 IE_NAME = 'soundcloud:trackstation'
811 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
814 'title': 'Track station: your text',
816 'playlist_mincount': 47,
819 def _real_extract(self, url):
820 track_name = self._match_id(url)
822 track = self._download_json(self._resolv_url(url), track_name, headers=self._HEADERS)
823 track_id = self._search_regex(
824 r'soundcloud:track-stations:(\d+)', track['id'], 'track id')
826 return self._extract_playlist(
827 self._API_V2_BASE + 'stations/ %s /tracks' % track['id'],
828 track_id, 'Track station: %s ' % track['title'])
831 class SoundcloudRelatedIE(SoundcloudPagedPlaylistBaseIE):
832 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<slug>[\w\d-]+/[\w\d-]+)/(?P<relation>albums|sets|recommended)'
833 IE_NAME = 'soundcloud:related'
835 'url': 'https://soundcloud.com/wajang/sexapil-pingers-5/recommended',
838 'title': 'Sexapil - Pingers 5 (Recommended)',
840 'playlist_mincount': 50,
842 'url': 'https://soundcloud.com/wajang/sexapil-pingers-5/albums',
845 'title': 'Sexapil - Pingers 5 (Albums)',
847 'playlist_mincount': 1,
849 'url': 'https://soundcloud.com/wajang/sexapil-pingers-5/sets',
852 'title': 'Sexapil - Pingers 5 (Sets)',
854 'playlist_mincount': 4,
858 'albums': 'tracks/ %s /albums',
859 'sets': 'tracks/ %s /playlists_without_albums',
860 'recommended': 'tracks/ %s /related',
863 def _real_extract(self, url):
864 slug, relation = self._match_valid_url(url).group('slug', 'relation')
866 track = self._download_json(
867 self._resolv_url(self._BASE_URL + slug),
868 slug, 'Downloading track info', headers=self._HEADERS)
870 if track.get('errors'):
871 raise ExtractorError(f' {self.IE_NAME} said: %s ' % ','.join(
872 str(err['error_message']) for err in track['errors']), expected=True)
874 return self._extract_playlist(
875 self._API_V2_BASE + self._BASE_URL_MAP[relation] % track['id'], str(track['id']),
876 ' %s ( %s )' % (track.get('title') or slug, relation.capitalize()))
879 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
880 _VALID_URL = r'https?://api(?:-v2)?\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/? \? secret_token=(?P<token>[^&]+?))?$'
881 IE_NAME = 'soundcloud:playlist'
883 'url': 'https://api.soundcloud.com/playlists/4110309',
886 'title': 'TILT Brass - Bowery Poetry Club, August \' 03 [Non-Site SCR 02]',
887 'description': 're:.*?TILT Brass - Bowery Poetry Club',
892 def _real_extract(self, url):
893 mobj = self._match_valid_url(url)
894 playlist_id = mobj.group('id')
897 token = mobj.group('token')
899 query['secret_token'] = token
901 data = self._download_json(
902 self._API_V2_BASE + 'playlists/' + playlist_id,
903 playlist_id, 'Downloading playlist', query=query, headers=self._HEADERS)
905 return self._extract_set(data, token)
908 class SoundcloudSearchIE(SoundcloudBaseIE, SearchInfoExtractor):
909 IE_NAME = 'soundcloud:search'
910 IE_DESC = 'Soundcloud search'
911 _SEARCH_KEY = 'scsearch'
913 'url': 'scsearch15:post-avant jazzcore',
915 'title': 'post-avant jazzcore',
917 'playlist_count': 15,
920 _MAX_RESULTS_PER_PAGE = 200
921 _DEFAULT_RESULTS_PER_PAGE = 50
923 def _get_collection(self, endpoint, collection_id, **query):
925 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
926 self._MAX_RESULTS_PER_PAGE)
929 'linked_partitioning': 1,
932 next_url = update_url_query(self._API_V2_BASE + endpoint, query)
934 for i in itertools.count(1):
935 response = self._download_json(
936 next_url, collection_id, f'Downloading page {i} ',
937 'Unable to download API page', headers=self._HEADERS)
939 for item in response.get('collection') or []:
941 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
943 next_url = response.get('next_href')
947 def _get_n_results(self, query, n):
948 return self.playlist_result(itertools.islice(
949 self._get_collection('search/tracks', query, limit=n, q=query),
950 0, None if n == float('inf') else n), query, query)