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