Merge remote-tracking branch 'gabeos/crunchyroll-show-playlist'
[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 InfoExtractor
8 from ..utils import (
9     compat_str,
10     compat_urlparse,
11     compat_urllib_parse,
12
13     ExtractorError,
14     int_or_none,
15     unified_strdate,
16 )
17
18
19 class SoundcloudIE(InfoExtractor):
20     """Information extractor for soundcloud.com
21        To access the media, the uid of the song and a stream token
22        must be extracted from the page source and the script must make
23        a request to media.soundcloud.com/crossdomain.xml. Then
24        the media can be grabbed by requesting from an url composed
25        of the stream token and uid
26      """
27
28     _VALID_URL = r'''(?x)^(?:https?://)?
29                     (?:(?:(?:www\.|m\.)?soundcloud\.com/
30                             (?P<uploader>[\w\d-]+)/
31                             (?!sets/|likes/?(?:$|[?#]))
32                             (?P<title>[\w\d-]+)/?
33                             (?P<token>[^?]+?)?(?:[?].*)?$)
34                        |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
35                           (?:/?\?secret_token=(?P<secret_token>[^&]+?))?$)
36                        |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
37                     )
38                     '''
39     IE_NAME = 'soundcloud'
40     _TESTS = [
41         {
42             'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
43             'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
44             'info_dict': {
45                 'id': '62986583',
46                 'ext': 'mp3',
47                 'upload_date': '20121011',
48                 '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',
49                 'uploader': 'E.T. ExTerrestrial Music',
50                 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
51                 'duration': 143,
52             }
53         },
54         # not streamable song
55         {
56             'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
57             'info_dict': {
58                 'id': '47127627',
59                 'ext': 'mp3',
60                 'title': 'Goldrushed',
61                 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
62                 'uploader': 'The Royal Concept',
63                 'upload_date': '20120521',
64                 'duration': 227,
65             },
66             'params': {
67                 # rtmp
68                 'skip_download': True,
69             },
70         },
71         # private link
72         {
73             'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
74             'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
75             'info_dict': {
76                 'id': '123998367',
77                 'ext': 'mp3',
78                 'title': 'Youtube - Dl Test Video \'\' Ä↭',
79                 'uploader': 'jaimeMF',
80                 'description': 'test chars:  \"\'/\\ä↭',
81                 'upload_date': '20131209',
82                 'duration': 9,
83             },
84         },
85         # private link (alt format)
86         {
87             'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
88             'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
89             'info_dict': {
90                 'id': '123998367',
91                 'ext': 'mp3',
92                 'title': 'Youtube - Dl Test Video \'\' Ä↭',
93                 'uploader': 'jaimeMF',
94                 'description': 'test chars:  \"\'/\\ä↭',
95                 'upload_date': '20131209',
96                 'duration': 9,
97             },
98         },
99         # downloadable song
100         {
101             'url': 'https://soundcloud.com/oddsamples/bus-brakes',
102             'md5': '7624f2351f8a3b2e7cd51522496e7631',
103             'info_dict': {
104                 'id': '128590877',
105                 'ext': 'mp3',
106                 'title': 'Bus Brakes',
107                 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
108                 'uploader': 'oddsamples',
109                 'upload_date': '20140109',
110                 'duration': 17,
111             },
112         },
113     ]
114
115     _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
116     _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
117
118     def report_resolve(self, video_id):
119         """Report information extraction."""
120         self.to_screen('%s: Resolving id' % video_id)
121
122     @classmethod
123     def _resolv_url(cls, url):
124         return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
125
126     def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
127         track_id = compat_str(info['id'])
128         name = full_title or track_id
129         if quiet:
130             self.report_extraction(name)
131
132         thumbnail = info['artwork_url']
133         if thumbnail is not None:
134             thumbnail = thumbnail.replace('-large', '-t500x500')
135         ext = 'mp3'
136         result = {
137             'id': track_id,
138             'uploader': info['user']['username'],
139             'upload_date': unified_strdate(info['created_at']),
140             'title': info['title'],
141             'description': info['description'],
142             'thumbnail': thumbnail,
143             'duration': int_or_none(info.get('duration'), 1000),
144         }
145         formats = []
146         if info.get('downloadable', False):
147             # We can build a direct link to the song
148             format_url = (
149                 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
150                     track_id, self._CLIENT_ID))
151             formats.append({
152                 'format_id': 'download',
153                 'ext': info.get('original_format', 'mp3'),
154                 'url': format_url,
155                 'vcodec': 'none',
156                 'preference': 10,
157             })
158
159         # We have to retrieve the url
160         streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
161             'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
162         format_dict = self._download_json(
163             streams_url,
164             track_id, 'Downloading track url')
165
166         for key, stream_url in format_dict.items():
167             if key.startswith('http'):
168                 formats.append({
169                     'format_id': key,
170                     'ext': ext,
171                     'url': stream_url,
172                     'vcodec': 'none',
173                 })
174             elif key.startswith('rtmp'):
175                 # The url doesn't have an rtmp app, we have to extract the playpath
176                 url, path = stream_url.split('mp3:', 1)
177                 formats.append({
178                     'format_id': key,
179                     'url': url,
180                     'play_path': 'mp3:' + path,
181                     'ext': ext,
182                     'vcodec': 'none',
183                 })
184
185             if not formats:
186                 # We fallback to the stream_url in the original info, this
187                 # cannot be always used, sometimes it can give an HTTP 404 error
188                 formats.append({
189                     'format_id': 'fallback',
190                     'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
191                     'ext': ext,
192                     'vcodec': 'none',
193                 })
194
195             for f in formats:
196                 if f['format_id'].startswith('http'):
197                     f['protocol'] = 'http'
198                 if f['format_id'].startswith('rtmp'):
199                     f['protocol'] = 'rtmp'
200
201             self._sort_formats(formats)
202             result['formats'] = formats
203
204         return result
205
206     def _real_extract(self, url):
207         mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
208         if mobj is None:
209             raise ExtractorError('Invalid URL: %s' % url)
210
211         track_id = mobj.group('track_id')
212         token = None
213         if track_id is not None:
214             info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
215             full_title = track_id
216             token = mobj.group('secret_token')
217             if token:
218                 info_json_url += "&secret_token=" + token
219         elif mobj.group('player'):
220             query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
221             return self.url_result(query['url'][0])
222         else:
223             # extract uploader (which is in the url)
224             uploader = mobj.group('uploader')
225             # extract simple title (uploader + slug of song title)
226             slug_title =  mobj.group('title')
227             token = mobj.group('token')
228             full_title = resolve_title = '%s/%s' % (uploader, slug_title)
229             if token:
230                 resolve_title += '/%s' % token
231     
232             self.report_resolve(full_title)
233     
234             url = 'http://soundcloud.com/%s' % resolve_title
235             info_json_url = self._resolv_url(url)
236         info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
237
238         return self._extract_info_dict(info, full_title, secret_token=token)
239
240
241 class SoundcloudSetIE(SoundcloudIE):
242     _VALID_URL = r'https?://(?:www\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
243     IE_NAME = 'soundcloud:set'
244     _TESTS = [{
245         'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
246         'info_dict': {
247             'title': 'The Royal Concept EP',
248         },
249         'playlist_mincount': 6,
250     }]
251
252     def _real_extract(self, url):
253         mobj = re.match(self._VALID_URL, url)
254
255         # extract uploader (which is in the url)
256         uploader = mobj.group('uploader')
257         # extract simple title (uploader + slug of song title)
258         slug_title = mobj.group('slug_title')
259         full_title = '%s/sets/%s' % (uploader, slug_title)
260         url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
261
262         token = mobj.group('token')
263         if token:
264             full_title += '/' + token
265             url += '/' + token
266
267         self.report_resolve(full_title)
268
269         resolv_url = self._resolv_url(url)
270         info = self._download_json(resolv_url, full_title)
271
272         if 'errors' in info:
273             for err in info['errors']:
274                 self._downloader.report_error('unable to download video webpage: %s' % compat_str(err['error_message']))
275             return
276
277         return {
278             '_type': 'playlist',
279             'entries': [self._extract_info_dict(track, secret_token=token) for track in info['tracks']],
280             'id': info['id'],
281             'title': info['title'],
282         }
283
284
285 class SoundcloudUserIE(SoundcloudIE):
286     _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)/?((?P<rsrc>tracks|likes)/?)?(\?.*)?$'
287     IE_NAME = 'soundcloud:user'
288     _TESTS = [{
289         'url': 'https://soundcloud.com/the-concept-band',
290         'info_dict': {
291             'id': '9615865',
292             'title': 'The Royal Concept',
293         },
294         'playlist_mincount': 12
295     }, {
296         'url': 'https://soundcloud.com/the-concept-band/likes',
297         'info_dict': {
298             'id': '9615865',
299             'title': 'The Royal Concept',
300         },
301         'playlist_mincount': 1,
302     }]
303
304     def _real_extract(self, url):
305         mobj = re.match(self._VALID_URL, url)
306         uploader = mobj.group('user')
307         resource = mobj.group('rsrc')
308         if resource is None:
309             resource = 'tracks'
310         elif resource == 'likes':
311             resource = 'favorites'
312
313         url = 'http://soundcloud.com/%s/' % uploader
314         resolv_url = self._resolv_url(url)
315         user = self._download_json(
316             resolv_url, uploader, 'Downloading user info')
317         base_url = 'http://api.soundcloud.com/users/%s/%s.json?' % (uploader, resource)
318
319         entries = []
320         for i in itertools.count():
321             data = compat_urllib_parse.urlencode({
322                 'offset': i * 50,
323                 'limit': 50,
324                 'client_id': self._CLIENT_ID,
325             })
326             new_entries = self._download_json(
327                 base_url + data, uploader, 'Downloading track page %s' % (i + 1))
328             if len(new_entries) == 0:
329                 self.to_screen('%s: End page received' % uploader)
330                 break
331             entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
332
333         return {
334             '_type': 'playlist',
335             'id': compat_str(user['id']),
336             'title': user['username'],
337             'entries': entries,
338         }
339
340
341 class SoundcloudPlaylistIE(SoundcloudIE):
342     _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
343     IE_NAME = 'soundcloud:playlist'
344     _TESTS = [{
345         'url': 'http://api.soundcloud.com/playlists/4110309',
346         'info_dict': {
347             'id': '4110309',
348             'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
349             'description': 're:.*?TILT Brass - Bowery Poetry Club',
350         },
351         'playlist_count': 6,
352     }]
353
354     def _real_extract(self, url):
355         mobj = re.match(self._VALID_URL, url)
356         playlist_id = mobj.group('id')
357         base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
358
359         data_dict = {
360             'client_id': self._CLIENT_ID,
361         }
362         token = mobj.group('token')
363
364         if token:
365             data_dict['secret_token'] = token
366
367         data = compat_urllib_parse.urlencode(data_dict)
368         data = self._download_json(
369             base_url + data, playlist_id, 'Downloading playlist')
370
371         entries = [
372             self._extract_info_dict(t, quiet=True, secret_token=token)
373                 for t in data['tracks']]
374
375         return {
376             '_type': 'playlist',
377             'id': playlist_id,
378             'title': data.get('title'),
379             'description': data.get('description'),
380             'entries': entries,
381         }