]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/soundcloud.py
3c1d058db9cf546bb94a299d9f1badd79fab12d3
[youtubedl] / 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 'webpage_url': info.get('permalink_url'),
145 }
146 formats = []
147 if info.get('downloadable', False):
148 # We can build a direct link to the song
149 format_url = (
150 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
151 track_id, self._CLIENT_ID))
152 formats.append({
153 'format_id': 'download',
154 'ext': info.get('original_format', 'mp3'),
155 'url': format_url,
156 'vcodec': 'none',
157 'preference': 10,
158 })
159
160 # We have to retrieve the url
161 streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
162 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
163 format_dict = self._download_json(
164 streams_url,
165 track_id, 'Downloading track url')
166
167 for key, stream_url in format_dict.items():
168 if key.startswith('http'):
169 formats.append({
170 'format_id': key,
171 'ext': ext,
172 'url': stream_url,
173 'vcodec': 'none',
174 })
175 elif key.startswith('rtmp'):
176 # The url doesn't have an rtmp app, we have to extract the playpath
177 url, path = stream_url.split('mp3:', 1)
178 formats.append({
179 'format_id': key,
180 'url': url,
181 'play_path': 'mp3:' + path,
182 'ext': ext,
183 'vcodec': 'none',
184 })
185
186 if not formats:
187 # We fallback to the stream_url in the original info, this
188 # cannot be always used, sometimes it can give an HTTP 404 error
189 formats.append({
190 'format_id': 'fallback',
191 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
192 'ext': ext,
193 'vcodec': 'none',
194 })
195
196 for f in formats:
197 if f['format_id'].startswith('http'):
198 f['protocol'] = 'http'
199 if f['format_id'].startswith('rtmp'):
200 f['protocol'] = 'rtmp'
201
202 self._sort_formats(formats)
203 result['formats'] = formats
204
205 return result
206
207 def _real_extract(self, url):
208 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
209 if mobj is None:
210 raise ExtractorError('Invalid URL: %s' % url)
211
212 track_id = mobj.group('track_id')
213 token = None
214 if track_id is not None:
215 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
216 full_title = track_id
217 token = mobj.group('secret_token')
218 if token:
219 info_json_url += "&secret_token=" + token
220 elif mobj.group('player'):
221 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
222 return self.url_result(query['url'][0])
223 else:
224 # extract uploader (which is in the url)
225 uploader = mobj.group('uploader')
226 # extract simple title (uploader + slug of song title)
227 slug_title = mobj.group('title')
228 token = mobj.group('token')
229 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
230 if token:
231 resolve_title += '/%s' % token
232
233 self.report_resolve(full_title)
234
235 url = 'http://soundcloud.com/%s' % resolve_title
236 info_json_url = self._resolv_url(url)
237 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
238
239 return self._extract_info_dict(info, full_title, secret_token=token)
240
241
242 class SoundcloudSetIE(SoundcloudIE):
243 _VALID_URL = r'https?://(?:www\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
244 IE_NAME = 'soundcloud:set'
245 _TESTS = [{
246 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
247 'info_dict': {
248 'title': 'The Royal Concept EP',
249 },
250 'playlist_mincount': 6,
251 }]
252
253 def _real_extract(self, url):
254 mobj = re.match(self._VALID_URL, url)
255
256 # extract uploader (which is in the url)
257 uploader = mobj.group('uploader')
258 # extract simple title (uploader + slug of song title)
259 slug_title = mobj.group('slug_title')
260 full_title = '%s/sets/%s' % (uploader, slug_title)
261 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
262
263 token = mobj.group('token')
264 if token:
265 full_title += '/' + token
266 url += '/' + token
267
268 self.report_resolve(full_title)
269
270 resolv_url = self._resolv_url(url)
271 info = self._download_json(resolv_url, full_title)
272
273 if 'errors' in info:
274 for err in info['errors']:
275 self._downloader.report_error('unable to download video webpage: %s' % compat_str(err['error_message']))
276 return
277
278 return {
279 '_type': 'playlist',
280 'entries': [self._extract_info_dict(track, secret_token=token) for track in info['tracks']],
281 'id': info['id'],
282 'title': info['title'],
283 }
284
285
286 class SoundcloudUserIE(SoundcloudIE):
287 _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)/?((?P<rsrc>tracks|likes)/?)?(\?.*)?$'
288 IE_NAME = 'soundcloud:user'
289 _TESTS = [{
290 'url': 'https://soundcloud.com/the-concept-band',
291 'info_dict': {
292 'id': '9615865',
293 'title': 'The Royal Concept',
294 },
295 'playlist_mincount': 12
296 }, {
297 'url': 'https://soundcloud.com/the-concept-band/likes',
298 'info_dict': {
299 'id': '9615865',
300 'title': 'The Royal Concept',
301 },
302 'playlist_mincount': 1,
303 }]
304
305 def _real_extract(self, url):
306 mobj = re.match(self._VALID_URL, url)
307 uploader = mobj.group('user')
308 resource = mobj.group('rsrc')
309 if resource is None:
310 resource = 'tracks'
311 elif resource == 'likes':
312 resource = 'favorites'
313
314 url = 'http://soundcloud.com/%s/' % uploader
315 resolv_url = self._resolv_url(url)
316 user = self._download_json(
317 resolv_url, uploader, 'Downloading user info')
318 base_url = 'http://api.soundcloud.com/users/%s/%s.json?' % (uploader, resource)
319
320 entries = []
321 for i in itertools.count():
322 data = compat_urllib_parse.urlencode({
323 'offset': i * 50,
324 'limit': 50,
325 'client_id': self._CLIENT_ID,
326 })
327 new_entries = self._download_json(
328 base_url + data, uploader, 'Downloading track page %s' % (i + 1))
329 if len(new_entries) == 0:
330 self.to_screen('%s: End page received' % uploader)
331 break
332 entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
333
334 return {
335 '_type': 'playlist',
336 'id': compat_str(user['id']),
337 'title': user['username'],
338 'entries': entries,
339 }
340
341
342 class SoundcloudPlaylistIE(SoundcloudIE):
343 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
344 IE_NAME = 'soundcloud:playlist'
345 _TESTS = [{
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 def _real_extract(self, url):
356 mobj = re.match(self._VALID_URL, url)
357 playlist_id = mobj.group('id')
358 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
359
360 data_dict = {
361 'client_id': self._CLIENT_ID,
362 }
363 token = mobj.group('token')
364
365 if token:
366 data_dict['secret_token'] = token
367
368 data = compat_urllib_parse.urlencode(data_dict)
369 data = self._download_json(
370 base_url + data, playlist_id, 'Downloading playlist')
371
372 entries = [
373 self._extract_info_dict(t, quiet=True, secret_token=token)
374 for t in data['tracks']]
375
376 return {
377 '_type': 'playlist',
378 'id': playlist_id,
379 'title': data.get('title'),
380 'description': data.get('description'),
381 'entries': entries,
382 }