]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/soundcloud.py
release 2020.01.24
[yt-dlp.git] / youtube_dl / extractor / soundcloud.py
CommitLineData
dcdb292f 1# coding: utf-8
fbcd7b5f
PH
2from __future__ import unicode_literals
3
92790f4e 4import itertools
73602bcd 5import re
aad0d6d5 6
2abf7cab 7from .common import (
8 InfoExtractor,
9 SearchInfoExtractor
10)
1cc79574 11from ..compat import (
3bed6217
RA
12 compat_HTTPError,
13 compat_kwargs,
aad0d6d5 14 compat_str,
668de34c 15 compat_urlparse,
1cc79574
PH
16)
17from ..utils import (
de7aade2 18 error_to_compat_str,
aad0d6d5 19 ExtractorError,
e09965d5 20 float_or_none,
548c3957 21 HEADRequest,
eb920777 22 int_or_none,
e09965d5 23 KNOWN_EXTENSIONS,
e09965d5
S
24 mimetype2ext,
25 str_or_none,
f516f440
S
26 try_get,
27 unified_timestamp,
d7c7100e 28 update_url_query,
7c5307f4 29 url_or_none,
d7c7100e 30)
aad0d6d5
PH
31
32
548c3957 33class SoundcloudEmbedIE(InfoExtractor):
cf80ff18
RA
34 _VALID_URL = r'https?://(?:w|player|p)\.soundcloud\.com/player/?.*?\burl=(?P<id>.+)'
35 _TEST = {
36 # from https://www.soundi.fi/uutiset/ennakkokuuntelussa-timo-kaukolammen-station-to-station-to-station-julkaisua-juhlitaan-tanaan-g-livelabissa/
37 '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',
38 'only_matching': True,
39 }
548c3957
RA
40
41 @staticmethod
42 def _extract_urls(webpage):
43 return [m.group('url') for m in re.finditer(
44 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
45 webpage)]
46
47 def _real_extract(self, url):
cf80ff18
RA
48 query = compat_urlparse.parse_qs(
49 compat_urlparse.urlparse(url).query)
50 api_url = query['url'][0]
51 secret_token = query.get('secret_token')
52 if secret_token:
53 api_url = update_url_query(api_url, {'secret_token': secret_token[0]})
54 return self.url_result(api_url)
548c3957
RA
55
56
aad0d6d5
PH
57class SoundcloudIE(InfoExtractor):
58 """Information extractor for soundcloud.com
59 To access the media, the uid of the song and a stream token
60 must be extracted from the page source and the script must make
61 a request to media.soundcloud.com/crossdomain.xml. Then
62 the media can be grabbed by requesting from an url composed
63 of the stream token and uid
64 """
65
20991253 66 _VALID_URL = r'''(?x)^(?:https?://)?
71507a11 67 (?:(?:(?:www\.|m\.)?soundcloud\.com/
836ef264 68 (?!stations/track)
4ff50ef8 69 (?P<uploader>[\w\d-]+)/
3ef2da2d 70 (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
22a6f150 71 (?P<title>[\w\d-]+)/?
de2dd4c5 72 (?P<token>[^?]+?)?(?:[?].*)?$)
548c3957 73 |(?:api(?:-v2)?\.soundcloud\.com/tracks/(?P<track_id>\d+)
0403b069 74 (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
eb6a41ba
JMF
75 )
76 '''
fbcd7b5f 77 IE_NAME = 'soundcloud'
12c167c8
JMF
78 _TESTS = [
79 {
fbcd7b5f 80 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
fbcd7b5f
PH
81 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
82 'info_dict': {
0eb9fb9f
JMF
83 'id': '62986583',
84 'ext': 'mp3',
f516f440 85 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
0eb9fb9f
JMF
86 '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',
87 'uploader': 'E.T. ExTerrestrial Music',
548c3957 88 'uploader_id': '1571244',
f516f440
S
89 'timestamp': 1349920598,
90 'upload_date': '20121011',
e09965d5 91 'duration': 143.216,
4bfd294e 92 'license': 'all-rights-reserved',
f516f440
S
93 'view_count': int,
94 'like_count': int,
95 'comment_count': int,
96 'repost_count': int,
12c167c8
JMF
97 }
98 },
e4e5fa6e 99 # not streamable song, preview
12c167c8 100 {
fbcd7b5f
PH
101 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
102 'info_dict': {
103 'id': '47127627',
104 'ext': 'mp3',
105 'title': 'Goldrushed',
63ad0315 106 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
fbcd7b5f 107 'uploader': 'The Royal Concept',
548c3957 108 'uploader_id': '9615865',
f516f440 109 'timestamp': 1337635207,
fbcd7b5f 110 'upload_date': '20120521',
f516f440 111 'duration': 30,
4bfd294e 112 'license': 'all-rights-reserved',
f516f440
S
113 'view_count': int,
114 'like_count': int,
115 'comment_count': int,
116 'repost_count': int,
12c167c8 117 },
fbcd7b5f 118 'params': {
12c167c8 119 # rtmp
fbcd7b5f 120 'skip_download': True,
12c167c8
JMF
121 },
122 },
de2dd4c5
JMF
123 # private link
124 {
fbcd7b5f
PH
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 \'\' Ä↭',
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 },
843ad179 232 # not available via api.soundcloud.com/i1/tracks/id/streams
e09965d5
S
233 {
234 'url': 'https://soundcloud.com/giovannisarani/mezzo-valzer',
235 'md5': 'e22aecd2bc88e0e4e432d7dcc0a1abf7',
236 'info_dict': {
237 'id': '583011102',
238 'ext': 'mp3',
239 'title': 'Mezzo Valzer',
240 'description': 'md5:4138d582f81866a530317bae316e8b61',
241 'uploader': 'Giovanni Sarani',
548c3957 242 'uploader_id': '3352531',
e09965d5
S
243 'timestamp': 1551394171,
244 'upload_date': '20190228',
245 'duration': 180.157,
246 'thumbnail': r're:https?://.*\.jpg',
247 'license': 'all-rights-reserved',
248 'view_count': int,
249 'like_count': int,
250 'comment_count': int,
251 'repost_count': int,
252 },
253 'expected_warnings': ['Unable to download JSON metadata'],
254 }
12c167c8 255 ]
aad0d6d5 256
548c3957
RA
257 _API_BASE = 'https://api.soundcloud.com/'
258 _API_V2_BASE = 'https://api-v2.soundcloud.com/'
259 _BASE_URL = 'https://soundcloud.com/'
548c3957
RA
260 _IMAGE_REPL_RE = r'-([0-9a-z]+)\.jpg'
261
262 _ARTWORK_MAP = {
263 'mini': 16,
264 'tiny': 20,
265 'small': 32,
266 'badge': 47,
267 't67x67': 67,
268 'large': 100,
269 't300x300': 300,
270 'crop': 400,
271 't500x500': 500,
272 'original': 0,
273 }
fbdf8d15 274
de7aade2
RA
275 def _store_client_id(self, client_id):
276 self._downloader.cache.store('soundcloud', 'client_id', client_id)
277
3bed6217
RA
278 def _update_client_id(self):
279 webpage = self._download_webpage('https://soundcloud.com/', None)
280 for src in reversed(re.findall(r'<script[^>]+src="([^"]+)"', webpage)):
281 script = self._download_webpage(src, None, fatal=False)
282 if script:
283 client_id = self._search_regex(
284 r'client_id\s*:\s*"([0-9a-zA-Z]{32})"',
285 script, 'client id', default=None)
286 if client_id:
287 self._CLIENT_ID = client_id
de7aade2 288 self._store_client_id(client_id)
3bed6217
RA
289 return
290 raise ExtractorError('Unable to extract client id')
291
292 def _download_json(self, *args, **kwargs):
de7aade2
RA
293 non_fatal = kwargs.get('fatal') is False
294 if non_fatal:
295 del kwargs['fatal']
3bed6217
RA
296 query = kwargs.get('query', {}).copy()
297 for _ in range(2):
298 query['client_id'] = self._CLIENT_ID
299 kwargs['query'] = query
300 try:
301 return super(SoundcloudIE, self)._download_json(*args, **compat_kwargs(kwargs))
302 except ExtractorError as e:
303 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
de7aade2 304 self._store_client_id(None)
3bed6217
RA
305 self._update_client_id()
306 continue
de7aade2
RA
307 elif non_fatal:
308 self._downloader.report_warning(error_to_compat_str(e))
309 return False
3bed6217
RA
310 raise
311
312 def _real_initialize(self):
313 self._CLIENT_ID = self._downloader.cache.load('soundcloud', 'client_id') or 'YUKXoArFcqrlQn9tfNHvvyfnDISj04zk'
314
7d239269
JMF
315 @classmethod
316 def _resolv_url(cls, url):
3bed6217 317 return SoundcloudIE._API_V2_BASE + 'resolve?url=' + url
7d239269 318
548c3957 319 def _extract_info_dict(self, info, full_title=None, secret_token=None, version=2):
12c167c8 320 track_id = compat_str(info['id'])
f516f440 321 title = info['title']
548c3957 322 track_base_url = self._API_BASE + 'tracks/%s' % track_id
e09965d5
S
323
324 format_urls = set()
5e114e4b 325 formats = []
73602bcd 326 query = {'client_id': self._CLIENT_ID}
548c3957 327 if secret_token:
73602bcd 328 query['secret_token'] = secret_token
548c3957 329
2e9ad59a 330 if info.get('downloadable') and info.get('has_downloads_left'):
73602bcd 331 format_url = update_url_query(
548c3957 332 info.get('download_url') or track_base_url + '/download', query)
e09965d5 333 format_urls.add(format_url)
548c3957
RA
334 if version == 2:
335 v1_info = self._download_json(
336 track_base_url, track_id, query=query, fatal=False) or {}
337 else:
338 v1_info = info
5e114e4b 339 formats.append({
2a15e706 340 'format_id': 'download',
548c3957
RA
341 'ext': v1_info.get('original_format') or 'mp3',
342 'filesize': int_or_none(v1_info.get('original_content_size')),
2a15e706 343 'url': format_url,
5e114e4b
PH
344 'preference': 10,
345 })
346
548c3957 347 def invalid_url(url):
e4e5fa6e 348 return not url or url in format_urls
e09965d5 349
e4e5fa6e 350 def add_format(f, protocol, is_preview=False):
548c3957
RA
351 mobj = re.search(r'\.(?P<abr>\d+)\.(?P<ext>[0-9a-z]{3,4})(?=[/?])', stream_url)
352 if mobj:
353 for k, v in mobj.groupdict().items():
354 if not f.get(k):
355 f[k] = v
356 format_id_list = []
357 if protocol:
358 format_id_list.append(protocol)
359 for k in ('ext', 'abr'):
360 v = f.get(k)
361 if v:
362 format_id_list.append(v)
e4e5fa6e
S
363 preview = is_preview or re.search(r'/(?:preview|playlist)/0/30/', f['url'])
364 if preview:
365 format_id_list.append('preview')
548c3957
RA
366 abr = f.get('abr')
367 if abr:
368 f['abr'] = int(abr)
369 f.update({
370 'format_id': '_'.join(format_id_list),
371 'protocol': 'm3u8_native' if protocol == 'hls' else 'http',
e4e5fa6e 372 'preference': -10 if preview else None,
548c3957
RA
373 })
374 formats.append(f)
e09965d5
S
375
376 # New API
377 transcodings = try_get(
378 info, lambda x: x['media']['transcodings'], list) or []
379 for t in transcodings:
380 if not isinstance(t, dict):
3a194cb4 381 continue
e09965d5 382 format_url = url_or_none(t.get('url'))
e4e5fa6e 383 if not format_url:
e09965d5
S
384 continue
385 stream = self._download_json(
548c3957 386 format_url, track_id, query=query, fatal=False)
e09965d5
S
387 if not isinstance(stream, dict):
388 continue
389 stream_url = url_or_none(stream.get('url'))
548c3957 390 if invalid_url(stream_url):
e09965d5
S
391 continue
392 format_urls.add(stream_url)
548c3957
RA
393 stream_format = t.get('format') or {}
394 protocol = stream_format.get('protocol')
e09965d5
S
395 if protocol != 'hls' and '/hls' in format_url:
396 protocol = 'hls'
397 ext = None
398 preset = str_or_none(t.get('preset'))
399 if preset:
400 ext = preset.split('_')[0]
548c3957
RA
401 if ext not in KNOWN_EXTENSIONS:
402 ext = mimetype2ext(stream_format.get('mime_type'))
403 add_format({
e09965d5 404 'url': stream_url,
e09965d5 405 'ext': ext,
e4e5fa6e
S
406 }, 'http' if protocol == 'progressive' else protocol,
407 t.get('snipped') or '/preview/' in format_url)
548c3957
RA
408
409 if not formats:
410 # Old API, does not work for some tracks (e.g.
411 # https://soundcloud.com/giovannisarani/mezzo-valzer)
412 # and might serve preview URLs (e.g.
413 # http://www.soundcloud.com/snbrn/ele)
414 format_dict = self._download_json(
415 track_base_url + '/streams', track_id,
416 'Downloading track url', query=query, fatal=False) or {}
417
418 for key, stream_url in format_dict.items():
419 if invalid_url(stream_url):
420 continue
421 format_urls.add(stream_url)
422 mobj = re.search(r'(http|hls)_([^_]+)_(\d+)_url', key)
423 if mobj:
424 protocol, ext, abr = mobj.groups()
425 add_format({
426 'abr': abr,
427 'ext': ext,
428 'url': stream_url,
429 }, protocol)
3a194cb4
S
430
431 if not formats:
432 # We fallback to the stream_url in the original info, this
433 # cannot be always used, sometimes it can give an HTTP 404 error
548c3957
RA
434 urlh = self._request_webpage(
435 HEADRequest(info.get('stream_url') or track_base_url + '/stream'),
436 track_id, query=query, fatal=False)
437 if urlh:
438 stream_url = urlh.geturl()
439 if not invalid_url(stream_url):
440 add_format({'url': stream_url}, 'http')
3a194cb4
S
441
442 for f in formats:
443 f['vcodec'] = 'none'
2a15e706 444
562ceab1 445 self._sort_formats(formats)
64bb5187 446
548c3957
RA
447 user = info.get('user') or {}
448
449 thumbnails = []
450 artwork_url = info.get('artwork_url')
451 thumbnail = artwork_url or user.get('avatar_url')
452 if isinstance(thumbnail, compat_str):
453 if re.search(self._IMAGE_REPL_RE, thumbnail):
454 for image_id, size in self._ARTWORK_MAP.items():
455 i = {
456 'id': image_id,
457 'url': re.sub(self._IMAGE_REPL_RE, '-%s.jpg' % image_id, thumbnail),
458 }
459 if image_id == 'tiny' and not artwork_url:
460 size = 18
461 elif image_id == 'original':
462 i['preference'] = 10
463 if size:
464 i.update({
465 'width': size,
466 'height': size,
467 })
468 thumbnails.append(i)
469 else:
470 thumbnails = [{'url': thumbnail}]
471
472 def extract_count(key):
473 return int_or_none(info.get('%s_count' % key))
474
475 return {
476 'id': track_id,
477 'uploader': user.get('username'),
478 'uploader_id': str_or_none(user.get('id')) or user.get('permalink'),
479 'uploader_url': user.get('permalink_url'),
480 'timestamp': unified_timestamp(info.get('created_at')),
481 'title': title,
482 'description': info.get('description'),
483 'thumbnails': thumbnails,
484 'duration': float_or_none(info.get('duration'), 1000),
485 'webpage_url': info.get('permalink_url'),
486 'license': info.get('license'),
487 'view_count': extract_count('playback'),
488 'like_count': extract_count('favoritings') or extract_count('likes'),
489 'comment_count': extract_count('comment'),
490 'repost_count': extract_count('reposts'),
491 'genre': info.get('genre'),
492 'formats': formats
493 }
7d239269 494
aad0d6d5 495 def _real_extract(self, url):
548c3957 496 mobj = re.match(self._VALID_URL, url)
aad0d6d5 497
eb6a41ba 498 track_id = mobj.group('track_id')
4bfd294e 499
3bed6217 500 query = {}
548c3957
RA
501 if track_id:
502 info_json_url = self._API_V2_BASE + 'tracks/' + track_id
eb6a41ba 503 full_title = track_id
9296738f 504 token = mobj.group('secret_token')
505 if token:
548c3957 506 query['secret_token'] = token
eb6a41ba 507 else:
548c3957 508 full_title = resolve_title = '%s/%s' % mobj.group('uploader', 'title')
de2dd4c5 509 token = mobj.group('token')
de2dd4c5
JMF
510 if token:
511 resolve_title += '/%s' % token
548c3957 512 info_json_url = self._resolv_url(self._BASE_URL + resolve_title)
5f6a1245 513
548c3957 514 version = 2
e09965d5 515 info = self._download_json(
548c3957
RA
516 info_json_url, full_title, 'Downloading info JSON', query=query, fatal=False)
517 if not info:
518 info = self._download_json(
519 info_json_url.replace(self._API_V2_BASE, self._API_BASE),
520 full_title, 'Downloading info JSON', query=query)
521 version = 1
e09965d5 522
548c3957 523 return self._extract_info_dict(info, full_title, token, version)
aad0d6d5 524
20991253 525
7518a61d 526class SoundcloudPlaylistBaseIE(SoundcloudIE):
548c3957
RA
527 def _extract_track_entries(self, tracks, token=None):
528 entries = []
529 for track in tracks:
530 track_id = str_or_none(track.get('id'))
531 url = track.get('permalink_url')
532 if not url:
533 if not track_id:
534 continue
535 url = self._API_V2_BASE + 'tracks/' + track_id
536 if token:
537 url += '?secret_token=' + token
538 entries.append(self.url_result(
539 url, SoundcloudIE.ie_key(), track_id))
540 return entries
8e45e1cc
S
541
542
7518a61d 543class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
c808ef81 544 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
fbcd7b5f 545 IE_NAME = 'soundcloud:set'
22a6f150
PH
546 _TESTS = [{
547 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
548 'info_dict': {
a9551e90 549 'id': '2284613',
22a6f150
PH
550 'title': 'The Royal Concept EP',
551 },
bf2dc9cc 552 'playlist_mincount': 5,
f7043ef3
S
553 }, {
554 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
555 'only_matching': True,
22a6f150 556 }]
aad0d6d5 557
aad0d6d5
PH
558 def _real_extract(self, url):
559 mobj = re.match(self._VALID_URL, url)
aad0d6d5 560
548c3957 561 full_title = '%s/sets/%s' % mobj.group('uploader', 'slug_title')
2f834e93 562 token = mobj.group('token')
563 if token:
564 full_title += '/' + token
aad0d6d5 565
548c3957
RA
566 info = self._download_json(self._resolv_url(
567 self._BASE_URL + full_title), full_title)
aad0d6d5 568
aad0d6d5 569 if 'errors' in info:
214e74bf
JMF
570 msgs = (compat_str(err['error_message']) for err in info['errors'])
571 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
aad0d6d5 572
548c3957 573 entries = self._extract_track_entries(info['tracks'], token)
b14fa8e6 574
548c3957
RA
575 return self.playlist_result(
576 entries, str_or_none(info.get('id')), info.get('title'))
92790f4e
JMF
577
578
836ef264 579class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
836ef264
S
580 def _extract_playlist(self, base_url, playlist_id, playlist_title):
581 COMMON_QUERY = {
548c3957 582 'limit': 2000000000,
836ef264
S
583 'linked_partitioning': '1',
584 }
585
586 query = COMMON_QUERY.copy()
587 query['offset'] = 0
588
548c3957 589 next_href = base_url
836ef264
S
590
591 entries = []
592 for i in itertools.count():
593 response = self._download_json(
548c3957
RA
594 next_href, playlist_id,
595 'Downloading track page %s' % (i + 1), query=query)
836ef264
S
596
597 collection = response['collection']
3ef2da2d
S
598
599 if not isinstance(collection, list):
600 collection = []
601
602 # Empty collection may be returned, in this case we proceed
603 # straight to next_href
836ef264 604
7c5307f4
S
605 def resolve_entry(candidates):
606 for cand in candidates:
607 if not isinstance(cand, dict):
608 continue
609 permalink_url = url_or_none(cand.get('permalink_url'))
610 if not permalink_url:
611 continue
612 return self.url_result(
613 permalink_url,
548c3957
RA
614 SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
615 str_or_none(cand.get('id')), cand.get('title'))
836ef264
S
616
617 for e in collection:
7c5307f4
S
618 entry = resolve_entry((e, e.get('track'), e.get('playlist')))
619 if entry:
620 entries.append(entry)
836ef264
S
621
622 next_href = response.get('next_href')
623 if not next_href:
624 break
625
548c3957
RA
626 next_href = response['next_href']
627 parsed_next_href = compat_urlparse.urlparse(next_href)
628 query = compat_urlparse.parse_qs(parsed_next_href.query)
629 query.update(COMMON_QUERY)
836ef264
S
630
631 return {
632 '_type': 'playlist',
633 'id': playlist_id,
634 'title': playlist_title,
635 'entries': entries,
636 }
637
638
639class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
16a08978
S
640 _VALID_URL = r'''(?x)
641 https?://
642 (?:(?:www|m)\.)?soundcloud\.com/
643 (?P<user>[^/]+)
644 (?:/
3ef2da2d 645 (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
16a08978
S
646 )?
647 /?(?:[?#].*)?$
648 '''
fbcd7b5f 649 IE_NAME = 'soundcloud:user'
22a6f150 650 _TESTS = [{
b6423e6c 651 'url': 'https://soundcloud.com/soft-cell-official',
22a6f150 652 'info_dict': {
b6423e6c
S
653 'id': '207965082',
654 'title': 'Soft Cell (All)',
22a6f150 655 },
b6423e6c 656 'playlist_mincount': 28,
22a6f150 657 }, {
b6423e6c 658 'url': 'https://soundcloud.com/soft-cell-official/tracks',
22a6f150 659 'info_dict': {
b6423e6c
S
660 'id': '207965082',
661 'title': 'Soft Cell (Tracks)',
22a6f150 662 },
b6423e6c 663 'playlist_mincount': 27,
03b9c944 664 }, {
b6423e6c
S
665 'url': 'https://soundcloud.com/soft-cell-official/albums',
666 'info_dict': {
667 'id': '207965082',
668 'title': 'Soft Cell (Albums)',
669 },
670 'playlist_mincount': 1,
671 }, {
672 'url': 'https://soundcloud.com/jcv246/sets',
80fb6d4a 673 'info_dict': {
b6423e6c 674 'id': '12982173',
548c3957 675 'title': 'Jordi / cv (Sets)',
80fb6d4a 676 },
8e45e1cc 677 'playlist_mincount': 2,
80fb6d4a 678 }, {
b6423e6c 679 'url': 'https://soundcloud.com/jcv246/reposts',
80fb6d4a 680 'info_dict': {
b6423e6c
S
681 'id': '12982173',
682 'title': 'Jordi / cv (Reposts)',
80fb6d4a 683 },
b6423e6c 684 'playlist_mincount': 6,
80fb6d4a 685 }, {
b6423e6c 686 'url': 'https://soundcloud.com/clalberg/likes',
80fb6d4a 687 'info_dict': {
b6423e6c
S
688 'id': '11817582',
689 'title': 'clalberg (Likes)',
80fb6d4a 690 },
b6423e6c 691 'playlist_mincount': 5,
80fb6d4a
S
692 }, {
693 'url': 'https://soundcloud.com/grynpyret/spotlight',
694 'info_dict': {
695 'id': '7098329',
bf2dc9cc 696 'title': 'Grynpyret (Spotlight)',
80fb6d4a
S
697 },
698 'playlist_mincount': 1,
22a6f150 699 }]
92790f4e 700
80fb6d4a 701 _BASE_URL_MAP = {
548c3957
RA
702 'all': 'stream/users/%s',
703 'tracks': 'users/%s/tracks',
704 'albums': 'users/%s/albums',
705 'sets': 'users/%s/playlists',
706 'reposts': 'stream/users/%s/reposts',
707 'likes': 'users/%s/likes',
708 'spotlight': 'users/%s/spotlight',
80fb6d4a
S
709 }
710
92790f4e
JMF
711 def _real_extract(self, url):
712 mobj = re.match(self._VALID_URL, url)
713 uploader = mobj.group('user')
714
20991253 715 user = self._download_json(
548c3957
RA
716 self._resolv_url(self._BASE_URL + uploader),
717 uploader, 'Downloading user info')
80fb6d4a
S
718
719 resource = mobj.group('rsrc') or 'all'
80fb6d4a 720
836ef264 721 return self._extract_playlist(
548c3957
RA
722 self._API_V2_BASE + self._BASE_URL_MAP[resource] % user['id'],
723 str_or_none(user.get('id')),
724 '%s (%s)' % (user['username'], resource.capitalize()))
97afd99a 725
92790f4e 726
836ef264
S
727class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
728 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
729 IE_NAME = 'soundcloud:trackstation'
730 _TESTS = [{
731 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
732 'info_dict': {
733 'id': '286017854',
548c3957 734 'title': 'Track station: your text',
836ef264
S
735 },
736 'playlist_mincount': 47,
737 }]
80fb6d4a 738
836ef264
S
739 def _real_extract(self, url):
740 track_name = self._match_id(url)
80fb6d4a 741
548c3957 742 track = self._download_json(self._resolv_url(url), track_name)
836ef264 743 track_id = self._search_regex(
548c3957 744 r'soundcloud:track-stations:(\d+)', track['id'], 'track id')
92790f4e 745
836ef264 746 return self._extract_playlist(
548c3957
RA
747 self._API_V2_BASE + 'stations/%s/tracks' % track['id'],
748 track_id, 'Track station: %s' % track['title'])
20991253
PH
749
750
7518a61d 751class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
548c3957 752 _VALID_URL = r'https?://api(?:-v2)?\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
20991253 753 IE_NAME = 'soundcloud:playlist'
46f74bcf 754 _TESTS = [{
f1c05100 755 'url': 'https://api.soundcloud.com/playlists/4110309',
46f74bcf
PH
756 'info_dict': {
757 'id': '4110309',
758 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
759 'description': 're:.*?TILT Brass - Bowery Poetry Club',
760 },
761 'playlist_count': 6,
762 }]
20991253
PH
763
764 def _real_extract(self, url):
765 mobj = re.match(self._VALID_URL, url)
766 playlist_id = mobj.group('id')
20991253 767
3bed6217 768 query = {}
2f834e93 769 token = mobj.group('token')
2f834e93 770 if token:
548c3957 771 query['secret_token'] = token
2f834e93 772
20991253 773 data = self._download_json(
548c3957
RA
774 self._API_V2_BASE + 'playlists/' + playlist_id,
775 playlist_id, 'Downloading playlist', query=query)
20991253 776
548c3957 777 entries = self._extract_track_entries(data['tracks'], token)
20991253 778
548c3957
RA
779 return self.playlist_result(
780 entries, playlist_id, data.get('title'), data.get('description'))
2abf7cab 781
782
783class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
784 IE_NAME = 'soundcloud:search'
785 IE_DESC = 'Soundcloud search'
328a22e1 786 _MAX_RESULTS = float('inf')
2abf7cab 787 _TESTS = [{
788 'url': 'scsearch15:post-avant jazzcore',
789 'info_dict': {
790 'title': 'post-avant jazzcore',
791 },
792 'playlist_count': 15,
793 }]
794
795 _SEARCH_KEY = 'scsearch'
328a22e1 796 _MAX_RESULTS_PER_PAGE = 200
797 _DEFAULT_RESULTS_PER_PAGE = 50
2abf7cab 798
799 def _get_collection(self, endpoint, collection_id, **query):
a3372437 800 limit = min(
328a22e1 801 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
802 self._MAX_RESULTS_PER_PAGE)
548c3957
RA
803 query.update({
804 'limit': limit,
548c3957
RA
805 'linked_partitioning': 1,
806 'offset': 0,
807 })
808 next_url = update_url_query(self._API_V2_BASE + endpoint, query)
2abf7cab 809
2abf7cab 810 collected_results = 0
811
f6c903e7 812 for i in itertools.count(1):
7e347275 813 response = self._download_json(
f6c903e7 814 next_url, collection_id, 'Downloading page {0}'.format(i),
7e347275 815 'Unable to download API page')
2abf7cab 816
f6c903e7
S
817 collection = response.get('collection', [])
818 if not collection:
819 break
2abf7cab 820
f6c903e7 821 collection = list(filter(bool, collection))
2abf7cab 822 collected_results += len(collection)
823
f6c903e7
S
824 for item in collection:
825 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
2abf7cab 826
f6c903e7 827 if not collection or collected_results >= limit:
2abf7cab 828 break
829
7e347275 830 next_url = response.get('next_href')
f6c903e7
S
831 if not next_url:
832 break
2abf7cab 833
834 def _get_n_results(self, query, n):
548c3957 835 tracks = self._get_collection('search/tracks', query, limit=n, q=query)
f6c903e7 836 return self.playlist_result(tracks, playlist_title=query)