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