]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/soundcloud.py
[soundcloud] Refetch `client_id` on 403
[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 compat_urlparse,
18 )
19 from ..utils import (
20 error_to_compat_str,
21 ExtractorError,
22 float_or_none,
23 HEADRequest,
24 int_or_none,
25 KNOWN_EXTENSIONS,
26 mimetype2ext,
27 str_or_none,
28 try_get,
29 unified_timestamp,
30 update_url_query,
31 url_or_none,
32 urlhandle_detect_ext,
33 sanitized_Request,
34 )
35
36
37 class SoundcloudEmbedIE(InfoExtractor):
38 _VALID_URL = r'https?://(?:w|player|p)\.soundcloud\.com/player/?.*?\burl=(?P<id>.+)'
39 _TEST = {
40 # from https://www.soundi.fi/uutiset/ennakkokuuntelussa-timo-kaukolammen-station-to-station-to-station-julkaisua-juhlitaan-tanaan-g-livelabissa/
41 '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',
42 'only_matching': True,
43 }
44
45 @staticmethod
46 def _extract_urls(webpage):
47 return [m.group('url') for m in re.finditer(
48 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
49 webpage)]
50
51 def _real_extract(self, url):
52 query = compat_urlparse.parse_qs(
53 compat_urlparse.urlparse(url).query)
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 'fSSdm5yTnDka1g0Fz1CO5Yx6z0NbeHAj'
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 = re.match(self._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 = re.match(self._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 # Per the SoundCloud documentation, the maximum limit for a linked partitioning query is 200.
660 # https://developers.soundcloud.com/blog/offset-pagination-deprecated
661 COMMON_QUERY = {
662 'limit': 200,
663 'linked_partitioning': '1',
664 }
665
666 query = COMMON_QUERY.copy()
667 query['offset'] = 0
668
669 next_href = base_url
670
671 entries = []
672 for i in itertools.count():
673 response = self._download_json(
674 next_href, playlist_id,
675 'Downloading track page %s' % (i + 1), query=query, headers=self._HEADERS)
676
677 collection = response['collection']
678
679 if not isinstance(collection, list):
680 collection = []
681
682 # Empty collection may be returned, in this case we proceed
683 # straight to next_href
684
685 def resolve_entry(candidates):
686 for cand in candidates:
687 if not isinstance(cand, dict):
688 continue
689 permalink_url = url_or_none(cand.get('permalink_url'))
690 if not permalink_url:
691 continue
692 return self.url_result(
693 permalink_url,
694 SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
695 str_or_none(cand.get('id')), cand.get('title'))
696
697 for e in collection:
698 entry = resolve_entry((e, e.get('track'), e.get('playlist')))
699 if entry:
700 entries.append(entry)
701
702 next_href = response.get('next_href')
703 if not next_href:
704 break
705
706 next_href = response['next_href']
707 parsed_next_href = compat_urlparse.urlparse(next_href)
708 query = compat_urlparse.parse_qs(parsed_next_href.query)
709 query.update(COMMON_QUERY)
710
711 return {
712 '_type': 'playlist',
713 'id': playlist_id,
714 'title': playlist_title,
715 'entries': entries,
716 }
717
718
719 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
720 _VALID_URL = r'''(?x)
721 https?://
722 (?:(?:www|m)\.)?soundcloud\.com/
723 (?P<user>[^/]+)
724 (?:/
725 (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
726 )?
727 /?(?:[?#].*)?$
728 '''
729 IE_NAME = 'soundcloud:user'
730 _TESTS = [{
731 'url': 'https://soundcloud.com/soft-cell-official',
732 'info_dict': {
733 'id': '207965082',
734 'title': 'Soft Cell (All)',
735 },
736 'playlist_mincount': 28,
737 }, {
738 'url': 'https://soundcloud.com/soft-cell-official/tracks',
739 'info_dict': {
740 'id': '207965082',
741 'title': 'Soft Cell (Tracks)',
742 },
743 'playlist_mincount': 27,
744 }, {
745 'url': 'https://soundcloud.com/soft-cell-official/albums',
746 'info_dict': {
747 'id': '207965082',
748 'title': 'Soft Cell (Albums)',
749 },
750 'playlist_mincount': 1,
751 }, {
752 'url': 'https://soundcloud.com/jcv246/sets',
753 'info_dict': {
754 'id': '12982173',
755 'title': 'Jordi / cv (Sets)',
756 },
757 'playlist_mincount': 2,
758 }, {
759 'url': 'https://soundcloud.com/jcv246/reposts',
760 'info_dict': {
761 'id': '12982173',
762 'title': 'Jordi / cv (Reposts)',
763 },
764 'playlist_mincount': 6,
765 }, {
766 'url': 'https://soundcloud.com/clalberg/likes',
767 'info_dict': {
768 'id': '11817582',
769 'title': 'clalberg (Likes)',
770 },
771 'playlist_mincount': 5,
772 }, {
773 'url': 'https://soundcloud.com/grynpyret/spotlight',
774 'info_dict': {
775 'id': '7098329',
776 'title': 'Grynpyret (Spotlight)',
777 },
778 'playlist_mincount': 1,
779 }]
780
781 _BASE_URL_MAP = {
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',
789 }
790
791 def _real_extract(self, url):
792 mobj = re.match(self._VALID_URL, url)
793 uploader = mobj.group('user')
794
795 user = self._download_json(
796 self._resolv_url(self._BASE_URL + uploader),
797 uploader, 'Downloading user info', headers=self._HEADERS)
798
799 resource = mobj.group('rsrc') or 'all'
800
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()))
805
806
807 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
808 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
809 IE_NAME = 'soundcloud:trackstation'
810 _TESTS = [{
811 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
812 'info_dict': {
813 'id': '286017854',
814 'title': 'Track station: your text',
815 },
816 'playlist_mincount': 47,
817 }]
818
819 def _real_extract(self, url):
820 track_name = self._match_id(url)
821
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')
825
826 return self._extract_playlist(
827 self._API_V2_BASE + 'stations/%s/tracks' % track['id'],
828 track_id, 'Track station: %s' % track['title'])
829
830
831 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
832 _VALID_URL = r'https?://api(?:-v2)?\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
833 IE_NAME = 'soundcloud:playlist'
834 _TESTS = [{
835 'url': 'https://api.soundcloud.com/playlists/4110309',
836 'info_dict': {
837 'id': '4110309',
838 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
839 'description': 're:.*?TILT Brass - Bowery Poetry Club',
840 },
841 'playlist_count': 6,
842 }]
843
844 def _real_extract(self, url):
845 mobj = re.match(self._VALID_URL, url)
846 playlist_id = mobj.group('id')
847
848 query = {}
849 token = mobj.group('token')
850 if token:
851 query['secret_token'] = token
852
853 data = self._download_json(
854 self._API_V2_BASE + 'playlists/' + playlist_id,
855 playlist_id, 'Downloading playlist', query=query, headers=self._HEADERS)
856
857 return self._extract_set(data, token)
858
859
860 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
861 IE_NAME = 'soundcloud:search'
862 IE_DESC = 'Soundcloud search'
863 _MAX_RESULTS = float('inf')
864 _TESTS = [{
865 'url': 'scsearch15:post-avant jazzcore',
866 'info_dict': {
867 'title': 'post-avant jazzcore',
868 },
869 'playlist_count': 15,
870 }]
871
872 _SEARCH_KEY = 'scsearch'
873 _MAX_RESULTS_PER_PAGE = 200
874 _DEFAULT_RESULTS_PER_PAGE = 50
875
876 def _get_collection(self, endpoint, collection_id, **query):
877 limit = min(
878 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
879 self._MAX_RESULTS_PER_PAGE)
880 query.update({
881 'limit': limit,
882 'linked_partitioning': 1,
883 'offset': 0,
884 })
885 next_url = update_url_query(self._API_V2_BASE + endpoint, query)
886
887 collected_results = 0
888
889 for i in itertools.count(1):
890 response = self._download_json(
891 next_url, collection_id, 'Downloading page {0}'.format(i),
892 'Unable to download API page', headers=self._HEADERS)
893
894 collection = response.get('collection', [])
895 if not collection:
896 break
897
898 collection = list(filter(bool, collection))
899 collected_results += len(collection)
900
901 for item in collection:
902 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
903
904 if not collection or collected_results >= limit:
905 break
906
907 next_url = response.get('next_href')
908 if not next_url:
909 break
910
911 def _get_n_results(self, query, n):
912 tracks = self._get_collection('search/tracks', query, limit=n, q=query)
913 return self.playlist_result(tracks, playlist_title=query)