]> jfr.im git - yt-dlp.git/blob - youtube_dl/extractor/soundcloud.py
[skip travis] adding automerge support
[yt-dlp.git] / youtube_dl / 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-dlc-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/oddsamples/bus-brakes',
168 'md5': '7624f2351f8a3b2e7cd51522496e7631',
169 'info_dict': {
170 'id': '128590877',
171 'ext': 'mp3',
172 'title': 'Bus Brakes',
173 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
174 'uploader': 'oddsamples',
175 'uploader_id': '73680509',
176 'timestamp': 1389232924,
177 'upload_date': '20140109',
178 'duration': 17.346,
179 'license': 'cc-by-sa',
180 'view_count': int,
181 'like_count': int,
182 'comment_count': int,
183 'repost_count': int,
184 },
185 },
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',
196 'uploader_id': '12563093',
197 'timestamp': 1504206263,
198 'upload_date': '20170831',
199 'duration': 7449.096,
200 'license': 'all-rights-reserved',
201 'view_count': int,
202 'like_count': int,
203 'comment_count': int,
204 'repost_count': int,
205 },
206 },
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',
217 'uploader_id': '2366352',
218 'timestamp': 1488152409,
219 'upload_date': '20170226',
220 'duration': 207.012,
221 'thumbnail': r're:https?://.*\.jpg',
222 'license': 'all-rights-reserved',
223 'view_count': int,
224 'like_count': int,
225 'comment_count': int,
226 'repost_count': int,
227 },
228 'params': {
229 'skip_download': True,
230 },
231 },
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',
240 'uploader': 'Micronie',
241 'uploader_id': '3352531',
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 },
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 },
258 ]
259
260 _API_V2_BASE = 'https://api-v2.soundcloud.com/'
261 _BASE_URL = 'https://soundcloud.com/'
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 }
276
277 def _store_client_id(self, client_id):
278 self._downloader.cache.store('soundcloud', 'client_id', client_id)
279
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
290 self._store_client_id(client_id)
291 return
292 raise ExtractorError('Unable to extract client id')
293
294 def _download_json(self, *args, **kwargs):
295 non_fatal = kwargs.get('fatal') is False
296 if non_fatal:
297 del kwargs['fatal']
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:
306 self._store_client_id(None)
307 self._update_client_id()
308 continue
309 elif non_fatal:
310 self._downloader.report_warning(error_to_compat_str(e))
311 return False
312 raise
313
314 def _real_initialize(self):
315 self._CLIENT_ID = self._downloader.cache.load('soundcloud', 'client_id') or "T5R4kgWS2PRf6lzLyIravUMnKlbIxQag" # 'EXLwg5lHTO2dslU5EePe3xkw0m1h86Cd' # 'YUKXoArFcqrlQn9tfNHvvyfnDISj04zk'
316 self._login()
317
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"
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
322 _HEADERS = {}
323 _NETRC_MACHINE = 'soundcloud'
324
325 def _login(self):
326 username, password = self._get_login_info()
327 if username is None:
328 return
329
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
335 payload = {
336 'client_id': self._CLIENT_ID,
337 'recaptcha_pubkey': 'null',
338 'recaptcha_response': 'null',
339 'credentials': {
340 'identifier': username,
341 'password': password
342 },
343 'signature': self.sign(username, password, self._CLIENT_ID),
344 'device_id': genDevId(),
345 'user_agent': self._USER_AGENT
346 }
347
348 query = self._API_AUTH_QUERY_TEMPLATE % self._CLIENT_ID
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
357 # signature generation
358 def sign(self, user, pw, clid):
359 a = 33
360 i = 1
361 s = 440123
362 w = 117
363 u = 1800000
364 l = 1042
365 b = 37
366 k = 37
367 c = 5
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
373
374 d = '-'.join([str(mInt) for mInt in [a, i, s, w, u, l, b, k]])
375 p = n + y + d + r + e + t + d + n
376 h = p
377
378 m = 8011470
379 f = 0
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
391 @classmethod
392 def _resolv_url(cls, url):
393 return SoundcloudIE._API_V2_BASE + 'resolve?url=' + url
394
395 def _extract_info_dict(self, info, full_title=None, secret_token=None):
396 track_id = compat_str(info['id'])
397 title = info['title']
398
399 format_urls = set()
400 formats = []
401 query = {'client_id': self._CLIENT_ID}
402 if secret_token:
403 query['secret_token'] = secret_token
404
405 if info.get('downloadable') and info.get('has_downloads_left'):
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 })
422
423 def invalid_url(url):
424 return not url or url in format_urls
425
426 def add_format(f, protocol, is_preview=False):
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)
435 ext = f.get('ext')
436 if ext == 'aac':
437 f['abr'] = '256'
438 for k in ('ext', 'abr'):
439 v = f.get(k)
440 if v:
441 format_id_list.append(v)
442 preview = is_preview or re.search(r'/(?:preview|playlist)/0/30/', f['url'])
443 if preview:
444 format_id_list.append('preview')
445 abr = f.get('abr')
446 if abr:
447 f['abr'] = int(abr)
448 if protocol == 'hls':
449 protocol = 'm3u8' if ext == 'aac' else 'm3u8_native'
450 else:
451 protocol = 'http'
452 f.update({
453 'format_id': '_'.join(format_id_list),
454 'protocol': protocol,
455 'preference': -10 if preview else None,
456 })
457 formats.append(f)
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):
464 continue
465 format_url = url_or_none(t.get('url'))
466 if not format_url:
467 continue
468 stream = self._download_json(
469 format_url, track_id, query=query, fatal=False, headers=self._HEADERS)
470 if not isinstance(stream, dict):
471 continue
472 stream_url = url_or_none(stream.get('url'))
473 if invalid_url(stream_url):
474 continue
475 format_urls.add(stream_url)
476 stream_format = t.get('format') or {}
477 protocol = stream_format.get('protocol')
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]
484 if ext not in KNOWN_EXTENSIONS:
485 ext = mimetype2ext(stream_format.get('mime_type'))
486 add_format({
487 'url': stream_url,
488 'ext': ext,
489 }, 'http' if protocol == 'progressive' else protocol,
490 t.get('snipped') or '/preview/' in format_url)
491
492 for f in formats:
493 f['vcodec'] = 'none'
494
495 if not formats and info.get('policy') == 'BLOCK':
496 self.raise_geo_restricted()
497 self._sort_formats(formats)
498
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 }
546
547 def _real_extract(self, url):
548 mobj = re.match(self._VALID_URL, url)
549
550 track_id = mobj.group('track_id')
551
552 query = {}
553 if track_id:
554 info_json_url = self._API_V2_BASE + 'tracks/' + track_id
555 full_title = track_id
556 token = mobj.group('secret_token')
557 if token:
558 query['secret_token'] = token
559 else:
560 full_title = resolve_title = '%s/%s' % mobj.group('uploader', 'title')
561 token = mobj.group('token')
562 if token:
563 resolve_title += '/%s' % token
564 info_json_url = self._resolv_url(self._BASE_URL + resolve_title)
565
566 info = self._download_json(
567 info_json_url, full_title, 'Downloading info JSON', query=query, headers=self._HEADERS)
568
569 return self._extract_info_dict(info, full_title, token)
570
571
572 class SoundcloudPlaylistBaseIE(SoundcloudIE):
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,
583 }, headers=self._HEADERS)
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))
596 return self.playlist_result(
597 entries, playlist_id,
598 playlist.get('title'),
599 playlist.get('description'))
600
601
602 class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
603 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
604 IE_NAME = 'soundcloud:set'
605 _TESTS = [{
606 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
607 'info_dict': {
608 'id': '2284613',
609 'title': 'The Royal Concept EP',
610 'description': 'md5:71d07087c7a449e8941a70a29e34671e',
611 },
612 'playlist_mincount': 5,
613 }, {
614 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
615 'only_matching': True,
616 }]
617
618 def _real_extract(self, url):
619 mobj = re.match(self._VALID_URL, url)
620
621 full_title = '%s/sets/%s' % mobj.group('uploader', 'slug_title')
622 token = mobj.group('token')
623 if token:
624 full_title += '/' + token
625
626 info = self._download_json(self._resolv_url(
627 self._BASE_URL + full_title), full_title, headers=self._HEADERS)
628
629 if 'errors' in info:
630 msgs = (compat_str(err['error_message']) for err in info['errors'])
631 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
632
633 return self._extract_set(info, token)
634
635
636 class SoundcloudPagedPlaylistBaseIE(SoundcloudIE):
637 def _extract_playlist(self, base_url, playlist_id, playlist_title):
638 COMMON_QUERY = {
639 'limit': 80000,
640 'linked_partitioning': '1',
641 }
642
643 query = COMMON_QUERY.copy()
644 query['offset'] = 0
645
646 next_href = base_url
647
648 entries = []
649 for i in itertools.count():
650 response = self._download_json(
651 next_href, playlist_id,
652 'Downloading track page %s' % (i + 1), query=query, headers=self._HEADERS)
653
654 collection = response['collection']
655
656 if not isinstance(collection, list):
657 collection = []
658
659 # Empty collection may be returned, in this case we proceed
660 # straight to next_href
661
662 def resolve_entry(candidates):
663 for cand in candidates:
664 if not isinstance(cand, dict):
665 continue
666 permalink_url = url_or_none(cand.get('permalink_url'))
667 if not permalink_url:
668 continue
669 return self.url_result(
670 permalink_url,
671 SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
672 str_or_none(cand.get('id')), cand.get('title'))
673
674 for e in collection:
675 entry = resolve_entry((e, e.get('track'), e.get('playlist')))
676 if entry:
677 entries.append(entry)
678
679 next_href = response.get('next_href')
680 if not next_href:
681 break
682
683 next_href = response['next_href']
684 parsed_next_href = compat_urlparse.urlparse(next_href)
685 query = compat_urlparse.parse_qs(parsed_next_href.query)
686 query.update(COMMON_QUERY)
687
688 return {
689 '_type': 'playlist',
690 'id': playlist_id,
691 'title': playlist_title,
692 'entries': entries,
693 }
694
695
696 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
697 _VALID_URL = r'''(?x)
698 https?://
699 (?:(?:www|m)\.)?soundcloud\.com/
700 (?P<user>[^/]+)
701 (?:/
702 (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
703 )?
704 /?(?:[?#].*)?$
705 '''
706 IE_NAME = 'soundcloud:user'
707 _TESTS = [{
708 'url': 'https://soundcloud.com/soft-cell-official',
709 'info_dict': {
710 'id': '207965082',
711 'title': 'Soft Cell (All)',
712 },
713 'playlist_mincount': 28,
714 }, {
715 'url': 'https://soundcloud.com/soft-cell-official/tracks',
716 'info_dict': {
717 'id': '207965082',
718 'title': 'Soft Cell (Tracks)',
719 },
720 'playlist_mincount': 27,
721 }, {
722 'url': 'https://soundcloud.com/soft-cell-official/albums',
723 'info_dict': {
724 'id': '207965082',
725 'title': 'Soft Cell (Albums)',
726 },
727 'playlist_mincount': 1,
728 }, {
729 'url': 'https://soundcloud.com/jcv246/sets',
730 'info_dict': {
731 'id': '12982173',
732 'title': 'Jordi / cv (Sets)',
733 },
734 'playlist_mincount': 2,
735 }, {
736 'url': 'https://soundcloud.com/jcv246/reposts',
737 'info_dict': {
738 'id': '12982173',
739 'title': 'Jordi / cv (Reposts)',
740 },
741 'playlist_mincount': 6,
742 }, {
743 'url': 'https://soundcloud.com/clalberg/likes',
744 'info_dict': {
745 'id': '11817582',
746 'title': 'clalberg (Likes)',
747 },
748 'playlist_mincount': 5,
749 }, {
750 'url': 'https://soundcloud.com/grynpyret/spotlight',
751 'info_dict': {
752 'id': '7098329',
753 'title': 'Grynpyret (Spotlight)',
754 },
755 'playlist_mincount': 1,
756 }]
757
758 _BASE_URL_MAP = {
759 'all': 'stream/users/%s',
760 'tracks': 'users/%s/tracks',
761 'albums': 'users/%s/albums',
762 'sets': 'users/%s/playlists',
763 'reposts': 'stream/users/%s/reposts',
764 'likes': 'users/%s/likes',
765 'spotlight': 'users/%s/spotlight',
766 }
767
768 def _real_extract(self, url):
769 mobj = re.match(self._VALID_URL, url)
770 uploader = mobj.group('user')
771
772 user = self._download_json(
773 self._resolv_url(self._BASE_URL + uploader),
774 uploader, 'Downloading user info', headers=self._HEADERS)
775
776 resource = mobj.group('rsrc') or 'all'
777
778 return self._extract_playlist(
779 self._API_V2_BASE + self._BASE_URL_MAP[resource] % user['id'],
780 str_or_none(user.get('id')),
781 '%s (%s)' % (user['username'], resource.capitalize()))
782
783
784 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
785 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
786 IE_NAME = 'soundcloud:trackstation'
787 _TESTS = [{
788 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
789 'info_dict': {
790 'id': '286017854',
791 'title': 'Track station: your text',
792 },
793 'playlist_mincount': 47,
794 }]
795
796 def _real_extract(self, url):
797 track_name = self._match_id(url)
798
799 track = self._download_json(self._resolv_url(url), track_name, headers=self._HEADERS)
800 track_id = self._search_regex(
801 r'soundcloud:track-stations:(\d+)', track['id'], 'track id')
802
803 return self._extract_playlist(
804 self._API_V2_BASE + 'stations/%s/tracks' % track['id'],
805 track_id, 'Track station: %s' % track['title'])
806
807
808 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
809 _VALID_URL = r'https?://api(?:-v2)?\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
810 IE_NAME = 'soundcloud:playlist'
811 _TESTS = [{
812 'url': 'https://api.soundcloud.com/playlists/4110309',
813 'info_dict': {
814 'id': '4110309',
815 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
816 'description': 're:.*?TILT Brass - Bowery Poetry Club',
817 },
818 'playlist_count': 6,
819 }]
820
821 def _real_extract(self, url):
822 mobj = re.match(self._VALID_URL, url)
823 playlist_id = mobj.group('id')
824
825 query = {}
826 token = mobj.group('token')
827 if token:
828 query['secret_token'] = token
829
830 data = self._download_json(
831 self._API_V2_BASE + 'playlists/' + playlist_id,
832 playlist_id, 'Downloading playlist', query=query, headers=self._HEADERS)
833
834 return self._extract_set(data, token)
835
836
837 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
838 IE_NAME = 'soundcloud:search'
839 IE_DESC = 'Soundcloud search'
840 _MAX_RESULTS = float('inf')
841 _TESTS = [{
842 'url': 'scsearch15:post-avant jazzcore',
843 'info_dict': {
844 'title': 'post-avant jazzcore',
845 },
846 'playlist_count': 15,
847 }]
848
849 _SEARCH_KEY = 'scsearch'
850 _MAX_RESULTS_PER_PAGE = 200
851 _DEFAULT_RESULTS_PER_PAGE = 50
852
853 def _get_collection(self, endpoint, collection_id, **query):
854 limit = min(
855 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
856 self._MAX_RESULTS_PER_PAGE)
857 query.update({
858 'limit': limit,
859 'linked_partitioning': 1,
860 'offset': 0,
861 })
862 next_url = update_url_query(self._API_V2_BASE + endpoint, query)
863
864 collected_results = 0
865
866 for i in itertools.count(1):
867 response = self._download_json(
868 next_url, collection_id, 'Downloading page {0}'.format(i),
869 'Unable to download API page', headers=self._HEADERS)
870
871 collection = response.get('collection', [])
872 if not collection:
873 break
874
875 collection = list(filter(bool, collection))
876 collected_results += len(collection)
877
878 for item in collection:
879 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
880
881 if not collection or collected_results >= limit:
882 break
883
884 next_url = response.get('next_href')
885 if not next_url:
886 break
887
888 def _get_n_results(self, query, n):
889 tracks = self._get_collection('search/tracks', query, limit=n, q=query)
890 return self.playlist_result(tracks, playlist_title=query)