[soundcloud] Extract license metadata
[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_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 = '02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea'
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['artwork_url']
147         track_license = info['license']
148         if thumbnail is not None:
149             thumbnail = thumbnail.replace('-large', '-t500x500')
150         ext = 'mp3'
151         result = {
152             'id': track_id,
153             'uploader': info['user']['username'],
154             'upload_date': unified_strdate(info['created_at']),
155             'title': info['title'],
156             'description': info['description'],
157             'thumbnail': thumbnail,
158             'duration': int_or_none(info.get('duration'), 1000),
159             'webpage_url': info.get('permalink_url'),
160             'license': track_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         streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
178                        'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
179         format_dict = self._download_json(
180             streams_url,
181             track_id, 'Downloading track url')
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         token = None
231
232         if track_id is not None:
233             info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
234             full_title = track_id
235             token = mobj.group('secret_token')
236             if token:
237                 info_json_url += '&secret_token=' + token
238         elif mobj.group('player'):
239             query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
240             real_url = query['url'][0]
241             # If the token is in the query of the original url we have to
242             # manually add it
243             if 'secret_token' in query:
244                 real_url += '?secret_token=' + query['secret_token'][0]
245             return self.url_result(real_url)
246         else:
247             # extract uploader (which is in the url)
248             uploader = mobj.group('uploader')
249             # extract simple title (uploader + slug of song title)
250             slug_title = mobj.group('title')
251             token = mobj.group('token')
252             full_title = resolve_title = '%s/%s' % (uploader, slug_title)
253             if token:
254                 resolve_title += '/%s' % token
255
256             self.report_resolve(full_title)
257
258             url = 'http://soundcloud.com/%s' % resolve_title
259             info_json_url = self._resolv_url(url)
260         info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
261
262         return self._extract_info_dict(info, full_title, secret_token=token)
263
264
265 class SoundcloudSetIE(SoundcloudIE):
266     _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
267     IE_NAME = 'soundcloud:set'
268     _TESTS = [{
269         'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
270         'info_dict': {
271             'id': '2284613',
272             'title': 'The Royal Concept EP',
273         },
274         'playlist_mincount': 6,
275     }, {
276         'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
277         'only_matching': True,
278     }]
279
280     def _real_extract(self, url):
281         mobj = re.match(self._VALID_URL, url)
282
283         # extract uploader (which is in the url)
284         uploader = mobj.group('uploader')
285         # extract simple title (uploader + slug of song title)
286         slug_title = mobj.group('slug_title')
287         full_title = '%s/sets/%s' % (uploader, slug_title)
288         url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
289
290         token = mobj.group('token')
291         if token:
292             full_title += '/' + token
293             url += '/' + token
294
295         self.report_resolve(full_title)
296
297         resolv_url = self._resolv_url(url)
298         info = self._download_json(resolv_url, full_title)
299
300         if 'errors' in info:
301             msgs = (compat_str(err['error_message']) for err in info['errors'])
302             raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
303
304         entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in info['tracks']]
305
306         return {
307             '_type': 'playlist',
308             'entries': entries,
309             'id': '%s' % info['id'],
310             'title': info['title'],
311         }
312
313
314 class SoundcloudUserIE(SoundcloudIE):
315     _VALID_URL = r'''(?x)
316                         https?://
317                             (?:(?:www|m)\.)?soundcloud\.com/
318                             (?P<user>[^/]+)
319                             (?:/
320                                 (?P<rsrc>tracks|sets|reposts|likes|spotlight)
321                             )?
322                             /?(?:[?#].*)?$
323                     '''
324     IE_NAME = 'soundcloud:user'
325     _TESTS = [{
326         'url': 'https://soundcloud.com/the-akashic-chronicler',
327         'info_dict': {
328             'id': '114582580',
329             'title': 'The Akashic Chronicler (All)',
330         },
331         'playlist_mincount': 111,
332     }, {
333         'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
334         'info_dict': {
335             'id': '114582580',
336             'title': 'The Akashic Chronicler (Tracks)',
337         },
338         'playlist_mincount': 50,
339     }, {
340         'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
341         'info_dict': {
342             'id': '114582580',
343             'title': 'The Akashic Chronicler (Playlists)',
344         },
345         'playlist_mincount': 3,
346     }, {
347         'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
348         'info_dict': {
349             'id': '114582580',
350             'title': 'The Akashic Chronicler (Reposts)',
351         },
352         'playlist_mincount': 7,
353     }, {
354         'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
355         'info_dict': {
356             'id': '114582580',
357             'title': 'The Akashic Chronicler (Likes)',
358         },
359         'playlist_mincount': 321,
360     }, {
361         'url': 'https://soundcloud.com/grynpyret/spotlight',
362         'info_dict': {
363             'id': '7098329',
364             'title': 'Grynpyret (Spotlight)',
365         },
366         'playlist_mincount': 1,
367     }]
368
369     _API_BASE = 'https://api.soundcloud.com'
370     _API_V2_BASE = 'https://api-v2.soundcloud.com'
371
372     _BASE_URL_MAP = {
373         'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE,
374         'tracks': '%s/users/%%s/tracks' % _API_BASE,
375         'sets': '%s/users/%%s/playlists' % _API_V2_BASE,
376         'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE,
377         'likes': '%s/users/%%s/likes' % _API_V2_BASE,
378         'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE,
379     }
380
381     _TITLE_MAP = {
382         'all': 'All',
383         'tracks': 'Tracks',
384         'sets': 'Playlists',
385         'reposts': 'Reposts',
386         'likes': 'Likes',
387         'spotlight': 'Spotlight',
388     }
389
390     def _real_extract(self, url):
391         mobj = re.match(self._VALID_URL, url)
392         uploader = mobj.group('user')
393
394         url = 'http://soundcloud.com/%s/' % uploader
395         resolv_url = self._resolv_url(url)
396         user = self._download_json(
397             resolv_url, uploader, 'Downloading user info')
398
399         resource = mobj.group('rsrc') or 'all'
400         base_url = self._BASE_URL_MAP[resource] % user['id']
401
402         COMMON_QUERY = {
403             'limit': 50,
404             'client_id': self._CLIENT_ID,
405             'linked_partitioning': '1',
406         }
407
408         query = COMMON_QUERY.copy()
409         query['offset'] = 0
410
411         next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
412
413         entries = []
414         for i in itertools.count():
415             response = self._download_json(
416                 next_href, uploader, 'Downloading track page %s' % (i + 1))
417
418             collection = response['collection']
419             if not collection:
420                 break
421
422             def resolve_permalink_url(candidates):
423                 for cand in candidates:
424                     if isinstance(cand, dict):
425                         permalink_url = cand.get('permalink_url')
426                         if permalink_url and permalink_url.startswith('http'):
427                             return permalink_url
428
429             for e in collection:
430                 permalink_url = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
431                 if permalink_url:
432                     entries.append(self.url_result(permalink_url))
433
434             next_href = response.get('next_href')
435             if not next_href:
436                 break
437
438             parsed_next_href = compat_urlparse.urlparse(response['next_href'])
439             qs = compat_urlparse.parse_qs(parsed_next_href.query)
440             qs.update(COMMON_QUERY)
441             next_href = compat_urlparse.urlunparse(
442                 parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
443
444         return {
445             '_type': 'playlist',
446             'id': compat_str(user['id']),
447             'title': '%s (%s)' % (user['username'], self._TITLE_MAP[resource]),
448             'entries': entries,
449         }
450
451
452 class SoundcloudPlaylistIE(SoundcloudIE):
453     _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
454     IE_NAME = 'soundcloud:playlist'
455     _TESTS = [{
456         'url': 'http://api.soundcloud.com/playlists/4110309',
457         'info_dict': {
458             'id': '4110309',
459             'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
460             'description': 're:.*?TILT Brass - Bowery Poetry Club',
461         },
462         'playlist_count': 6,
463     }]
464
465     def _real_extract(self, url):
466         mobj = re.match(self._VALID_URL, url)
467         playlist_id = mobj.group('id')
468         base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
469
470         data_dict = {
471             'client_id': self._CLIENT_ID,
472         }
473         token = mobj.group('token')
474
475         if token:
476             data_dict['secret_token'] = token
477
478         data = compat_urllib_parse_urlencode(data_dict)
479         data = self._download_json(
480             base_url + data, playlist_id, 'Downloading playlist')
481
482         entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in data['tracks']]
483
484         return {
485             '_type': 'playlist',
486             'id': playlist_id,
487             'title': data.get('title'),
488             'description': data.get('description'),
489             'entries': entries,
490         }
491
492
493 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
494     IE_NAME = 'soundcloud:search'
495     IE_DESC = 'Soundcloud search'
496     _MAX_RESULTS = float('inf')
497     _TESTS = [{
498         'url': 'scsearch15:post-avant jazzcore',
499         'info_dict': {
500             'title': 'post-avant jazzcore',
501         },
502         'playlist_count': 15,
503     }]
504
505     _SEARCH_KEY = 'scsearch'
506     _MAX_RESULTS_PER_PAGE = 200
507     _DEFAULT_RESULTS_PER_PAGE = 50
508     _API_V2_BASE = 'https://api-v2.soundcloud.com'
509
510     def _get_collection(self, endpoint, collection_id, **query):
511         limit = min(
512             query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
513             self._MAX_RESULTS_PER_PAGE)
514         query['limit'] = limit
515         query['client_id'] = self._CLIENT_ID
516         query['linked_partitioning'] = '1'
517         query['offset'] = 0
518         data = compat_urllib_parse_urlencode(query)
519         next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
520
521         collected_results = 0
522
523         for i in itertools.count(1):
524             response = self._download_json(
525                 next_url, collection_id, 'Downloading page {0}'.format(i),
526                 'Unable to download API page')
527
528             collection = response.get('collection', [])
529             if not collection:
530                 break
531
532             collection = list(filter(bool, collection))
533             collected_results += len(collection)
534
535             for item in collection:
536                 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
537
538             if not collection or collected_results >= limit:
539                 break
540
541             next_url = response.get('next_href')
542             if not next_url:
543                 break
544
545     def _get_n_results(self, query, n):
546         tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
547         return self.playlist_result(tracks, playlist_title=query)