]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/soundcloud.py
Update Standards-Version to 3.9.8 (no changes required).
[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 (
8 InfoExtractor,
9 SearchInfoExtractor
10 )
11 from ..compat import (
12 compat_str,
13 compat_urlparse,
14 compat_urllib_parse_urlencode,
15 )
16 from ..utils import (
17 ExtractorError,
18 int_or_none,
19 unified_strdate,
20 )
21
22
23 class SoundcloudIE(InfoExtractor):
24 """Information extractor for soundcloud.com
25 To access the media, the uid of the song and a stream token
26 must be extracted from the page source and the script must make
27 a request to media.soundcloud.com/crossdomain.xml. Then
28 the media can be grabbed by requesting from an url composed
29 of the stream token and uid
30 """
31
32 _VALID_URL = r'''(?x)^(?:https?://)?
33 (?:(?:(?:www\.|m\.)?soundcloud\.com/
34 (?P<uploader>[\w\d-]+)/
35 (?!(?:tracks|sets(?:/[^/?#]+)?|reposts|likes|spotlight)/?(?:$|[?#]))
36 (?P<title>[\w\d-]+)/?
37 (?P<token>[^?]+?)?(?:[?].*)?$)
38 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
39 (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
40 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
41 )
42 '''
43 IE_NAME = 'soundcloud'
44 _TESTS = [
45 {
46 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
47 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
48 'info_dict': {
49 'id': '62986583',
50 'ext': 'mp3',
51 'upload_date': '20121011',
52 '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',
53 'uploader': 'E.T. ExTerrestrial Music',
54 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
55 'duration': 143,
56 }
57 },
58 # not streamable song
59 {
60 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
61 'info_dict': {
62 'id': '47127627',
63 'ext': 'mp3',
64 'title': 'Goldrushed',
65 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
66 'uploader': 'The Royal Concept',
67 'upload_date': '20120521',
68 'duration': 227,
69 },
70 'params': {
71 # rtmp
72 'skip_download': True,
73 },
74 },
75 # private link
76 {
77 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
78 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
79 'info_dict': {
80 'id': '123998367',
81 'ext': 'mp3',
82 'title': 'Youtube - Dl Test Video \'\' Ä↭',
83 'uploader': 'jaimeMF',
84 'description': 'test chars: \"\'/\\ä↭',
85 'upload_date': '20131209',
86 'duration': 9,
87 },
88 },
89 # private link (alt format)
90 {
91 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
92 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
93 'info_dict': {
94 'id': '123998367',
95 'ext': 'mp3',
96 'title': 'Youtube - Dl Test Video \'\' Ä↭',
97 'uploader': 'jaimeMF',
98 'description': 'test chars: \"\'/\\ä↭',
99 'upload_date': '20131209',
100 'duration': 9,
101 },
102 },
103 # downloadable song
104 {
105 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
106 'md5': '7624f2351f8a3b2e7cd51522496e7631',
107 'info_dict': {
108 'id': '128590877',
109 'ext': 'mp3',
110 'title': 'Bus Brakes',
111 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
112 'uploader': 'oddsamples',
113 'upload_date': '20140109',
114 'duration': 17,
115 },
116 },
117 ]
118
119 _CLIENT_ID = '02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea'
120 _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
121
122 @staticmethod
123 def _extract_urls(webpage):
124 return [m.group('url') for m in re.finditer(
125 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
126 webpage)]
127
128 def report_resolve(self, video_id):
129 """Report information extraction."""
130 self.to_screen('%s: Resolving id' % video_id)
131
132 @classmethod
133 def _resolv_url(cls, url):
134 return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
135
136 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
137 track_id = compat_str(info['id'])
138 name = full_title or track_id
139 if quiet:
140 self.report_extraction(name)
141
142 thumbnail = info['artwork_url']
143 if thumbnail is not None:
144 thumbnail = thumbnail.replace('-large', '-t500x500')
145 ext = 'mp3'
146 result = {
147 'id': track_id,
148 'uploader': info['user']['username'],
149 'upload_date': unified_strdate(info['created_at']),
150 'title': info['title'],
151 'description': info['description'],
152 'thumbnail': thumbnail,
153 'duration': int_or_none(info.get('duration'), 1000),
154 'webpage_url': info.get('permalink_url'),
155 }
156 formats = []
157 if info.get('downloadable', False):
158 # We can build a direct link to the song
159 format_url = (
160 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
161 track_id, self._CLIENT_ID))
162 formats.append({
163 'format_id': 'download',
164 'ext': info.get('original_format', 'mp3'),
165 'url': format_url,
166 'vcodec': 'none',
167 'preference': 10,
168 })
169
170 # We have to retrieve the url
171 streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
172 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
173 format_dict = self._download_json(
174 streams_url,
175 track_id, 'Downloading track url')
176
177 for key, stream_url in format_dict.items():
178 if key.startswith('http'):
179 formats.append({
180 'format_id': key,
181 'ext': ext,
182 'url': stream_url,
183 'vcodec': 'none',
184 })
185 elif key.startswith('rtmp'):
186 # The url doesn't have an rtmp app, we have to extract the playpath
187 url, path = stream_url.split('mp3:', 1)
188 formats.append({
189 'format_id': key,
190 'url': url,
191 'play_path': 'mp3:' + path,
192 'ext': 'flv',
193 'vcodec': 'none',
194 })
195
196 if not formats:
197 # We fallback to the stream_url in the original info, this
198 # cannot be always used, sometimes it can give an HTTP 404 error
199 formats.append({
200 'format_id': 'fallback',
201 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
202 'ext': ext,
203 'vcodec': 'none',
204 })
205
206 for f in formats:
207 if f['format_id'].startswith('http'):
208 f['protocol'] = 'http'
209 if f['format_id'].startswith('rtmp'):
210 f['protocol'] = 'rtmp'
211
212 self._check_formats(formats, track_id)
213 self._sort_formats(formats)
214 result['formats'] = formats
215
216 return result
217
218 def _real_extract(self, url):
219 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
220 if mobj is None:
221 raise ExtractorError('Invalid URL: %s' % url)
222
223 track_id = mobj.group('track_id')
224 token = None
225 if track_id is not None:
226 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
227 full_title = track_id
228 token = mobj.group('secret_token')
229 if token:
230 info_json_url += '&secret_token=' + token
231 elif mobj.group('player'):
232 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
233 real_url = query['url'][0]
234 # If the token is in the query of the original url we have to
235 # manually add it
236 if 'secret_token' in query:
237 real_url += '?secret_token=' + query['secret_token'][0]
238 return self.url_result(real_url)
239 else:
240 # extract uploader (which is in the url)
241 uploader = mobj.group('uploader')
242 # extract simple title (uploader + slug of song title)
243 slug_title = mobj.group('title')
244 token = mobj.group('token')
245 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
246 if token:
247 resolve_title += '/%s' % token
248
249 self.report_resolve(full_title)
250
251 url = 'http://soundcloud.com/%s' % resolve_title
252 info_json_url = self._resolv_url(url)
253 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
254
255 return self._extract_info_dict(info, full_title, secret_token=token)
256
257
258 class SoundcloudSetIE(SoundcloudIE):
259 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
260 IE_NAME = 'soundcloud:set'
261 _TESTS = [{
262 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
263 'info_dict': {
264 'id': '2284613',
265 'title': 'The Royal Concept EP',
266 },
267 'playlist_mincount': 6,
268 }]
269
270 def _real_extract(self, url):
271 mobj = re.match(self._VALID_URL, url)
272
273 # extract uploader (which is in the url)
274 uploader = mobj.group('uploader')
275 # extract simple title (uploader + slug of song title)
276 slug_title = mobj.group('slug_title')
277 full_title = '%s/sets/%s' % (uploader, slug_title)
278 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
279
280 token = mobj.group('token')
281 if token:
282 full_title += '/' + token
283 url += '/' + token
284
285 self.report_resolve(full_title)
286
287 resolv_url = self._resolv_url(url)
288 info = self._download_json(resolv_url, full_title)
289
290 if 'errors' in info:
291 msgs = (compat_str(err['error_message']) for err in info['errors'])
292 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
293
294 entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in info['tracks']]
295
296 return {
297 '_type': 'playlist',
298 'entries': entries,
299 'id': '%s' % info['id'],
300 'title': info['title'],
301 }
302
303
304 class SoundcloudUserIE(SoundcloudIE):
305 _VALID_URL = r'''(?x)
306 https?://
307 (?:(?:www|m)\.)?soundcloud\.com/
308 (?P<user>[^/]+)
309 (?:/
310 (?P<rsrc>tracks|sets|reposts|likes|spotlight)
311 )?
312 /?(?:[?#].*)?$
313 '''
314 IE_NAME = 'soundcloud:user'
315 _TESTS = [{
316 'url': 'https://soundcloud.com/the-akashic-chronicler',
317 'info_dict': {
318 'id': '114582580',
319 'title': 'The Akashic Chronicler (All)',
320 },
321 'playlist_mincount': 111,
322 }, {
323 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
324 'info_dict': {
325 'id': '114582580',
326 'title': 'The Akashic Chronicler (Tracks)',
327 },
328 'playlist_mincount': 50,
329 }, {
330 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
331 'info_dict': {
332 'id': '114582580',
333 'title': 'The Akashic Chronicler (Playlists)',
334 },
335 'playlist_mincount': 3,
336 }, {
337 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
338 'info_dict': {
339 'id': '114582580',
340 'title': 'The Akashic Chronicler (Reposts)',
341 },
342 'playlist_mincount': 7,
343 }, {
344 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
345 'info_dict': {
346 'id': '114582580',
347 'title': 'The Akashic Chronicler (Likes)',
348 },
349 'playlist_mincount': 321,
350 }, {
351 'url': 'https://soundcloud.com/grynpyret/spotlight',
352 'info_dict': {
353 'id': '7098329',
354 'title': 'Grynpyret (Spotlight)',
355 },
356 'playlist_mincount': 1,
357 }]
358
359 _API_BASE = 'https://api.soundcloud.com'
360 _API_V2_BASE = 'https://api-v2.soundcloud.com'
361
362 _BASE_URL_MAP = {
363 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE,
364 'tracks': '%s/users/%%s/tracks' % _API_BASE,
365 'sets': '%s/users/%%s/playlists' % _API_V2_BASE,
366 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE,
367 'likes': '%s/users/%%s/likes' % _API_V2_BASE,
368 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE,
369 }
370
371 _TITLE_MAP = {
372 'all': 'All',
373 'tracks': 'Tracks',
374 'sets': 'Playlists',
375 'reposts': 'Reposts',
376 'likes': 'Likes',
377 'spotlight': 'Spotlight',
378 }
379
380 def _real_extract(self, url):
381 mobj = re.match(self._VALID_URL, url)
382 uploader = mobj.group('user')
383
384 url = 'http://soundcloud.com/%s/' % uploader
385 resolv_url = self._resolv_url(url)
386 user = self._download_json(
387 resolv_url, uploader, 'Downloading user info')
388
389 resource = mobj.group('rsrc') or 'all'
390 base_url = self._BASE_URL_MAP[resource] % user['id']
391
392 COMMON_QUERY = {
393 'limit': 50,
394 'client_id': self._CLIENT_ID,
395 'linked_partitioning': '1',
396 }
397
398 query = COMMON_QUERY.copy()
399 query['offset'] = 0
400
401 next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
402
403 entries = []
404 for i in itertools.count():
405 response = self._download_json(
406 next_href, uploader, 'Downloading track page %s' % (i + 1))
407
408 collection = response['collection']
409 if not collection:
410 break
411
412 def resolve_permalink_url(candidates):
413 for cand in candidates:
414 if isinstance(cand, dict):
415 permalink_url = cand.get('permalink_url')
416 if permalink_url and permalink_url.startswith('http'):
417 return permalink_url
418
419 for e in collection:
420 permalink_url = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
421 if permalink_url:
422 entries.append(self.url_result(permalink_url))
423
424 next_href = response.get('next_href')
425 if not next_href:
426 break
427
428 parsed_next_href = compat_urlparse.urlparse(response['next_href'])
429 qs = compat_urlparse.parse_qs(parsed_next_href.query)
430 qs.update(COMMON_QUERY)
431 next_href = compat_urlparse.urlunparse(
432 parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
433
434 return {
435 '_type': 'playlist',
436 'id': compat_str(user['id']),
437 'title': '%s (%s)' % (user['username'], self._TITLE_MAP[resource]),
438 'entries': entries,
439 }
440
441
442 class SoundcloudPlaylistIE(SoundcloudIE):
443 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
444 IE_NAME = 'soundcloud:playlist'
445 _TESTS = [{
446 'url': 'http://api.soundcloud.com/playlists/4110309',
447 'info_dict': {
448 'id': '4110309',
449 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
450 'description': 're:.*?TILT Brass - Bowery Poetry Club',
451 },
452 'playlist_count': 6,
453 }]
454
455 def _real_extract(self, url):
456 mobj = re.match(self._VALID_URL, url)
457 playlist_id = mobj.group('id')
458 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
459
460 data_dict = {
461 'client_id': self._CLIENT_ID,
462 }
463 token = mobj.group('token')
464
465 if token:
466 data_dict['secret_token'] = token
467
468 data = compat_urllib_parse_urlencode(data_dict)
469 data = self._download_json(
470 base_url + data, playlist_id, 'Downloading playlist')
471
472 entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in data['tracks']]
473
474 return {
475 '_type': 'playlist',
476 'id': playlist_id,
477 'title': data.get('title'),
478 'description': data.get('description'),
479 'entries': entries,
480 }
481
482
483 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
484 IE_NAME = 'soundcloud:search'
485 IE_DESC = 'Soundcloud search'
486 _MAX_RESULTS = float('inf')
487 _TESTS = [{
488 'url': 'scsearch15:post-avant jazzcore',
489 'info_dict': {
490 'title': 'post-avant jazzcore',
491 },
492 'playlist_count': 15,
493 }]
494
495 _SEARCH_KEY = 'scsearch'
496 _MAX_RESULTS_PER_PAGE = 200
497 _DEFAULT_RESULTS_PER_PAGE = 50
498 _API_V2_BASE = 'https://api-v2.soundcloud.com'
499
500 def _get_collection(self, endpoint, collection_id, **query):
501 limit = min(
502 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
503 self._MAX_RESULTS_PER_PAGE)
504 query['limit'] = limit
505 query['client_id'] = self._CLIENT_ID
506 query['linked_partitioning'] = '1'
507 query['offset'] = 0
508 data = compat_urllib_parse_urlencode(query)
509 next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
510
511 collected_results = 0
512
513 for i in itertools.count(1):
514 response = self._download_json(
515 next_url, collection_id, 'Downloading page {0}'.format(i),
516 'Unable to download API page')
517
518 collection = response.get('collection', [])
519 if not collection:
520 break
521
522 collection = list(filter(bool, collection))
523 collected_results += len(collection)
524
525 for item in collection:
526 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
527
528 if not collection or collected_results >= limit:
529 break
530
531 next_url = response.get('next_href')
532 if not next_url:
533 break
534
535 def _get_n_results(self, query, n):
536 tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
537 return self.playlist_result(tracks, playlist_title=query)