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