a1372d38934a67ebc925849b4ac00a13977df70b
[youtube-dl] / youtube_dl / extractor / soundcloud.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import itertools
5 import re
6
7 from .common import (
8     InfoExtractor,
9     SearchInfoExtractor
10 )
11 from ..compat import (
12     compat_HTTPError,
13     compat_kwargs,
14     compat_str,
15     compat_urlparse,
16 )
17 from ..utils import (
18     error_to_compat_str,
19     ExtractorError,
20     float_or_none,
21     HEADRequest,
22     int_or_none,
23     KNOWN_EXTENSIONS,
24     mimetype2ext,
25     str_or_none,
26     try_get,
27     unified_timestamp,
28     update_url_query,
29     url_or_none,
30 )
31
32
33 class SoundcloudEmbedIE(InfoExtractor):
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     }
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):
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)
55
56
57 class 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
66     _VALID_URL = r'''(?x)^(?:https?://)?
67                     (?:(?:(?:www\.|m\.)?soundcloud\.com/
68                             (?!stations/track)
69                             (?P<uploader>[\w\d-]+)/
70                             (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
71                             (?P<title>[\w\d-]+)/?
72                             (?P<token>[^?]+?)?(?:[?].*)?$)
73                        |(?:api(?:-v2)?\.soundcloud\.com/tracks/(?P<track_id>\d+)
74                           (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
75                     )
76                     '''
77     IE_NAME = 'soundcloud'
78     _TESTS = [
79         {
80             'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
81             'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
82             'info_dict': {
83                 'id': '62986583',
84                 'ext': 'mp3',
85                 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
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',
88                 'uploader_id': '1571244',
89                 'timestamp': 1349920598,
90                 'upload_date': '20121011',
91                 'duration': 143.216,
92                 'license': 'all-rights-reserved',
93                 'view_count': int,
94                 'like_count': int,
95                 'comment_count': int,
96                 'repost_count': int,
97             }
98         },
99         # not streamable song, preview
100         {
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',
106                 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
107                 'uploader': 'The Royal Concept',
108                 'uploader_id': '9615865',
109                 'timestamp': 1337635207,
110                 'upload_date': '20120521',
111                 'duration': 30,
112                 'license': 'all-rights-reserved',
113                 'view_count': int,
114                 'like_count': int,
115                 'comment_count': int,
116                 'repost_count': int,
117             },
118             'params': {
119                 # rtmp
120                 'skip_download': True,
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/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         # not available via api.soundcloud.com/i1/tracks/id/streams
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': 'Micronie',
242                 'uploader_id': '3352531',
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         }
255     ]
256
257     _API_BASE = 'https://api.soundcloud.com/'
258     _API_V2_BASE = 'https://api-v2.soundcloud.com/'
259     _BASE_URL = 'https://soundcloud.com/'
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     }
274
275     def _store_client_id(self, client_id):
276         self._downloader.cache.store('soundcloud', 'client_id', client_id)
277
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
288                     self._store_client_id(client_id)
289                     return
290         raise ExtractorError('Unable to extract client id')
291
292     def _download_json(self, *args, **kwargs):
293         non_fatal = kwargs.get('fatal') is False
294         if non_fatal:
295             del kwargs['fatal']
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:
304                     self._store_client_id(None)
305                     self._update_client_id()
306                     continue
307                 elif non_fatal:
308                     self._downloader.report_warning(error_to_compat_str(e))
309                     return False
310                 raise
311
312     def _real_initialize(self):
313         self._CLIENT_ID = self._downloader.cache.load('soundcloud', 'client_id') or 'YUKXoArFcqrlQn9tfNHvvyfnDISj04zk'
314
315     @classmethod
316     def _resolv_url(cls, url):
317         return SoundcloudIE._API_V2_BASE + 'resolve?url=' + url
318
319     def _extract_info_dict(self, info, full_title=None, secret_token=None, version=2):
320         track_id = compat_str(info['id'])
321         title = info['title']
322         track_base_url = self._API_BASE + 'tracks/%s' % track_id
323
324         format_urls = set()
325         formats = []
326         query = {'client_id': self._CLIENT_ID}
327         if secret_token:
328             query['secret_token'] = secret_token
329
330         if info.get('downloadable') and info.get('has_downloads_left'):
331             format_url = update_url_query(
332                 info.get('download_url') or track_base_url + '/download', query)
333             format_urls.add(format_url)
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
339             formats.append({
340                 'format_id': 'download',
341                 'ext': v1_info.get('original_format') or 'mp3',
342                 'filesize': int_or_none(v1_info.get('original_content_size')),
343                 'url': format_url,
344                 'preference': 10,
345             })
346
347         def invalid_url(url):
348             return not url or url in format_urls
349
350         def add_format(f, protocol, is_preview=False):
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)
363             preview = is_preview or re.search(r'/(?:preview|playlist)/0/30/', f['url'])
364             if preview:
365                 format_id_list.append('preview')
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',
372                 'preference': -10 if preview else None,
373             })
374             formats.append(f)
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):
381                 continue
382             format_url = url_or_none(t.get('url'))
383             if not format_url:
384                 continue
385             stream = self._download_json(
386                 format_url, track_id, query=query, fatal=False)
387             if not isinstance(stream, dict):
388                 continue
389             stream_url = url_or_none(stream.get('url'))
390             if invalid_url(stream_url):
391                 continue
392             format_urls.add(stream_url)
393             stream_format = t.get('format') or {}
394             protocol = stream_format.get('protocol')
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]
401             if ext not in KNOWN_EXTENSIONS:
402                 ext = mimetype2ext(stream_format.get('mime_type'))
403             add_format({
404                 'url': stream_url,
405                 'ext': ext,
406             }, 'http' if protocol == 'progressive' else protocol,
407                 t.get('snipped') or '/preview/' in format_url)
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)
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
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')
441
442         for f in formats:
443             f['vcodec'] = 'none'
444
445         self._sort_formats(formats)
446
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         }
494
495     def _real_extract(self, url):
496         mobj = re.match(self._VALID_URL, url)
497
498         track_id = mobj.group('track_id')
499
500         query = {}
501         if track_id:
502             info_json_url = self._API_V2_BASE + 'tracks/' + track_id
503             full_title = track_id
504             token = mobj.group('secret_token')
505             if token:
506                 query['secret_token'] = token
507         else:
508             full_title = resolve_title = '%s/%s' % mobj.group('uploader', 'title')
509             token = mobj.group('token')
510             if token:
511                 resolve_title += '/%s' % token
512             info_json_url = self._resolv_url(self._BASE_URL + resolve_title)
513
514         version = 2
515         info = self._download_json(
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
522
523         return self._extract_info_dict(info, full_title, token, version)
524
525
526 class SoundcloudPlaylistBaseIE(SoundcloudIE):
527     def _extract_set(self, playlist, token=None):
528         playlist_id = compat_str(playlist['id'])
529         tracks = playlist.get('tracks') or []
530         if not all([t.get('permalink_url') for t in tracks]) and token:
531             tracks = self._download_json(
532                 self._API_V2_BASE + 'tracks', playlist_id,
533                 'Downloading tracks', query={
534                     'ids': ','.join([compat_str(t['id']) for t in tracks]),
535                     'playlistId': playlist_id,
536                     'playlistSecretToken': token,
537                 })
538         entries = []
539         for track in tracks:
540             track_id = str_or_none(track.get('id'))
541             url = track.get('permalink_url')
542             if not url:
543                 if not track_id:
544                     continue
545                 url = self._API_V2_BASE + 'tracks/' + track_id
546                 if token:
547                     url += '?secret_token=' + token
548             entries.append(self.url_result(
549                 url, SoundcloudIE.ie_key(), track_id))
550         return self.playlist_result(
551             entries, playlist_id,
552             playlist.get('title'),
553             playlist.get('description'))
554
555
556 class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
557     _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
558     IE_NAME = 'soundcloud:set'
559     _TESTS = [{
560         'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
561         'info_dict': {
562             'id': '2284613',
563             'title': 'The Royal Concept EP',
564             'description': 'md5:71d07087c7a449e8941a70a29e34671e',
565         },
566         'playlist_mincount': 5,
567     }, {
568         'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
569         'only_matching': True,
570     }]
571
572     def _real_extract(self, url):
573         mobj = re.match(self._VALID_URL, url)
574
575         full_title = '%s/sets/%s' % mobj.group('uploader', 'slug_title')
576         token = mobj.group('token')
577         if token:
578             full_title += '/' + token
579
580         info = self._download_json(self._resolv_url(
581             self._BASE_URL + full_title), full_title)
582
583         if 'errors' in info:
584             msgs = (compat_str(err['error_message']) for err in info['errors'])
585             raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
586
587         return self._extract_set(info, token)
588
589
590 class SoundcloudPagedPlaylistBaseIE(SoundcloudIE):
591     def _extract_playlist(self, base_url, playlist_id, playlist_title):
592         COMMON_QUERY = {
593             'limit': 2000000000,
594             'linked_partitioning': '1',
595         }
596
597         query = COMMON_QUERY.copy()
598         query['offset'] = 0
599
600         next_href = base_url
601
602         entries = []
603         for i in itertools.count():
604             response = self._download_json(
605                 next_href, playlist_id,
606                 'Downloading track page %s' % (i + 1), query=query)
607
608             collection = response['collection']
609
610             if not isinstance(collection, list):
611                 collection = []
612
613             # Empty collection may be returned, in this case we proceed
614             # straight to next_href
615
616             def resolve_entry(candidates):
617                 for cand in candidates:
618                     if not isinstance(cand, dict):
619                         continue
620                     permalink_url = url_or_none(cand.get('permalink_url'))
621                     if not permalink_url:
622                         continue
623                     return self.url_result(
624                         permalink_url,
625                         SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
626                         str_or_none(cand.get('id')), cand.get('title'))
627
628             for e in collection:
629                 entry = resolve_entry((e, e.get('track'), e.get('playlist')))
630                 if entry:
631                     entries.append(entry)
632
633             next_href = response.get('next_href')
634             if not next_href:
635                 break
636
637             next_href = response['next_href']
638             parsed_next_href = compat_urlparse.urlparse(next_href)
639             query = compat_urlparse.parse_qs(parsed_next_href.query)
640             query.update(COMMON_QUERY)
641
642         return {
643             '_type': 'playlist',
644             'id': playlist_id,
645             'title': playlist_title,
646             'entries': entries,
647         }
648
649
650 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
651     _VALID_URL = r'''(?x)
652                         https?://
653                             (?:(?:www|m)\.)?soundcloud\.com/
654                             (?P<user>[^/]+)
655                             (?:/
656                                 (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
657                             )?
658                             /?(?:[?#].*)?$
659                     '''
660     IE_NAME = 'soundcloud:user'
661     _TESTS = [{
662         'url': 'https://soundcloud.com/soft-cell-official',
663         'info_dict': {
664             'id': '207965082',
665             'title': 'Soft Cell (All)',
666         },
667         'playlist_mincount': 28,
668     }, {
669         'url': 'https://soundcloud.com/soft-cell-official/tracks',
670         'info_dict': {
671             'id': '207965082',
672             'title': 'Soft Cell (Tracks)',
673         },
674         'playlist_mincount': 27,
675     }, {
676         'url': 'https://soundcloud.com/soft-cell-official/albums',
677         'info_dict': {
678             'id': '207965082',
679             'title': 'Soft Cell (Albums)',
680         },
681         'playlist_mincount': 1,
682     }, {
683         'url': 'https://soundcloud.com/jcv246/sets',
684         'info_dict': {
685             'id': '12982173',
686             'title': 'Jordi / cv (Sets)',
687         },
688         'playlist_mincount': 2,
689     }, {
690         'url': 'https://soundcloud.com/jcv246/reposts',
691         'info_dict': {
692             'id': '12982173',
693             'title': 'Jordi / cv (Reposts)',
694         },
695         'playlist_mincount': 6,
696     }, {
697         'url': 'https://soundcloud.com/clalberg/likes',
698         'info_dict': {
699             'id': '11817582',
700             'title': 'clalberg (Likes)',
701         },
702         'playlist_mincount': 5,
703     }, {
704         'url': 'https://soundcloud.com/grynpyret/spotlight',
705         'info_dict': {
706             'id': '7098329',
707             'title': 'Grynpyret (Spotlight)',
708         },
709         'playlist_mincount': 1,
710     }]
711
712     _BASE_URL_MAP = {
713         'all': 'stream/users/%s',
714         'tracks': 'users/%s/tracks',
715         'albums': 'users/%s/albums',
716         'sets': 'users/%s/playlists',
717         'reposts': 'stream/users/%s/reposts',
718         'likes': 'users/%s/likes',
719         'spotlight': 'users/%s/spotlight',
720     }
721
722     def _real_extract(self, url):
723         mobj = re.match(self._VALID_URL, url)
724         uploader = mobj.group('user')
725
726         user = self._download_json(
727             self._resolv_url(self._BASE_URL + uploader),
728             uploader, 'Downloading user info')
729
730         resource = mobj.group('rsrc') or 'all'
731
732         return self._extract_playlist(
733             self._API_V2_BASE + self._BASE_URL_MAP[resource] % user['id'],
734             str_or_none(user.get('id')),
735             '%s (%s)' % (user['username'], resource.capitalize()))
736
737
738 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
739     _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
740     IE_NAME = 'soundcloud:trackstation'
741     _TESTS = [{
742         'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
743         'info_dict': {
744             'id': '286017854',
745             'title': 'Track station: your text',
746         },
747         'playlist_mincount': 47,
748     }]
749
750     def _real_extract(self, url):
751         track_name = self._match_id(url)
752
753         track = self._download_json(self._resolv_url(url), track_name)
754         track_id = self._search_regex(
755             r'soundcloud:track-stations:(\d+)', track['id'], 'track id')
756
757         return self._extract_playlist(
758             self._API_V2_BASE + 'stations/%s/tracks' % track['id'],
759             track_id, 'Track station: %s' % track['title'])
760
761
762 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
763     _VALID_URL = r'https?://api(?:-v2)?\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
764     IE_NAME = 'soundcloud:playlist'
765     _TESTS = [{
766         'url': 'https://api.soundcloud.com/playlists/4110309',
767         'info_dict': {
768             'id': '4110309',
769             'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
770             'description': 're:.*?TILT Brass - Bowery Poetry Club',
771         },
772         'playlist_count': 6,
773     }]
774
775     def _real_extract(self, url):
776         mobj = re.match(self._VALID_URL, url)
777         playlist_id = mobj.group('id')
778
779         query = {}
780         token = mobj.group('token')
781         if token:
782             query['secret_token'] = token
783
784         data = self._download_json(
785             self._API_V2_BASE + 'playlists/' + playlist_id,
786             playlist_id, 'Downloading playlist', query=query)
787
788         return self._extract_set(data, token)
789
790
791 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
792     IE_NAME = 'soundcloud:search'
793     IE_DESC = 'Soundcloud search'
794     _MAX_RESULTS = float('inf')
795     _TESTS = [{
796         'url': 'scsearch15:post-avant jazzcore',
797         'info_dict': {
798             'title': 'post-avant jazzcore',
799         },
800         'playlist_count': 15,
801     }]
802
803     _SEARCH_KEY = 'scsearch'
804     _MAX_RESULTS_PER_PAGE = 200
805     _DEFAULT_RESULTS_PER_PAGE = 50
806
807     def _get_collection(self, endpoint, collection_id, **query):
808         limit = min(
809             query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
810             self._MAX_RESULTS_PER_PAGE)
811         query.update({
812             'limit': limit,
813             'linked_partitioning': 1,
814             'offset': 0,
815         })
816         next_url = update_url_query(self._API_V2_BASE + endpoint, query)
817
818         collected_results = 0
819
820         for i in itertools.count(1):
821             response = self._download_json(
822                 next_url, collection_id, 'Downloading page {0}'.format(i),
823                 'Unable to download API page')
824
825             collection = response.get('collection', [])
826             if not collection:
827                 break
828
829             collection = list(filter(bool, collection))
830             collected_results += len(collection)
831
832             for item in collection:
833                 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
834
835             if not collection or collected_results >= limit:
836                 break
837
838             next_url = response.get('next_href')
839             if not next_url:
840                 break
841
842     def _get_n_results(self, query, n):
843         tracks = self._get_collection('search/tracks', query, limit=n, q=query)
844         return self.playlist_result(tracks, playlist_title=query)