[soundcloud] Update client id
[youtube-dl] / youtube_dl / extractor / soundcloud.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import itertools
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 )
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         if info.get('downloadable', False):
164             # We can build a direct link to the song
165             format_url = (
166                 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
167                     track_id, self._CLIENT_ID))
168             formats.append({
169                 'format_id': 'download',
170                 'ext': info.get('original_format', 'mp3'),
171                 'url': format_url,
172                 'vcodec': 'none',
173                 'preference': 10,
174             })
175
176         # We have to retrieve the url
177         format_dict = self._download_json(
178             'https://api.soundcloud.com/i1/tracks/%s/streams' % track_id,
179             track_id, 'Downloading track url', query={
180                 'client_id': self._CLIENT_ID,
181                 'secret_token': secret_token,
182             })
183
184         for key, stream_url in format_dict.items():
185             abr = int_or_none(self._search_regex(
186                 r'_(\d+)_url', key, 'audio bitrate', default=None))
187             if key.startswith('http'):
188                 stream_formats = [{
189                     'format_id': key,
190                     'ext': ext,
191                     'url': stream_url,
192                 }]
193             elif key.startswith('rtmp'):
194                 # The url doesn't have an rtmp app, we have to extract the playpath
195                 url, path = stream_url.split('mp3:', 1)
196                 stream_formats = [{
197                     'format_id': key,
198                     'url': url,
199                     'play_path': 'mp3:' + path,
200                     'ext': 'flv',
201                 }]
202             elif key.startswith('hls'):
203                 stream_formats = self._extract_m3u8_formats(
204                     stream_url, track_id, 'mp3', entry_protocol='m3u8_native',
205                     m3u8_id=key, fatal=False)
206             else:
207                 continue
208
209             for f in stream_formats:
210                 f['abr'] = abr
211
212             formats.extend(stream_formats)
213
214         if not formats:
215             # We fallback to the stream_url in the original info, this
216             # cannot be always used, sometimes it can give an HTTP 404 error
217             formats.append({
218                 'format_id': 'fallback',
219                 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
220                 'ext': ext,
221             })
222
223         for f in formats:
224             f['vcodec'] = 'none'
225
226         self._check_formats(formats, track_id)
227         self._sort_formats(formats)
228         result['formats'] = formats
229
230         return result
231
232     def _real_extract(self, url):
233         mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
234         if mobj is None:
235             raise ExtractorError('Invalid URL: %s' % url)
236
237         track_id = mobj.group('track_id')
238
239         if track_id is not None:
240             info_json_url = 'https://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
241             full_title = track_id
242             token = mobj.group('secret_token')
243             if token:
244                 info_json_url += '&secret_token=' + token
245         elif mobj.group('player'):
246             query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
247             real_url = query['url'][0]
248             # If the token is in the query of the original url we have to
249             # manually add it
250             if 'secret_token' in query:
251                 real_url += '?secret_token=' + query['secret_token'][0]
252             return self.url_result(real_url)
253         else:
254             # extract uploader (which is in the url)
255             uploader = mobj.group('uploader')
256             # extract simple title (uploader + slug of song title)
257             slug_title = mobj.group('title')
258             token = mobj.group('token')
259             full_title = resolve_title = '%s/%s' % (uploader, slug_title)
260             if token:
261                 resolve_title += '/%s' % token
262
263             self.report_resolve(full_title)
264
265             url = 'https://soundcloud.com/%s' % resolve_title
266             info_json_url = self._resolv_url(url)
267         info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
268
269         return self._extract_info_dict(info, full_title, secret_token=token)
270
271
272 class SoundcloudPlaylistBaseIE(SoundcloudIE):
273     @staticmethod
274     def _extract_id(e):
275         return compat_str(e['id']) if e.get('id') else None
276
277     def _extract_track_entries(self, tracks):
278         return [
279             self.url_result(
280                 track['permalink_url'], SoundcloudIE.ie_key(),
281                 video_id=self._extract_id(track))
282             for track in tracks if track.get('permalink_url')]
283
284
285 class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
286     _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
287     IE_NAME = 'soundcloud:set'
288     _TESTS = [{
289         'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
290         'info_dict': {
291             'id': '2284613',
292             'title': 'The Royal Concept EP',
293         },
294         'playlist_mincount': 5,
295     }, {
296         'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
297         'only_matching': True,
298     }]
299
300     def _real_extract(self, url):
301         mobj = re.match(self._VALID_URL, url)
302
303         # extract uploader (which is in the url)
304         uploader = mobj.group('uploader')
305         # extract simple title (uploader + slug of song title)
306         slug_title = mobj.group('slug_title')
307         full_title = '%s/sets/%s' % (uploader, slug_title)
308         url = 'https://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
309
310         token = mobj.group('token')
311         if token:
312             full_title += '/' + token
313             url += '/' + token
314
315         self.report_resolve(full_title)
316
317         resolv_url = self._resolv_url(url)
318         info = self._download_json(resolv_url, full_title)
319
320         if 'errors' in info:
321             msgs = (compat_str(err['error_message']) for err in info['errors'])
322             raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
323
324         entries = self._extract_track_entries(info['tracks'])
325
326         return {
327             '_type': 'playlist',
328             'entries': entries,
329             'id': '%s' % info['id'],
330             'title': info['title'],
331         }
332
333
334 class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
335     _API_BASE = 'https://api.soundcloud.com'
336     _API_V2_BASE = 'https://api-v2.soundcloud.com'
337
338     def _extract_playlist(self, base_url, playlist_id, playlist_title):
339         COMMON_QUERY = {
340             'limit': 50,
341             'client_id': self._CLIENT_ID,
342             'linked_partitioning': '1',
343         }
344
345         query = COMMON_QUERY.copy()
346         query['offset'] = 0
347
348         next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
349
350         entries = []
351         for i in itertools.count():
352             response = self._download_json(
353                 next_href, playlist_id, 'Downloading track page %s' % (i + 1))
354
355             collection = response['collection']
356             if not collection:
357                 break
358
359             def resolve_permalink_url(candidates):
360                 for cand in candidates:
361                     if isinstance(cand, dict):
362                         permalink_url = cand.get('permalink_url')
363                         entry_id = self._extract_id(cand)
364                         if permalink_url and permalink_url.startswith('http'):
365                             return permalink_url, entry_id
366
367             for e in collection:
368                 permalink_url, entry_id = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
369                 if permalink_url:
370                     entries.append(self.url_result(permalink_url, video_id=entry_id))
371
372             next_href = response.get('next_href')
373             if not next_href:
374                 break
375
376             parsed_next_href = compat_urlparse.urlparse(response['next_href'])
377             qs = compat_urlparse.parse_qs(parsed_next_href.query)
378             qs.update(COMMON_QUERY)
379             next_href = compat_urlparse.urlunparse(
380                 parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
381
382         return {
383             '_type': 'playlist',
384             'id': playlist_id,
385             'title': playlist_title,
386             'entries': entries,
387         }
388
389
390 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
391     _VALID_URL = r'''(?x)
392                         https?://
393                             (?:(?:www|m)\.)?soundcloud\.com/
394                             (?P<user>[^/]+)
395                             (?:/
396                                 (?P<rsrc>tracks|sets|reposts|likes|spotlight)
397                             )?
398                             /?(?:[?#].*)?$
399                     '''
400     IE_NAME = 'soundcloud:user'
401     _TESTS = [{
402         'url': 'https://soundcloud.com/the-akashic-chronicler',
403         'info_dict': {
404             'id': '114582580',
405             'title': 'The Akashic Chronicler (All)',
406         },
407         'playlist_mincount': 74,
408     }, {
409         'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
410         'info_dict': {
411             'id': '114582580',
412             'title': 'The Akashic Chronicler (Tracks)',
413         },
414         'playlist_mincount': 37,
415     }, {
416         'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
417         'info_dict': {
418             'id': '114582580',
419             'title': 'The Akashic Chronicler (Playlists)',
420         },
421         'playlist_mincount': 2,
422     }, {
423         'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
424         'info_dict': {
425             'id': '114582580',
426             'title': 'The Akashic Chronicler (Reposts)',
427         },
428         'playlist_mincount': 7,
429     }, {
430         'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
431         'info_dict': {
432             'id': '114582580',
433             'title': 'The Akashic Chronicler (Likes)',
434         },
435         'playlist_mincount': 321,
436     }, {
437         'url': 'https://soundcloud.com/grynpyret/spotlight',
438         'info_dict': {
439             'id': '7098329',
440             'title': 'Grynpyret (Spotlight)',
441         },
442         'playlist_mincount': 1,
443     }]
444
445     _BASE_URL_MAP = {
446         'all': '%s/profile/soundcloud:users:%%s' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
447         'tracks': '%s/users/%%s/tracks' % SoundcloudPagedPlaylistBaseIE._API_BASE,
448         'sets': '%s/users/%%s/playlists' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
449         'reposts': '%s/profile/soundcloud:users:%%s/reposts' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
450         'likes': '%s/users/%%s/likes' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
451         'spotlight': '%s/users/%%s/spotlight' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
452     }
453
454     _TITLE_MAP = {
455         'all': 'All',
456         'tracks': 'Tracks',
457         'sets': 'Playlists',
458         'reposts': 'Reposts',
459         'likes': 'Likes',
460         'spotlight': 'Spotlight',
461     }
462
463     def _real_extract(self, url):
464         mobj = re.match(self._VALID_URL, url)
465         uploader = mobj.group('user')
466
467         url = 'https://soundcloud.com/%s/' % uploader
468         resolv_url = self._resolv_url(url)
469         user = self._download_json(
470             resolv_url, uploader, 'Downloading user info')
471
472         resource = mobj.group('rsrc') or 'all'
473
474         return self._extract_playlist(
475             self._BASE_URL_MAP[resource] % user['id'], compat_str(user['id']),
476             '%s (%s)' % (user['username'], self._TITLE_MAP[resource]))
477
478
479 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
480     _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
481     IE_NAME = 'soundcloud:trackstation'
482     _TESTS = [{
483         'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
484         'info_dict': {
485             'id': '286017854',
486             'title': 'Track station: your-text',
487         },
488         'playlist_mincount': 47,
489     }]
490
491     def _real_extract(self, url):
492         track_name = self._match_id(url)
493
494         webpage = self._download_webpage(url, track_name)
495
496         track_id = self._search_regex(
497             r'soundcloud:track-stations:(\d+)', webpage, 'track id')
498
499         return self._extract_playlist(
500             '%s/stations/soundcloud:track-stations:%s/tracks'
501             % (self._API_V2_BASE, track_id),
502             track_id, 'Track station: %s' % track_name)
503
504
505 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
506     _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
507     IE_NAME = 'soundcloud:playlist'
508     _TESTS = [{
509         'url': 'https://api.soundcloud.com/playlists/4110309',
510         'info_dict': {
511             'id': '4110309',
512             'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
513             'description': 're:.*?TILT Brass - Bowery Poetry Club',
514         },
515         'playlist_count': 6,
516     }]
517
518     def _real_extract(self, url):
519         mobj = re.match(self._VALID_URL, url)
520         playlist_id = mobj.group('id')
521         base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
522
523         data_dict = {
524             'client_id': self._CLIENT_ID,
525         }
526         token = mobj.group('token')
527
528         if token:
529             data_dict['secret_token'] = token
530
531         data = compat_urllib_parse_urlencode(data_dict)
532         data = self._download_json(
533             base_url + data, playlist_id, 'Downloading playlist')
534
535         entries = self._extract_track_entries(data['tracks'])
536
537         return {
538             '_type': 'playlist',
539             'id': playlist_id,
540             'title': data.get('title'),
541             'description': data.get('description'),
542             'entries': entries,
543         }
544
545
546 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
547     IE_NAME = 'soundcloud:search'
548     IE_DESC = 'Soundcloud search'
549     _MAX_RESULTS = float('inf')
550     _TESTS = [{
551         'url': 'scsearch15:post-avant jazzcore',
552         'info_dict': {
553             'title': 'post-avant jazzcore',
554         },
555         'playlist_count': 15,
556     }]
557
558     _SEARCH_KEY = 'scsearch'
559     _MAX_RESULTS_PER_PAGE = 200
560     _DEFAULT_RESULTS_PER_PAGE = 50
561     _API_V2_BASE = 'https://api-v2.soundcloud.com'
562
563     def _get_collection(self, endpoint, collection_id, **query):
564         limit = min(
565             query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
566             self._MAX_RESULTS_PER_PAGE)
567         query['limit'] = limit
568         query['client_id'] = self._CLIENT_ID
569         query['linked_partitioning'] = '1'
570         query['offset'] = 0
571         data = compat_urllib_parse_urlencode(query)
572         next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
573
574         collected_results = 0
575
576         for i in itertools.count(1):
577             response = self._download_json(
578                 next_url, collection_id, 'Downloading page {0}'.format(i),
579                 'Unable to download API page')
580
581             collection = response.get('collection', [])
582             if not collection:
583                 break
584
585             collection = list(filter(bool, collection))
586             collected_results += len(collection)
587
588             for item in collection:
589                 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
590
591             if not collection or collected_results >= limit:
592                 break
593
594             next_url = response.get('next_href')
595             if not next_url:
596                 break
597
598     def _get_n_results(self, query, n):
599         tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
600         return self.playlist_result(tracks, playlist_title=query)