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