]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/soundcloud.py
412331e17c7d699a410cc9c81e5e64fb9accae9d
[yt-dlp.git] / yt_dlp / extractor / soundcloud.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import itertools
5 import re
6 import json
7 # import random
8
9 from .common import (
10 InfoExtractor,
11 SearchInfoExtractor
12 )
13 from ..compat import (
14 compat_HTTPError,
15 compat_kwargs,
16 compat_str,
17 )
18 from ..utils import (
19 error_to_compat_str,
20 ExtractorError,
21 float_or_none,
22 HEADRequest,
23 int_or_none,
24 KNOWN_EXTENSIONS,
25 mimetype2ext,
26 remove_end,
27 parse_qs,
28 str_or_none,
29 try_get,
30 unified_timestamp,
31 update_url_query,
32 url_or_none,
33 urlhandle_detect_ext,
34 sanitized_Request,
35 )
36
37
38 class SoundcloudEmbedIE(InfoExtractor):
39 _VALID_URL = r'https?://(?:w|player|p)\.soundcloud\.com/player/?.*?\burl=(?P<id>.+)'
40 _TEST = {
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,
44 }
45
46 @staticmethod
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',
50 webpage)]
51
52 def _real_extract(self, url):
53 query = parse_qs(url)
54 api_url = query['url'][0]
55 secret_token = query.get('secret_token')
56 if secret_token:
57 api_url = update_url_query(api_url, {'secret_token': secret_token[0]})
58 return self.url_result(api_url)
59
60
61 class SoundcloudIE(InfoExtractor):
62 """Information extractor for soundcloud.com
63 To access the media, the uid of the song and a stream token
64 must be extracted from the page source and the script must make
65 a request to media.soundcloud.com/crossdomain.xml. Then
66 the media can be grabbed by requesting from an url composed
67 of the stream token and uid
68 """
69
70 _VALID_URL = r'''(?x)^(?:https?://)?
71 (?:(?:(?:www\.|m\.)?soundcloud\.com/
72 (?!stations/track)
73 (?P<uploader>[\w\d-]+)/
74 (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
75 (?P<title>[\w\d-]+)/?
76 (?P<token>[^?]+?)?(?:[?].*)?$)
77 |(?:api(?:-v2)?\.soundcloud\.com/tracks/(?P<track_id>\d+)
78 (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
79 )
80 '''
81 IE_NAME = 'soundcloud'
82 _TESTS = [
83 {
84 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
85 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
86 'info_dict': {
87 'id': '62986583',
88 'ext': 'mp3',
89 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
90 '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',
91 'uploader': 'E.T. ExTerrestrial Music',
92 'uploader_id': '1571244',
93 'timestamp': 1349920598,
94 'upload_date': '20121011',
95 'duration': 143.216,
96 'license': 'all-rights-reserved',
97 'view_count': int,
98 'like_count': int,
99 'comment_count': int,
100 'repost_count': int,
101 }
102 },
103 # geo-restricted
104 {
105 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
106 'info_dict': {
107 'id': '47127627',
108 'ext': 'mp3',
109 'title': 'Goldrushed',
110 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
111 'uploader': 'The Royal Concept',
112 'uploader_id': '9615865',
113 'timestamp': 1337635207,
114 'upload_date': '20120521',
115 'duration': 227.155,
116 'license': 'all-rights-reserved',
117 'view_count': int,
118 'like_count': int,
119 'comment_count': int,
120 'repost_count': int,
121 },
122 },
123 # private link
124 {
125 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
126 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
127 'info_dict': {
128 'id': '123998367',
129 'ext': 'mp3',
130 'title': 'Youtube - Dl Test Video \'\' Ä↭',
131 'description': 'test chars: \"\'/\\ä↭',
132 'uploader': 'jaimeMF',
133 'uploader_id': '69767071',
134 'timestamp': 1386604920,
135 'upload_date': '20131209',
136 'duration': 9.927,
137 'license': 'all-rights-reserved',
138 'view_count': int,
139 'like_count': int,
140 'comment_count': int,
141 'repost_count': int,
142 },
143 },
144 # private link (alt format)
145 {
146 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
147 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
148 'info_dict': {
149 'id': '123998367',
150 'ext': 'mp3',
151 'title': 'Youtube - Dl Test Video \'\' Ä↭',
152 'description': 'test chars: \"\'/\\ä↭',
153 'uploader': 'jaimeMF',
154 'uploader_id': '69767071',
155 'timestamp': 1386604920,
156 'upload_date': '20131209',
157 'duration': 9.927,
158 'license': 'all-rights-reserved',
159 'view_count': int,
160 'like_count': int,
161 'comment_count': int,
162 'repost_count': int,
163 },
164 },
165 # downloadable song
166 {
167 'url': 'https://soundcloud.com/the80m/the-following',
168 'md5': '9ffcddb08c87d74fb5808a3c183a1d04',
169 'info_dict': {
170 'id': '343609555',
171 'ext': 'wav',
172 },
173 },
174 # private link, downloadable format
175 {
176 'url': 'https://soundcloud.com/oriuplift/uponly-238-no-talking-wav/s-AyZUd',
177 'md5': '64a60b16e617d41d0bef032b7f55441e',
178 'info_dict': {
179 'id': '340344461',
180 'ext': 'wav',
181 'title': 'Uplifting Only 238 [No Talking] (incl. Alex Feed Guestmix) (Aug 31, 2017) [wav]',
182 'description': 'md5:fa20ee0fca76a3d6df8c7e57f3715366',
183 'uploader': 'Ori Uplift Music',
184 'uploader_id': '12563093',
185 'timestamp': 1504206263,
186 'upload_date': '20170831',
187 'duration': 7449.096,
188 'license': 'all-rights-reserved',
189 'view_count': int,
190 'like_count': int,
191 'comment_count': int,
192 'repost_count': int,
193 },
194 },
195 # no album art, use avatar pic for thumbnail
196 {
197 'url': 'https://soundcloud.com/garyvee/sideways-prod-mad-real',
198 'md5': '59c7872bc44e5d99b7211891664760c2',
199 'info_dict': {
200 'id': '309699954',
201 'ext': 'mp3',
202 'title': 'Sideways (Prod. Mad Real)',
203 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
204 'uploader': 'garyvee',
205 'uploader_id': '2366352',
206 'timestamp': 1488152409,
207 'upload_date': '20170226',
208 'duration': 207.012,
209 'thumbnail': r're:https?://.*\.jpg',
210 'license': 'all-rights-reserved',
211 'view_count': int,
212 'like_count': int,
213 'comment_count': int,
214 'repost_count': int,
215 },
216 'params': {
217 'skip_download': True,
218 },
219 },
220 {
221 'url': 'https://soundcloud.com/giovannisarani/mezzo-valzer',
222 'md5': 'e22aecd2bc88e0e4e432d7dcc0a1abf7',
223 'info_dict': {
224 'id': '583011102',
225 'ext': 'mp3',
226 'title': 'Mezzo Valzer',
227 'description': 'md5:4138d582f81866a530317bae316e8b61',
228 'uploader': 'Micronie',
229 'uploader_id': '3352531',
230 'timestamp': 1551394171,
231 'upload_date': '20190228',
232 'duration': 180.157,
233 'thumbnail': r're:https?://.*\.jpg',
234 'license': 'all-rights-reserved',
235 'view_count': int,
236 'like_count': int,
237 'comment_count': int,
238 'repost_count': int,
239 },
240 },
241 {
242 # AAC HQ format available (account with active subscription needed)
243 'url': 'https://soundcloud.com/wandw/the-chainsmokers-ft-daya-dont-let-me-down-ww-remix-1',
244 'only_matching': True,
245 },
246 {
247 # Go+ (account with active subscription needed)
248 'url': 'https://soundcloud.com/taylorswiftofficial/look-what-you-made-me-do',
249 'only_matching': True,
250 },
251 ]
252
253 _API_V2_BASE = 'https://api-v2.soundcloud.com/'
254 _BASE_URL = 'https://soundcloud.com/'
255 _IMAGE_REPL_RE = r'-([0-9a-z]+)\.jpg'
256
257 _ARTWORK_MAP = {
258 'mini': 16,
259 'tiny': 20,
260 'small': 32,
261 'badge': 47,
262 't67x67': 67,
263 'large': 100,
264 't300x300': 300,
265 'crop': 400,
266 't500x500': 500,
267 'original': 0,
268 }
269
270 def _store_client_id(self, client_id):
271 self._downloader.cache.store('soundcloud', 'client_id', client_id)
272
273 def _update_client_id(self):
274 webpage = self._download_webpage('https://soundcloud.com/', None)
275 for src in reversed(re.findall(r'<script[^>]+src="([^"]+)"', webpage)):
276 script = self._download_webpage(src, None, fatal=False)
277 if script:
278 client_id = self._search_regex(
279 r'client_id\s*:\s*"([0-9a-zA-Z]{32})"',
280 script, 'client id', default=None)
281 if client_id:
282 self._CLIENT_ID = client_id
283 self._store_client_id(client_id)
284 return
285 raise ExtractorError('Unable to extract client id')
286
287 def _download_json(self, *args, **kwargs):
288 non_fatal = kwargs.get('fatal') is False
289 if non_fatal:
290 del kwargs['fatal']
291 query = kwargs.get('query', {}).copy()
292 for _ in range(2):
293 query['client_id'] = self._CLIENT_ID
294 kwargs['query'] = query
295 try:
296 return super(SoundcloudIE, self)._download_json(*args, **compat_kwargs(kwargs))
297 except ExtractorError as e:
298 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (401, 403):
299 self._store_client_id(None)
300 self._update_client_id()
301 continue
302 elif non_fatal:
303 self.report_warning(error_to_compat_str(e))
304 return False
305 raise
306
307 def _real_initialize(self):
308 self._CLIENT_ID = self._downloader.cache.load('soundcloud', 'client_id') or 'a3e059563d7fd3372b49b37f00a00bcf'
309 self._login()
310
311 _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'
312 _API_AUTH_QUERY_TEMPLATE = '?client_id=%s'
313 _API_AUTH_URL_PW = 'https://api-auth.soundcloud.com/web-auth/sign-in/password%s'
314 _API_VERIFY_AUTH_TOKEN = 'https://api-auth.soundcloud.com/connect/session%s'
315 _access_token = None
316 _HEADERS = {}
317 _NETRC_MACHINE = 'soundcloud'
318
319 def _login(self):
320 username, password = self._get_login_info()
321 if username is None:
322 return
323
324 if username == 'oauth' and password is not None:
325 self._access_token = password
326 query = self._API_AUTH_QUERY_TEMPLATE % self._CLIENT_ID
327 payload = {'session': {'access_token': self._access_token}}
328 token_verification = sanitized_Request(self._API_VERIFY_AUTH_TOKEN % query, json.dumps(payload).encode('utf-8'))
329 response = self._download_json(token_verification, None, note='Verifying login token...', fatal=False)
330 if response is not False:
331 self._HEADERS = {'Authorization': 'OAuth ' + self._access_token}
332 self.report_login()
333 else:
334 self.report_warning('Provided authorization token seems to be invalid. Continue as guest')
335 elif username is not None:
336 self.report_warning(
337 'Login using username and password is not currently supported. '
338 'Use "--user oauth --password <oauth_token>" to login using an oauth token')
339
340 r'''
341 def genDevId():
342 def genNumBlock():
343 return ''.join([str(random.randrange(10)) for i in range(6)])
344 return '-'.join([genNumBlock() for i in range(4)])
345
346 payload = {
347 'client_id': self._CLIENT_ID,
348 'recaptcha_pubkey': 'null',
349 'recaptcha_response': 'null',
350 'credentials': {
351 'identifier': username,
352 'password': password
353 },
354 'signature': self.sign(username, password, self._CLIENT_ID),
355 'device_id': genDevId(),
356 'user_agent': self._USER_AGENT
357 }
358
359 query = self._API_AUTH_QUERY_TEMPLATE % self._CLIENT_ID
360 login = sanitized_Request(self._API_AUTH_URL_PW % query, json.dumps(payload).encode('utf-8'))
361 response = self._download_json(login, None)
362 self._access_token = response.get('session').get('access_token')
363 if not self._access_token:
364 self.report_warning('Unable to get access token, login may has failed')
365 else:
366 self._HEADERS = {'Authorization': 'OAuth ' + self._access_token}
367 '''
368
369 # signature generation
370 def sign(self, user, pw, clid):
371 a = 33
372 i = 1
373 s = 440123
374 w = 117
375 u = 1800000
376 l = 1042
377 b = 37
378 k = 37
379 c = 5
380 n = '0763ed7314c69015fd4a0dc16bbf4b90' # _KEY
381 y = '8' # _REV
382 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
383 e = user # _USERNAME
384 t = clid # _CLIENT_ID
385
386 d = '-'.join([str(mInt) for mInt in [a, i, s, w, u, l, b, k]])
387 p = n + y + d + r + e + t + d + n
388 h = p
389
390 m = 8011470
391 f = 0
392
393 for f in range(f, len(h)):
394 m = (m >> 1) + ((1 & m) << 23)
395 m += ord(h[f])
396 m &= 16777215
397
398 # c is not even needed
399 out = str(y) + ':' + str(d) + ':' + format(m, 'x') + ':' + str(c)
400
401 return out
402
403 @classmethod
404 def _resolv_url(cls, url):
405 return SoundcloudIE._API_V2_BASE + 'resolve?url=' + url
406
407 def _extract_info_dict(self, info, full_title=None, secret_token=None):
408 track_id = compat_str(info['id'])
409 title = info['title']
410
411 format_urls = set()
412 formats = []
413 query = {'client_id': self._CLIENT_ID}
414 if secret_token:
415 query['secret_token'] = secret_token
416
417 if info.get('downloadable') and info.get('has_downloads_left'):
418 download_url = update_url_query(
419 self._API_V2_BASE + 'tracks/' + track_id + '/download', query)
420 redirect_url = (self._download_json(download_url, track_id, fatal=False) or {}).get('redirectUri')
421 if redirect_url:
422 urlh = self._request_webpage(
423 HEADRequest(redirect_url), track_id, fatal=False)
424 if urlh:
425 format_url = urlh.geturl()
426 format_urls.add(format_url)
427 formats.append({
428 'format_id': 'download',
429 'ext': urlhandle_detect_ext(urlh) or 'mp3',
430 'filesize': int_or_none(urlh.headers.get('Content-Length')),
431 'url': format_url,
432 'quality': 10,
433 })
434
435 def invalid_url(url):
436 return not url or url in format_urls
437
438 def add_format(f, protocol, is_preview=False):
439 mobj = re.search(r'\.(?P<abr>\d+)\.(?P<ext>[0-9a-z]{3,4})(?=[/?])', stream_url)
440 if mobj:
441 for k, v in mobj.groupdict().items():
442 if not f.get(k):
443 f[k] = v
444 format_id_list = []
445 if protocol:
446 format_id_list.append(protocol)
447 ext = f.get('ext')
448 if ext == 'aac':
449 f['abr'] = '256'
450 for k in ('ext', 'abr'):
451 v = f.get(k)
452 if v:
453 format_id_list.append(v)
454 preview = is_preview or re.search(r'/(?:preview|playlist)/0/30/', f['url'])
455 if preview:
456 format_id_list.append('preview')
457 abr = f.get('abr')
458 if abr:
459 f['abr'] = int(abr)
460 if protocol == 'hls':
461 protocol = 'm3u8' if ext == 'aac' else 'm3u8_native'
462 else:
463 protocol = 'http'
464 f.update({
465 'format_id': '_'.join(format_id_list),
466 'protocol': protocol,
467 'preference': -10 if preview else None,
468 })
469 formats.append(f)
470
471 # New API
472 transcodings = try_get(
473 info, lambda x: x['media']['transcodings'], list) or []
474 for t in transcodings:
475 if not isinstance(t, dict):
476 continue
477 format_url = url_or_none(t.get('url'))
478 if not format_url:
479 continue
480 stream = self._download_json(
481 format_url, track_id, query=query, fatal=False, headers=self._HEADERS)
482 if not isinstance(stream, dict):
483 continue
484 stream_url = url_or_none(stream.get('url'))
485 if invalid_url(stream_url):
486 continue
487 format_urls.add(stream_url)
488 stream_format = t.get('format') or {}
489 protocol = stream_format.get('protocol')
490 if protocol != 'hls' and '/hls' in format_url:
491 protocol = 'hls'
492 ext = None
493 preset = str_or_none(t.get('preset'))
494 if preset:
495 ext = preset.split('_')[0]
496 if ext not in KNOWN_EXTENSIONS:
497 ext = mimetype2ext(stream_format.get('mime_type'))
498 add_format({
499 'url': stream_url,
500 'ext': ext,
501 }, 'http' if protocol == 'progressive' else protocol,
502 t.get('snipped') or '/preview/' in format_url)
503
504 for f in formats:
505 f['vcodec'] = 'none'
506
507 if not formats and info.get('policy') == 'BLOCK':
508 self.raise_geo_restricted(metadata_available=True)
509 self._sort_formats(formats)
510
511 user = info.get('user') or {}
512
513 thumbnails = []
514 artwork_url = info.get('artwork_url')
515 thumbnail = artwork_url or user.get('avatar_url')
516 if isinstance(thumbnail, compat_str):
517 if re.search(self._IMAGE_REPL_RE, thumbnail):
518 for image_id, size in self._ARTWORK_MAP.items():
519 i = {
520 'id': image_id,
521 'url': re.sub(self._IMAGE_REPL_RE, '-%s.jpg' % image_id, thumbnail),
522 }
523 if image_id == 'tiny' and not artwork_url:
524 size = 18
525 elif image_id == 'original':
526 i['preference'] = 10
527 if size:
528 i.update({
529 'width': size,
530 'height': size,
531 })
532 thumbnails.append(i)
533 else:
534 thumbnails = [{'url': thumbnail}]
535
536 def extract_count(key):
537 return int_or_none(info.get('%s_count' % key))
538
539 return {
540 'id': track_id,
541 'uploader': user.get('username'),
542 'uploader_id': str_or_none(user.get('id')) or user.get('permalink'),
543 'uploader_url': user.get('permalink_url'),
544 'timestamp': unified_timestamp(info.get('created_at')),
545 'title': title,
546 'description': info.get('description'),
547 'thumbnails': thumbnails,
548 'duration': float_or_none(info.get('duration'), 1000),
549 'webpage_url': info.get('permalink_url'),
550 'license': info.get('license'),
551 'view_count': extract_count('playback'),
552 'like_count': extract_count('favoritings') or extract_count('likes'),
553 'comment_count': extract_count('comment'),
554 'repost_count': extract_count('reposts'),
555 'genre': info.get('genre'),
556 'formats': formats
557 }
558
559 def _real_extract(self, url):
560 mobj = self._match_valid_url(url)
561
562 track_id = mobj.group('track_id')
563
564 query = {}
565 if track_id:
566 info_json_url = self._API_V2_BASE + 'tracks/' + track_id
567 full_title = track_id
568 token = mobj.group('secret_token')
569 if token:
570 query['secret_token'] = token
571 else:
572 full_title = resolve_title = '%s/%s' % mobj.group('uploader', 'title')
573 token = mobj.group('token')
574 if token:
575 resolve_title += '/%s' % token
576 info_json_url = self._resolv_url(self._BASE_URL + resolve_title)
577
578 info = self._download_json(
579 info_json_url, full_title, 'Downloading info JSON', query=query, headers=self._HEADERS)
580
581 return self._extract_info_dict(info, full_title, token)
582
583
584 class SoundcloudPlaylistBaseIE(SoundcloudIE):
585 def _extract_set(self, playlist, token=None):
586 playlist_id = compat_str(playlist['id'])
587 tracks = playlist.get('tracks') or []
588 if not all([t.get('permalink_url') for t in tracks]) and token:
589 tracks = self._download_json(
590 self._API_V2_BASE + 'tracks', playlist_id,
591 'Downloading tracks', query={
592 'ids': ','.join([compat_str(t['id']) for t in tracks]),
593 'playlistId': playlist_id,
594 'playlistSecretToken': token,
595 }, headers=self._HEADERS)
596 entries = []
597 for track in tracks:
598 track_id = str_or_none(track.get('id'))
599 url = track.get('permalink_url')
600 if not url:
601 if not track_id:
602 continue
603 url = self._API_V2_BASE + 'tracks/' + track_id
604 if token:
605 url += '?secret_token=' + token
606 entries.append(self.url_result(
607 url, SoundcloudIE.ie_key(), track_id))
608 return self.playlist_result(
609 entries, playlist_id,
610 playlist.get('title'),
611 playlist.get('description'))
612
613
614 class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
615 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[:\w\d-]+)(?:/(?P<token>[^?/]+))?'
616 IE_NAME = 'soundcloud:set'
617 _TESTS = [{
618 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
619 'info_dict': {
620 'id': '2284613',
621 'title': 'The Royal Concept EP',
622 'description': 'md5:71d07087c7a449e8941a70a29e34671e',
623 },
624 'playlist_mincount': 5,
625 }, {
626 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
627 'only_matching': True,
628 }, {
629 'url': 'https://soundcloud.com/discover/sets/weekly::flacmatic',
630 'only_matching': True,
631 }, {
632 'url': 'https://soundcloud.com/discover/sets/charts-top:all-music:de',
633 'only_matching': True,
634 }, {
635 'url': 'https://soundcloud.com/discover/sets/charts-top:hiphoprap:kr',
636 'only_matching': True,
637 }]
638
639 def _real_extract(self, url):
640 mobj = self._match_valid_url(url)
641
642 full_title = '%s/sets/%s' % mobj.group('uploader', 'slug_title')
643 token = mobj.group('token')
644 if token:
645 full_title += '/' + token
646
647 info = self._download_json(self._resolv_url(
648 self._BASE_URL + full_title), full_title, headers=self._HEADERS)
649
650 if 'errors' in info:
651 msgs = (compat_str(err['error_message']) for err in info['errors'])
652 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
653
654 return self._extract_set(info, token)
655
656
657 class SoundcloudPagedPlaylistBaseIE(SoundcloudIE):
658 def _extract_playlist(self, base_url, playlist_id, playlist_title):
659 return {
660 '_type': 'playlist',
661 'id': playlist_id,
662 'title': playlist_title,
663 'entries': self._entries(base_url, playlist_id),
664 }
665
666 def _entries(self, url, playlist_id):
667 # Per the SoundCloud documentation, the maximum limit for a linked partitioning query is 200.
668 # https://developers.soundcloud.com/blog/offset-pagination-deprecated
669 query = {
670 'limit': 200,
671 'linked_partitioning': '1',
672 'offset': 0,
673 }
674
675 retries = self.get_param('extractor_retries', 3)
676
677 for i in itertools.count():
678 attempt, last_error = -1, None
679 while attempt < retries:
680 attempt += 1
681 if last_error:
682 self.report_warning('%s. Retrying ...' % remove_end(last_error, '.'), playlist_id)
683 try:
684 response = self._download_json(
685 url, playlist_id, query=query, headers=self._HEADERS,
686 note='Downloading track page %s%s' % (i + 1, f' (retry #{attempt})' if attempt else ''))
687 break
688 except ExtractorError as e:
689 # Downloading page may result in intermittent 502 HTTP error
690 # See https://github.com/yt-dlp/yt-dlp/issues/872
691 if attempt >= retries or not isinstance(e.cause, compat_HTTPError) or e.cause.code != 502:
692 raise
693 last_error = str(e.cause or e.msg)
694
695 def resolve_entry(*candidates):
696 for cand in candidates:
697 if not isinstance(cand, dict):
698 continue
699 permalink_url = url_or_none(cand.get('permalink_url'))
700 if permalink_url:
701 return self.url_result(
702 permalink_url,
703 SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
704 str_or_none(cand.get('id')), cand.get('title'))
705
706 for e in response['collection'] or []:
707 yield resolve_entry(e, e.get('track'), e.get('playlist'))
708
709 url = response.get('next_href')
710 if not url:
711 break
712 query.pop('offset', None)
713
714
715 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
716 _VALID_URL = r'''(?x)
717 https?://
718 (?:(?:www|m)\.)?soundcloud\.com/
719 (?P<user>[^/]+)
720 (?:/
721 (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
722 )?
723 /?(?:[?#].*)?$
724 '''
725 IE_NAME = 'soundcloud:user'
726 _TESTS = [{
727 'url': 'https://soundcloud.com/soft-cell-official',
728 'info_dict': {
729 'id': '207965082',
730 'title': 'Soft Cell (All)',
731 },
732 'playlist_mincount': 28,
733 }, {
734 'url': 'https://soundcloud.com/soft-cell-official/tracks',
735 'info_dict': {
736 'id': '207965082',
737 'title': 'Soft Cell (Tracks)',
738 },
739 'playlist_mincount': 27,
740 }, {
741 'url': 'https://soundcloud.com/soft-cell-official/albums',
742 'info_dict': {
743 'id': '207965082',
744 'title': 'Soft Cell (Albums)',
745 },
746 'playlist_mincount': 1,
747 }, {
748 'url': 'https://soundcloud.com/jcv246/sets',
749 'info_dict': {
750 'id': '12982173',
751 'title': 'Jordi / cv (Sets)',
752 },
753 'playlist_mincount': 2,
754 }, {
755 'url': 'https://soundcloud.com/jcv246/reposts',
756 'info_dict': {
757 'id': '12982173',
758 'title': 'Jordi / cv (Reposts)',
759 },
760 'playlist_mincount': 6,
761 }, {
762 'url': 'https://soundcloud.com/clalberg/likes',
763 'info_dict': {
764 'id': '11817582',
765 'title': 'clalberg (Likes)',
766 },
767 'playlist_mincount': 5,
768 }, {
769 'url': 'https://soundcloud.com/grynpyret/spotlight',
770 'info_dict': {
771 'id': '7098329',
772 'title': 'Grynpyret (Spotlight)',
773 },
774 'playlist_mincount': 1,
775 }]
776
777 _BASE_URL_MAP = {
778 'all': 'stream/users/%s',
779 'tracks': 'users/%s/tracks',
780 'albums': 'users/%s/albums',
781 'sets': 'users/%s/playlists',
782 'reposts': 'stream/users/%s/reposts',
783 'likes': 'users/%s/likes',
784 'spotlight': 'users/%s/spotlight',
785 }
786
787 def _real_extract(self, url):
788 mobj = self._match_valid_url(url)
789 uploader = mobj.group('user')
790
791 user = self._download_json(
792 self._resolv_url(self._BASE_URL + uploader),
793 uploader, 'Downloading user info', headers=self._HEADERS)
794
795 resource = mobj.group('rsrc') or 'all'
796
797 return self._extract_playlist(
798 self._API_V2_BASE + self._BASE_URL_MAP[resource] % user['id'],
799 str_or_none(user.get('id')),
800 '%s (%s)' % (user['username'], resource.capitalize()))
801
802
803 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
804 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
805 IE_NAME = 'soundcloud:trackstation'
806 _TESTS = [{
807 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
808 'info_dict': {
809 'id': '286017854',
810 'title': 'Track station: your text',
811 },
812 'playlist_mincount': 47,
813 }]
814
815 def _real_extract(self, url):
816 track_name = self._match_id(url)
817
818 track = self._download_json(self._resolv_url(url), track_name, headers=self._HEADERS)
819 track_id = self._search_regex(
820 r'soundcloud:track-stations:(\d+)', track['id'], 'track id')
821
822 return self._extract_playlist(
823 self._API_V2_BASE + 'stations/%s/tracks' % track['id'],
824 track_id, 'Track station: %s' % track['title'])
825
826
827 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
828 _VALID_URL = r'https?://api(?:-v2)?\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
829 IE_NAME = 'soundcloud:playlist'
830 _TESTS = [{
831 'url': 'https://api.soundcloud.com/playlists/4110309',
832 'info_dict': {
833 'id': '4110309',
834 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
835 'description': 're:.*?TILT Brass - Bowery Poetry Club',
836 },
837 'playlist_count': 6,
838 }]
839
840 def _real_extract(self, url):
841 mobj = self._match_valid_url(url)
842 playlist_id = mobj.group('id')
843
844 query = {}
845 token = mobj.group('token')
846 if token:
847 query['secret_token'] = token
848
849 data = self._download_json(
850 self._API_V2_BASE + 'playlists/' + playlist_id,
851 playlist_id, 'Downloading playlist', query=query, headers=self._HEADERS)
852
853 return self._extract_set(data, token)
854
855
856 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
857 IE_NAME = 'soundcloud:search'
858 IE_DESC = 'Soundcloud search, "scsearch" keyword'
859 _MAX_RESULTS = float('inf')
860 _TESTS = [{
861 'url': 'scsearch15:post-avant jazzcore',
862 'info_dict': {
863 'title': 'post-avant jazzcore',
864 },
865 'playlist_count': 15,
866 }]
867
868 _SEARCH_KEY = 'scsearch'
869 _MAX_RESULTS_PER_PAGE = 200
870 _DEFAULT_RESULTS_PER_PAGE = 50
871
872 def _get_collection(self, endpoint, collection_id, **query):
873 limit = min(
874 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
875 self._MAX_RESULTS_PER_PAGE)
876 query.update({
877 'limit': limit,
878 'linked_partitioning': 1,
879 'offset': 0,
880 })
881 next_url = update_url_query(self._API_V2_BASE + endpoint, query)
882
883 for i in itertools.count(1):
884 response = self._download_json(
885 next_url, collection_id, f'Downloading page {i}',
886 'Unable to download API page', headers=self._HEADERS)
887
888 for item in response.get('collection') or []:
889 if item:
890 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
891
892 next_url = response.get('next_href')
893 if not next_url:
894 break
895
896 def _get_n_results(self, query, n):
897 tracks = self._get_collection('search/tracks', query, limit=n, q=query)
898 return self.playlist_result(tracks, query, query)