]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/extractor/soundcloud.py
[nhk] add support for audio URLs
[youtube-dl.git] / 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_str,
13     compat_urlparse,
14     compat_urllib_parse_urlencode,
15 )
16 from ..utils import (
17     ExtractorError,
18     int_or_none,
19     try_get,
20     unified_timestamp,
21     update_url_query,
22     url_or_none,
23 )
24
25
26 class SoundcloudIE(InfoExtractor):
27     """Information extractor for soundcloud.com
28        To access the media, the uid of the song and a stream token
29        must be extracted from the page source and the script must make
30        a request to media.soundcloud.com/crossdomain.xml. Then
31        the media can be grabbed by requesting from an url composed
32        of the stream token and uid
33      """
34
35     _VALID_URL = r'''(?x)^(?:https?://)?
36                     (?:(?:(?:www\.|m\.)?soundcloud\.com/
37                             (?!stations/track)
38                             (?P<uploader>[\w\d-]+)/
39                             (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
40                             (?P<title>[\w\d-]+)/?
41                             (?P<token>[^?]+?)?(?:[?].*)?$)
42                        |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
43                           (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
44                        |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
45                     )
46                     '''
47     IE_NAME = 'soundcloud'
48     _TESTS = [
49         {
50             'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
51             'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
52             'info_dict': {
53                 'id': '62986583',
54                 'ext': 'mp3',
55                 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
56                 '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',
57                 'uploader': 'E.T. ExTerrestrial Music',
58                 'timestamp': 1349920598,
59                 'upload_date': '20121011',
60                 'duration': 143,
61                 'license': 'all-rights-reserved',
62                 'view_count': int,
63                 'like_count': int,
64                 'comment_count': int,
65                 'repost_count': int,
66             }
67         },
68         # not streamable song
69         {
70             'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
71             'info_dict': {
72                 'id': '47127627',
73                 'ext': 'mp3',
74                 'title': 'Goldrushed',
75                 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
76                 'uploader': 'The Royal Concept',
77                 'timestamp': 1337635207,
78                 'upload_date': '20120521',
79                 'duration': 30,
80                 'license': 'all-rights-reserved',
81                 'view_count': int,
82                 'like_count': int,
83                 'comment_count': int,
84                 'repost_count': int,
85             },
86             'params': {
87                 # rtmp
88                 'skip_download': True,
89             },
90         },
91         # private link
92         {
93             'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
94             'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
95             'info_dict': {
96                 'id': '123998367',
97                 'ext': 'mp3',
98                 'title': 'Youtube - Dl Test Video \'\' Ä↭',
99                 'description': 'test chars:  \"\'/\\ä↭',
100                 'uploader': 'jaimeMF',
101                 'timestamp': 1386604920,
102                 'upload_date': '20131209',
103                 'duration': 9,
104                 'license': 'all-rights-reserved',
105                 'view_count': int,
106                 'like_count': int,
107                 'comment_count': int,
108                 'repost_count': int,
109             },
110         },
111         # private link (alt format)
112         {
113             'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
114             'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
115             'info_dict': {
116                 'id': '123998367',
117                 'ext': 'mp3',
118                 'title': 'Youtube - Dl Test Video \'\' Ä↭',
119                 'description': 'test chars:  \"\'/\\ä↭',
120                 'uploader': 'jaimeMF',
121                 'timestamp': 1386604920,
122                 'upload_date': '20131209',
123                 'duration': 9,
124                 'license': 'all-rights-reserved',
125                 'view_count': int,
126                 'like_count': int,
127                 'comment_count': int,
128                 'repost_count': int,
129             },
130         },
131         # downloadable song
132         {
133             'url': 'https://soundcloud.com/oddsamples/bus-brakes',
134             'md5': '7624f2351f8a3b2e7cd51522496e7631',
135             'info_dict': {
136                 'id': '128590877',
137                 'ext': 'mp3',
138                 'title': 'Bus Brakes',
139                 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
140                 'uploader': 'oddsamples',
141                 'timestamp': 1389232924,
142                 'upload_date': '20140109',
143                 'duration': 17,
144                 'license': 'cc-by-sa',
145                 'view_count': int,
146                 'like_count': int,
147                 'comment_count': int,
148                 'repost_count': int,
149             },
150         },
151         # private link, downloadable format
152         {
153             'url': 'https://soundcloud.com/oriuplift/uponly-238-no-talking-wav/s-AyZUd',
154             'md5': '64a60b16e617d41d0bef032b7f55441e',
155             'info_dict': {
156                 'id': '340344461',
157                 'ext': 'wav',
158                 'title': 'Uplifting Only 238 [No Talking] (incl. Alex Feed Guestmix) (Aug 31, 2017) [wav]',
159                 'description': 'md5:fa20ee0fca76a3d6df8c7e57f3715366',
160                 'uploader': 'Ori Uplift Music',
161                 'timestamp': 1504206263,
162                 'upload_date': '20170831',
163                 'duration': 7449,
164                 'license': 'all-rights-reserved',
165                 'view_count': int,
166                 'like_count': int,
167                 'comment_count': int,
168                 'repost_count': int,
169             },
170         },
171         # no album art, use avatar pic for thumbnail
172         {
173             'url': 'https://soundcloud.com/garyvee/sideways-prod-mad-real',
174             'md5': '59c7872bc44e5d99b7211891664760c2',
175             'info_dict': {
176                 'id': '309699954',
177                 'ext': 'mp3',
178                 'title': 'Sideways (Prod. Mad Real)',
179                 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
180                 'uploader': 'garyvee',
181                 'timestamp': 1488152409,
182                 'upload_date': '20170226',
183                 'duration': 207,
184                 'thumbnail': r're:https?://.*\.jpg',
185                 'license': 'all-rights-reserved',
186                 'view_count': int,
187                 'like_count': int,
188                 'comment_count': int,
189                 'repost_count': int,
190             },
191             'params': {
192                 'skip_download': True,
193             },
194         },
195     ]
196
197     _CLIENT_ID = 'NmW1FlPaiL94ueEu7oziOWjYEzZzQDcK'
198
199     @staticmethod
200     def _extract_urls(webpage):
201         return [m.group('url') for m in re.finditer(
202             r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
203             webpage)]
204
205     def report_resolve(self, video_id):
206         """Report information extraction."""
207         self.to_screen('%s: Resolving id' % video_id)
208
209     @classmethod
210     def _resolv_url(cls, url):
211         return 'https://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
212
213     def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
214         track_id = compat_str(info['id'])
215         title = info['title']
216         name = full_title or track_id
217         if quiet:
218             self.report_extraction(name)
219         thumbnail = info.get('artwork_url') or info.get('user', {}).get('avatar_url')
220         if isinstance(thumbnail, compat_str):
221             thumbnail = thumbnail.replace('-large', '-t500x500')
222         username = try_get(info, lambda x: x['user']['username'], compat_str)
223
224         def extract_count(key):
225             return int_or_none(info.get('%s_count' % key))
226
227         result = {
228             'id': track_id,
229             'uploader': username,
230             'timestamp': unified_timestamp(info.get('created_at')),
231             'title': title,
232             'description': info.get('description'),
233             'thumbnail': thumbnail,
234             'duration': int_or_none(info.get('duration'), 1000),
235             'webpage_url': info.get('permalink_url'),
236             'license': info.get('license'),
237             'view_count': extract_count('playback'),
238             'like_count': extract_count('favoritings'),
239             'comment_count': extract_count('comment'),
240             'repost_count': extract_count('reposts'),
241             'genre': info.get('genre'),
242         }
243         formats = []
244         query = {'client_id': self._CLIENT_ID}
245         if secret_token is not None:
246             query['secret_token'] = secret_token
247         if info.get('downloadable', False):
248             # We can build a direct link to the song
249             format_url = update_url_query(
250                 'https://api.soundcloud.com/tracks/%s/download' % track_id, query)
251             formats.append({
252                 'format_id': 'download',
253                 'ext': info.get('original_format', 'mp3'),
254                 'url': format_url,
255                 'vcodec': 'none',
256                 'preference': 10,
257             })
258
259         # We have to retrieve the url
260         format_dict = self._download_json(
261             'https://api.soundcloud.com/i1/tracks/%s/streams' % track_id,
262             track_id, 'Downloading track url', query=query)
263
264         for key, stream_url in format_dict.items():
265             ext, abr = 'mp3', None
266             mobj = re.search(r'_([^_]+)_(\d+)_url', key)
267             if mobj:
268                 ext, abr = mobj.groups()
269                 abr = int(abr)
270             if key.startswith('http'):
271                 stream_formats = [{
272                     'format_id': key,
273                     'ext': ext,
274                     'url': stream_url,
275                 }]
276             elif key.startswith('rtmp'):
277                 # The url doesn't have an rtmp app, we have to extract the playpath
278                 url, path = stream_url.split('mp3:', 1)
279                 stream_formats = [{
280                     'format_id': key,
281                     'url': url,
282                     'play_path': 'mp3:' + path,
283                     'ext': 'flv',
284                 }]
285             elif key.startswith('hls'):
286                 stream_formats = self._extract_m3u8_formats(
287                     stream_url, track_id, ext, entry_protocol='m3u8_native',
288                     m3u8_id=key, fatal=False)
289             else:
290                 continue
291
292             if abr:
293                 for f in stream_formats:
294                     f['abr'] = abr
295
296             formats.extend(stream_formats)
297
298         if not formats:
299             # We fallback to the stream_url in the original info, this
300             # cannot be always used, sometimes it can give an HTTP 404 error
301             formats.append({
302                 'format_id': 'fallback',
303                 'url': update_url_query(info['stream_url'], query),
304                 'ext': 'mp3',
305             })
306
307         for f in formats:
308             f['vcodec'] = 'none'
309
310         self._check_formats(formats, track_id)
311         self._sort_formats(formats)
312         result['formats'] = formats
313
314         return result
315
316     def _real_extract(self, url):
317         mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
318         if mobj is None:
319             raise ExtractorError('Invalid URL: %s' % url)
320
321         track_id = mobj.group('track_id')
322
323         if track_id is not None:
324             info_json_url = 'https://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
325             full_title = track_id
326             token = mobj.group('secret_token')
327             if token:
328                 info_json_url += '&secret_token=' + token
329         elif mobj.group('player'):
330             query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
331             real_url = query['url'][0]
332             # If the token is in the query of the original url we have to
333             # manually add it
334             if 'secret_token' in query:
335                 real_url += '?secret_token=' + query['secret_token'][0]
336             return self.url_result(real_url)
337         else:
338             # extract uploader (which is in the url)
339             uploader = mobj.group('uploader')
340             # extract simple title (uploader + slug of song title)
341             slug_title = mobj.group('title')
342             token = mobj.group('token')
343             full_title = resolve_title = '%s/%s' % (uploader, slug_title)
344             if token:
345                 resolve_title += '/%s' % token
346
347             self.report_resolve(full_title)
348
349             url = 'https://soundcloud.com/%s' % resolve_title
350             info_json_url = self._resolv_url(url)
351         info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
352
353         return self._extract_info_dict(info, full_title, secret_token=token)
354
355
356 class SoundcloudPlaylistBaseIE(SoundcloudIE):
357     @staticmethod
358     def _extract_id(e):
359         return compat_str(e['id']) if e.get('id') else None
360
361     def _extract_track_entries(self, tracks):
362         return [
363             self.url_result(
364                 track['permalink_url'], SoundcloudIE.ie_key(),
365                 video_id=self._extract_id(track))
366             for track in tracks if track.get('permalink_url')]
367
368
369 class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
370     _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
371     IE_NAME = 'soundcloud:set'
372     _TESTS = [{
373         'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
374         'info_dict': {
375             'id': '2284613',
376             'title': 'The Royal Concept EP',
377         },
378         'playlist_mincount': 5,
379     }, {
380         'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
381         'only_matching': True,
382     }]
383
384     def _real_extract(self, url):
385         mobj = re.match(self._VALID_URL, url)
386
387         # extract uploader (which is in the url)
388         uploader = mobj.group('uploader')
389         # extract simple title (uploader + slug of song title)
390         slug_title = mobj.group('slug_title')
391         full_title = '%s/sets/%s' % (uploader, slug_title)
392         url = 'https://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
393
394         token = mobj.group('token')
395         if token:
396             full_title += '/' + token
397             url += '/' + token
398
399         self.report_resolve(full_title)
400
401         resolv_url = self._resolv_url(url)
402         info = self._download_json(resolv_url, full_title)
403
404         if 'errors' in info:
405             msgs = (compat_str(err['error_message']) for err in info['errors'])
406             raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
407
408         entries = self._extract_track_entries(info['tracks'])
409
410         return {
411             '_type': 'playlist',
412             'entries': entries,
413             'id': '%s' % info['id'],
414             'title': info['title'],
415         }
416
417
418 class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
419     _API_V2_BASE = 'https://api-v2.soundcloud.com'
420
421     def _extract_playlist(self, base_url, playlist_id, playlist_title):
422         COMMON_QUERY = {
423             'limit': 50,
424             'client_id': self._CLIENT_ID,
425             'linked_partitioning': '1',
426         }
427
428         query = COMMON_QUERY.copy()
429         query['offset'] = 0
430
431         next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
432
433         entries = []
434         for i in itertools.count():
435             response = self._download_json(
436                 next_href, playlist_id, 'Downloading track page %s' % (i + 1))
437
438             collection = response['collection']
439
440             if not isinstance(collection, list):
441                 collection = []
442
443             # Empty collection may be returned, in this case we proceed
444             # straight to next_href
445
446             def resolve_entry(candidates):
447                 for cand in candidates:
448                     if not isinstance(cand, dict):
449                         continue
450                     permalink_url = url_or_none(cand.get('permalink_url'))
451                     if not permalink_url:
452                         continue
453                     return self.url_result(
454                         permalink_url,
455                         ie=SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
456                         video_id=self._extract_id(cand),
457                         video_title=cand.get('title'))
458
459             for e in collection:
460                 entry = resolve_entry((e, e.get('track'), e.get('playlist')))
461                 if entry:
462                     entries.append(entry)
463
464             next_href = response.get('next_href')
465             if not next_href:
466                 break
467
468             parsed_next_href = compat_urlparse.urlparse(response['next_href'])
469             qs = compat_urlparse.parse_qs(parsed_next_href.query)
470             qs.update(COMMON_QUERY)
471             next_href = compat_urlparse.urlunparse(
472                 parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
473
474         return {
475             '_type': 'playlist',
476             'id': playlist_id,
477             'title': playlist_title,
478             'entries': entries,
479         }
480
481
482 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
483     _VALID_URL = r'''(?x)
484                         https?://
485                             (?:(?:www|m)\.)?soundcloud\.com/
486                             (?P<user>[^/]+)
487                             (?:/
488                                 (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
489                             )?
490                             /?(?:[?#].*)?$
491                     '''
492     IE_NAME = 'soundcloud:user'
493     _TESTS = [{
494         'url': 'https://soundcloud.com/soft-cell-official',
495         'info_dict': {
496             'id': '207965082',
497             'title': 'Soft Cell (All)',
498         },
499         'playlist_mincount': 28,
500     }, {
501         'url': 'https://soundcloud.com/soft-cell-official/tracks',
502         'info_dict': {
503             'id': '207965082',
504             'title': 'Soft Cell (Tracks)',
505         },
506         'playlist_mincount': 27,
507     }, {
508         'url': 'https://soundcloud.com/soft-cell-official/albums',
509         'info_dict': {
510             'id': '207965082',
511             'title': 'Soft Cell (Albums)',
512         },
513         'playlist_mincount': 1,
514     }, {
515         'url': 'https://soundcloud.com/jcv246/sets',
516         'info_dict': {
517             'id': '12982173',
518             'title': 'Jordi / cv (Playlists)',
519         },
520         'playlist_mincount': 2,
521     }, {
522         'url': 'https://soundcloud.com/jcv246/reposts',
523         'info_dict': {
524             'id': '12982173',
525             'title': 'Jordi / cv (Reposts)',
526         },
527         'playlist_mincount': 6,
528     }, {
529         'url': 'https://soundcloud.com/clalberg/likes',
530         'info_dict': {
531             'id': '11817582',
532             'title': 'clalberg (Likes)',
533         },
534         'playlist_mincount': 5,
535     }, {
536         'url': 'https://soundcloud.com/grynpyret/spotlight',
537         'info_dict': {
538             'id': '7098329',
539             'title': 'Grynpyret (Spotlight)',
540         },
541         'playlist_mincount': 1,
542     }]
543
544     _BASE_URL_MAP = {
545         'all': '%s/stream/users/%%s' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
546         'tracks': '%s/users/%%s/tracks' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
547         'albums': '%s/users/%%s/albums' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
548         'sets': '%s/users/%%s/playlists' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
549         'reposts': '%s/stream/users/%%s/reposts' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
550         'likes': '%s/users/%%s/likes' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
551         'spotlight': '%s/users/%%s/spotlight' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
552     }
553
554     _TITLE_MAP = {
555         'all': 'All',
556         'tracks': 'Tracks',
557         'albums': 'Albums',
558         'sets': 'Playlists',
559         'reposts': 'Reposts',
560         'likes': 'Likes',
561         'spotlight': 'Spotlight',
562     }
563
564     def _real_extract(self, url):
565         mobj = re.match(self._VALID_URL, url)
566         uploader = mobj.group('user')
567
568         url = 'https://soundcloud.com/%s/' % uploader
569         resolv_url = self._resolv_url(url)
570         user = self._download_json(
571             resolv_url, uploader, 'Downloading user info')
572
573         resource = mobj.group('rsrc') or 'all'
574
575         return self._extract_playlist(
576             self._BASE_URL_MAP[resource] % user['id'], compat_str(user['id']),
577             '%s (%s)' % (user['username'], self._TITLE_MAP[resource]))
578
579
580 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
581     _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
582     IE_NAME = 'soundcloud:trackstation'
583     _TESTS = [{
584         'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
585         'info_dict': {
586             'id': '286017854',
587             'title': 'Track station: your-text',
588         },
589         'playlist_mincount': 47,
590     }]
591
592     def _real_extract(self, url):
593         track_name = self._match_id(url)
594
595         webpage = self._download_webpage(url, track_name)
596
597         track_id = self._search_regex(
598             r'soundcloud:track-stations:(\d+)', webpage, 'track id')
599
600         return self._extract_playlist(
601             '%s/stations/soundcloud:track-stations:%s/tracks'
602             % (self._API_V2_BASE, track_id),
603             track_id, 'Track station: %s' % track_name)
604
605
606 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
607     _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
608     IE_NAME = 'soundcloud:playlist'
609     _TESTS = [{
610         'url': 'https://api.soundcloud.com/playlists/4110309',
611         'info_dict': {
612             'id': '4110309',
613             'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
614             'description': 're:.*?TILT Brass - Bowery Poetry Club',
615         },
616         'playlist_count': 6,
617     }]
618
619     def _real_extract(self, url):
620         mobj = re.match(self._VALID_URL, url)
621         playlist_id = mobj.group('id')
622         base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
623
624         data_dict = {
625             'client_id': self._CLIENT_ID,
626         }
627         token = mobj.group('token')
628
629         if token:
630             data_dict['secret_token'] = token
631
632         data = compat_urllib_parse_urlencode(data_dict)
633         data = self._download_json(
634             base_url + data, playlist_id, 'Downloading playlist')
635
636         entries = self._extract_track_entries(data['tracks'])
637
638         return {
639             '_type': 'playlist',
640             'id': playlist_id,
641             'title': data.get('title'),
642             'description': data.get('description'),
643             'entries': entries,
644         }
645
646
647 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
648     IE_NAME = 'soundcloud:search'
649     IE_DESC = 'Soundcloud search'
650     _MAX_RESULTS = float('inf')
651     _TESTS = [{
652         'url': 'scsearch15:post-avant jazzcore',
653         'info_dict': {
654             'title': 'post-avant jazzcore',
655         },
656         'playlist_count': 15,
657     }]
658
659     _SEARCH_KEY = 'scsearch'
660     _MAX_RESULTS_PER_PAGE = 200
661     _DEFAULT_RESULTS_PER_PAGE = 50
662     _API_V2_BASE = 'https://api-v2.soundcloud.com'
663
664     def _get_collection(self, endpoint, collection_id, **query):
665         limit = min(
666             query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
667             self._MAX_RESULTS_PER_PAGE)
668         query['limit'] = limit
669         query['client_id'] = self._CLIENT_ID
670         query['linked_partitioning'] = '1'
671         query['offset'] = 0
672         data = compat_urllib_parse_urlencode(query)
673         next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
674
675         collected_results = 0
676
677         for i in itertools.count(1):
678             response = self._download_json(
679                 next_url, collection_id, 'Downloading page {0}'.format(i),
680                 'Unable to download API page')
681
682             collection = response.get('collection', [])
683             if not collection:
684                 break
685
686             collection = list(filter(bool, collection))
687             collected_results += len(collection)
688
689             for item in collection:
690                 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
691
692             if not collection or collected_results >= limit:
693                 break
694
695             next_url = response.get('next_href')
696             if not next_url:
697                 break
698
699     def _get_n_results(self, query, n):
700         tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
701         return self.playlist_result(tracks, playlist_title=query)