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