]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/soundcloud.py
194dabc71d84072fc64afd50baa3b80467c0808f
[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 def report_resolve(self, video_id):
123 """Report information extraction."""
124 self.to_screen('%s: Resolving id' % video_id)
125
126 @classmethod
127 def _resolv_url(cls, url):
128 return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
129
130 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
131 track_id = compat_str(info['id'])
132 name = full_title or track_id
133 if quiet:
134 self.report_extraction(name)
135
136 thumbnail = info['artwork_url']
137 if thumbnail is not None:
138 thumbnail = thumbnail.replace('-large', '-t500x500')
139 ext = 'mp3'
140 result = {
141 'id': track_id,
142 'uploader': info['user']['username'],
143 'upload_date': unified_strdate(info['created_at']),
144 'title': info['title'],
145 'description': info['description'],
146 'thumbnail': thumbnail,
147 'duration': int_or_none(info.get('duration'), 1000),
148 'webpage_url': info.get('permalink_url'),
149 }
150 formats = []
151 if info.get('downloadable', False):
152 # We can build a direct link to the song
153 format_url = (
154 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
155 track_id, self._CLIENT_ID))
156 formats.append({
157 'format_id': 'download',
158 'ext': info.get('original_format', 'mp3'),
159 'url': format_url,
160 'vcodec': 'none',
161 'preference': 10,
162 })
163
164 # We have to retrieve the url
165 streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
166 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
167 format_dict = self._download_json(
168 streams_url,
169 track_id, 'Downloading track url')
170
171 for key, stream_url in format_dict.items():
172 if key.startswith('http'):
173 formats.append({
174 'format_id': key,
175 'ext': ext,
176 'url': stream_url,
177 'vcodec': 'none',
178 })
179 elif key.startswith('rtmp'):
180 # The url doesn't have an rtmp app, we have to extract the playpath
181 url, path = stream_url.split('mp3:', 1)
182 formats.append({
183 'format_id': key,
184 'url': url,
185 'play_path': 'mp3:' + path,
186 'ext': 'flv',
187 'vcodec': 'none',
188 })
189
190 if not formats:
191 # We fallback to the stream_url in the original info, this
192 # cannot be always used, sometimes it can give an HTTP 404 error
193 formats.append({
194 'format_id': 'fallback',
195 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
196 'ext': ext,
197 'vcodec': 'none',
198 })
199
200 for f in formats:
201 if f['format_id'].startswith('http'):
202 f['protocol'] = 'http'
203 if f['format_id'].startswith('rtmp'):
204 f['protocol'] = 'rtmp'
205
206 self._check_formats(formats, track_id)
207 self._sort_formats(formats)
208 result['formats'] = formats
209
210 return result
211
212 def _real_extract(self, url):
213 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
214 if mobj is None:
215 raise ExtractorError('Invalid URL: %s' % url)
216
217 track_id = mobj.group('track_id')
218 token = None
219 if track_id is not None:
220 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
221 full_title = track_id
222 token = mobj.group('secret_token')
223 if token:
224 info_json_url += '&secret_token=' + token
225 elif mobj.group('player'):
226 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
227 real_url = query['url'][0]
228 # If the token is in the query of the original url we have to
229 # manually add it
230 if 'secret_token' in query:
231 real_url += '?secret_token=' + query['secret_token'][0]
232 return self.url_result(real_url)
233 else:
234 # extract uploader (which is in the url)
235 uploader = mobj.group('uploader')
236 # extract simple title (uploader + slug of song title)
237 slug_title = mobj.group('title')
238 token = mobj.group('token')
239 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
240 if token:
241 resolve_title += '/%s' % token
242
243 self.report_resolve(full_title)
244
245 url = 'http://soundcloud.com/%s' % resolve_title
246 info_json_url = self._resolv_url(url)
247 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
248
249 return self._extract_info_dict(info, full_title, secret_token=token)
250
251
252 class SoundcloudSetIE(SoundcloudIE):
253 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
254 IE_NAME = 'soundcloud:set'
255 _TESTS = [{
256 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
257 'info_dict': {
258 'id': '2284613',
259 'title': 'The Royal Concept EP',
260 },
261 'playlist_mincount': 6,
262 }]
263
264 def _real_extract(self, url):
265 mobj = re.match(self._VALID_URL, url)
266
267 # extract uploader (which is in the url)
268 uploader = mobj.group('uploader')
269 # extract simple title (uploader + slug of song title)
270 slug_title = mobj.group('slug_title')
271 full_title = '%s/sets/%s' % (uploader, slug_title)
272 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
273
274 token = mobj.group('token')
275 if token:
276 full_title += '/' + token
277 url += '/' + token
278
279 self.report_resolve(full_title)
280
281 resolv_url = self._resolv_url(url)
282 info = self._download_json(resolv_url, full_title)
283
284 if 'errors' in info:
285 msgs = (compat_str(err['error_message']) for err in info['errors'])
286 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
287
288 entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in info['tracks']]
289
290 return {
291 '_type': 'playlist',
292 'entries': entries,
293 'id': '%s' % info['id'],
294 'title': info['title'],
295 }
296
297
298 class SoundcloudUserIE(SoundcloudIE):
299 _VALID_URL = r'''(?x)
300 https?://
301 (?:(?:www|m)\.)?soundcloud\.com/
302 (?P<user>[^/]+)
303 (?:/
304 (?P<rsrc>tracks|sets|reposts|likes|spotlight)
305 )?
306 /?(?:[?#].*)?$
307 '''
308 IE_NAME = 'soundcloud:user'
309 _TESTS = [{
310 'url': 'https://soundcloud.com/the-akashic-chronicler',
311 'info_dict': {
312 'id': '114582580',
313 'title': 'The Akashic Chronicler (All)',
314 },
315 'playlist_mincount': 111,
316 }, {
317 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
318 'info_dict': {
319 'id': '114582580',
320 'title': 'The Akashic Chronicler (Tracks)',
321 },
322 'playlist_mincount': 50,
323 }, {
324 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
325 'info_dict': {
326 'id': '114582580',
327 'title': 'The Akashic Chronicler (Playlists)',
328 },
329 'playlist_mincount': 3,
330 }, {
331 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
332 'info_dict': {
333 'id': '114582580',
334 'title': 'The Akashic Chronicler (Reposts)',
335 },
336 'playlist_mincount': 7,
337 }, {
338 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
339 'info_dict': {
340 'id': '114582580',
341 'title': 'The Akashic Chronicler (Likes)',
342 },
343 'playlist_mincount': 321,
344 }, {
345 'url': 'https://soundcloud.com/grynpyret/spotlight',
346 'info_dict': {
347 'id': '7098329',
348 'title': 'Grynpyret (Spotlight)',
349 },
350 'playlist_mincount': 1,
351 }]
352
353 _API_BASE = 'https://api.soundcloud.com'
354 _API_V2_BASE = 'https://api-v2.soundcloud.com'
355
356 _BASE_URL_MAP = {
357 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE,
358 'tracks': '%s/users/%%s/tracks' % _API_BASE,
359 'sets': '%s/users/%%s/playlists' % _API_V2_BASE,
360 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE,
361 'likes': '%s/users/%%s/likes' % _API_V2_BASE,
362 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE,
363 }
364
365 _TITLE_MAP = {
366 'all': 'All',
367 'tracks': 'Tracks',
368 'sets': 'Playlists',
369 'reposts': 'Reposts',
370 'likes': 'Likes',
371 'spotlight': 'Spotlight',
372 }
373
374 def _real_extract(self, url):
375 mobj = re.match(self._VALID_URL, url)
376 uploader = mobj.group('user')
377
378 url = 'http://soundcloud.com/%s/' % uploader
379 resolv_url = self._resolv_url(url)
380 user = self._download_json(
381 resolv_url, uploader, 'Downloading user info')
382
383 resource = mobj.group('rsrc') or 'all'
384 base_url = self._BASE_URL_MAP[resource] % user['id']
385
386 COMMON_QUERY = {
387 'limit': 50,
388 'client_id': self._CLIENT_ID,
389 'linked_partitioning': '1',
390 }
391
392 query = COMMON_QUERY.copy()
393 query['offset'] = 0
394
395 next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
396
397 entries = []
398 for i in itertools.count():
399 response = self._download_json(
400 next_href, uploader, 'Downloading track page %s' % (i + 1))
401
402 collection = response['collection']
403 if not collection:
404 break
405
406 def resolve_permalink_url(candidates):
407 for cand in candidates:
408 if isinstance(cand, dict):
409 permalink_url = cand.get('permalink_url')
410 if permalink_url and permalink_url.startswith('http'):
411 return permalink_url
412
413 for e in collection:
414 permalink_url = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
415 if permalink_url:
416 entries.append(self.url_result(permalink_url))
417
418 next_href = response.get('next_href')
419 if not next_href:
420 break
421
422 parsed_next_href = compat_urlparse.urlparse(response['next_href'])
423 qs = compat_urlparse.parse_qs(parsed_next_href.query)
424 qs.update(COMMON_QUERY)
425 next_href = compat_urlparse.urlunparse(
426 parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
427
428 return {
429 '_type': 'playlist',
430 'id': compat_str(user['id']),
431 'title': '%s (%s)' % (user['username'], self._TITLE_MAP[resource]),
432 'entries': entries,
433 }
434
435
436 class SoundcloudPlaylistIE(SoundcloudIE):
437 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
438 IE_NAME = 'soundcloud:playlist'
439 _TESTS = [{
440 'url': 'http://api.soundcloud.com/playlists/4110309',
441 'info_dict': {
442 'id': '4110309',
443 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
444 'description': 're:.*?TILT Brass - Bowery Poetry Club',
445 },
446 'playlist_count': 6,
447 }]
448
449 def _real_extract(self, url):
450 mobj = re.match(self._VALID_URL, url)
451 playlist_id = mobj.group('id')
452 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
453
454 data_dict = {
455 'client_id': self._CLIENT_ID,
456 }
457 token = mobj.group('token')
458
459 if token:
460 data_dict['secret_token'] = token
461
462 data = compat_urllib_parse_urlencode(data_dict)
463 data = self._download_json(
464 base_url + data, playlist_id, 'Downloading playlist')
465
466 entries = [self.url_result(track['permalink_url'], 'Soundcloud') for track in data['tracks']]
467
468 return {
469 '_type': 'playlist',
470 'id': playlist_id,
471 'title': data.get('title'),
472 'description': data.get('description'),
473 'entries': entries,
474 }
475
476
477 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
478 IE_NAME = 'soundcloud:search'
479 IE_DESC = 'Soundcloud search'
480 _MAX_RESULTS = float('inf')
481 _TESTS = [{
482 'url': 'scsearch15:post-avant jazzcore',
483 'info_dict': {
484 'title': 'post-avant jazzcore',
485 },
486 'playlist_count': 15,
487 }]
488
489 _SEARCH_KEY = 'scsearch'
490 _MAX_RESULTS_PER_PAGE = 200
491 _DEFAULT_RESULTS_PER_PAGE = 50
492 _API_V2_BASE = 'https://api-v2.soundcloud.com'
493
494 def _get_collection(self, endpoint, collection_id, **query):
495 limit = min(
496 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
497 self._MAX_RESULTS_PER_PAGE)
498 query['limit'] = limit
499 query['client_id'] = self._CLIENT_ID
500 query['linked_partitioning'] = '1'
501 query['offset'] = 0
502 data = compat_urllib_parse_urlencode(query)
503 next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
504
505 collected_results = 0
506
507 for i in itertools.count(1):
508 response = self._download_json(
509 next_url, collection_id, 'Downloading page {0}'.format(i),
510 'Unable to download API page')
511
512 collection = response.get('collection', [])
513 if not collection:
514 break
515
516 collection = list(filter(bool, collection))
517 collected_results += len(collection)
518
519 for item in collection:
520 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
521
522 if not collection or collected_results >= limit:
523 break
524
525 next_url = response.get('next_href')
526 if not next_url:
527 break
528
529 def _get_n_results(self, query, n):
530 tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
531 return self.playlist_result(tracks, playlist_title=query)