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