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