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