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