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