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