]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/soundcloud.py
d/p/remove-autoupdate-mechanism.patch: Update patch with metadata at the top.
[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 = 'LvWovRaJZlWCHql0bISuum8Bd2KX79mb'
161
162 @staticmethod
163 def _extract_urls(webpage):
164 return [m.group('url') for m in re.finditer(
165 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
166 webpage)]
167
168 def report_resolve(self, video_id):
169 """Report information extraction."""
170 self.to_screen('%s: Resolving id' % video_id)
171
172 @classmethod
173 def _resolv_url(cls, url):
174 return 'https://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
175
176 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
177 track_id = compat_str(info['id'])
178 name = full_title or track_id
179 if quiet:
180 self.report_extraction(name)
181 thumbnail = info.get('artwork_url') or info.get('user', {}).get('avatar_url')
182 if isinstance(thumbnail, compat_str):
183 thumbnail = thumbnail.replace('-large', '-t500x500')
184 ext = 'mp3'
185 result = {
186 'id': track_id,
187 'uploader': info.get('user', {}).get('username'),
188 'upload_date': unified_strdate(info.get('created_at')),
189 'title': info['title'],
190 'description': info.get('description'),
191 'thumbnail': thumbnail,
192 'duration': int_or_none(info.get('duration'), 1000),
193 'webpage_url': info.get('permalink_url'),
194 'license': info.get('license'),
195 }
196 formats = []
197 query = {'client_id': self._CLIENT_ID}
198 if secret_token is not None:
199 query['secret_token'] = secret_token
200 if info.get('downloadable', False):
201 # We can build a direct link to the song
202 format_url = update_url_query(
203 'https://api.soundcloud.com/tracks/%s/download' % track_id, query)
204 formats.append({
205 'format_id': 'download',
206 'ext': info.get('original_format', 'mp3'),
207 'url': format_url,
208 'vcodec': 'none',
209 'preference': 10,
210 })
211
212 # We have to retrieve the url
213 format_dict = self._download_json(
214 'https://api.soundcloud.com/i1/tracks/%s/streams' % track_id,
215 track_id, 'Downloading track url', query=query)
216
217 for key, stream_url in format_dict.items():
218 abr = int_or_none(self._search_regex(
219 r'_(\d+)_url', key, 'audio bitrate', default=None))
220 if key.startswith('http'):
221 stream_formats = [{
222 'format_id': key,
223 'ext': ext,
224 'url': stream_url,
225 }]
226 elif key.startswith('rtmp'):
227 # The url doesn't have an rtmp app, we have to extract the playpath
228 url, path = stream_url.split('mp3:', 1)
229 stream_formats = [{
230 'format_id': key,
231 'url': url,
232 'play_path': 'mp3:' + path,
233 'ext': 'flv',
234 }]
235 elif key.startswith('hls'):
236 stream_formats = self._extract_m3u8_formats(
237 stream_url, track_id, 'mp3', entry_protocol='m3u8_native',
238 m3u8_id=key, fatal=False)
239 else:
240 continue
241
242 for f in stream_formats:
243 f['abr'] = abr
244
245 formats.extend(stream_formats)
246
247 if not formats:
248 # We fallback to the stream_url in the original info, this
249 # cannot be always used, sometimes it can give an HTTP 404 error
250 formats.append({
251 'format_id': 'fallback',
252 'url': update_url_query(info['stream_url'], query),
253 'ext': ext,
254 })
255
256 for f in formats:
257 f['vcodec'] = 'none'
258
259 self._check_formats(formats, track_id)
260 self._sort_formats(formats)
261 result['formats'] = formats
262
263 return result
264
265 def _real_extract(self, url):
266 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
267 if mobj is None:
268 raise ExtractorError('Invalid URL: %s' % url)
269
270 track_id = mobj.group('track_id')
271
272 if track_id is not None:
273 info_json_url = 'https://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
274 full_title = track_id
275 token = mobj.group('secret_token')
276 if token:
277 info_json_url += '&secret_token=' + token
278 elif mobj.group('player'):
279 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
280 real_url = query['url'][0]
281 # If the token is in the query of the original url we have to
282 # manually add it
283 if 'secret_token' in query:
284 real_url += '?secret_token=' + query['secret_token'][0]
285 return self.url_result(real_url)
286 else:
287 # extract uploader (which is in the url)
288 uploader = mobj.group('uploader')
289 # extract simple title (uploader + slug of song title)
290 slug_title = mobj.group('title')
291 token = mobj.group('token')
292 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
293 if token:
294 resolve_title += '/%s' % token
295
296 self.report_resolve(full_title)
297
298 url = 'https://soundcloud.com/%s' % resolve_title
299 info_json_url = self._resolv_url(url)
300 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
301
302 return self._extract_info_dict(info, full_title, secret_token=token)
303
304
305 class SoundcloudPlaylistBaseIE(SoundcloudIE):
306 @staticmethod
307 def _extract_id(e):
308 return compat_str(e['id']) if e.get('id') else None
309
310 def _extract_track_entries(self, tracks):
311 return [
312 self.url_result(
313 track['permalink_url'], SoundcloudIE.ie_key(),
314 video_id=self._extract_id(track))
315 for track in tracks if track.get('permalink_url')]
316
317
318 class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
319 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
320 IE_NAME = 'soundcloud:set'
321 _TESTS = [{
322 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
323 'info_dict': {
324 'id': '2284613',
325 'title': 'The Royal Concept EP',
326 },
327 'playlist_mincount': 5,
328 }, {
329 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
330 'only_matching': True,
331 }]
332
333 def _real_extract(self, url):
334 mobj = re.match(self._VALID_URL, url)
335
336 # extract uploader (which is in the url)
337 uploader = mobj.group('uploader')
338 # extract simple title (uploader + slug of song title)
339 slug_title = mobj.group('slug_title')
340 full_title = '%s/sets/%s' % (uploader, slug_title)
341 url = 'https://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
342
343 token = mobj.group('token')
344 if token:
345 full_title += '/' + token
346 url += '/' + token
347
348 self.report_resolve(full_title)
349
350 resolv_url = self._resolv_url(url)
351 info = self._download_json(resolv_url, full_title)
352
353 if 'errors' in info:
354 msgs = (compat_str(err['error_message']) for err in info['errors'])
355 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
356
357 entries = self._extract_track_entries(info['tracks'])
358
359 return {
360 '_type': 'playlist',
361 'entries': entries,
362 'id': '%s' % info['id'],
363 'title': info['title'],
364 }
365
366
367 class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
368 _API_BASE = 'https://api.soundcloud.com'
369 _API_V2_BASE = 'https://api-v2.soundcloud.com'
370
371 def _extract_playlist(self, base_url, playlist_id, playlist_title):
372 COMMON_QUERY = {
373 'limit': 50,
374 'client_id': self._CLIENT_ID,
375 'linked_partitioning': '1',
376 }
377
378 query = COMMON_QUERY.copy()
379 query['offset'] = 0
380
381 next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
382
383 entries = []
384 for i in itertools.count():
385 response = self._download_json(
386 next_href, playlist_id, 'Downloading track page %s' % (i + 1))
387
388 collection = response['collection']
389 if not collection:
390 break
391
392 def resolve_permalink_url(candidates):
393 for cand in candidates:
394 if isinstance(cand, dict):
395 permalink_url = cand.get('permalink_url')
396 entry_id = self._extract_id(cand)
397 if permalink_url and permalink_url.startswith('http'):
398 return permalink_url, entry_id
399
400 for e in collection:
401 permalink_url, entry_id = resolve_permalink_url((e, e.get('track'), e.get('playlist')))
402 if permalink_url:
403 entries.append(self.url_result(permalink_url, video_id=entry_id))
404
405 next_href = response.get('next_href')
406 if not next_href:
407 break
408
409 parsed_next_href = compat_urlparse.urlparse(response['next_href'])
410 qs = compat_urlparse.parse_qs(parsed_next_href.query)
411 qs.update(COMMON_QUERY)
412 next_href = compat_urlparse.urlunparse(
413 parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
414
415 return {
416 '_type': 'playlist',
417 'id': playlist_id,
418 'title': playlist_title,
419 'entries': entries,
420 }
421
422
423 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
424 _VALID_URL = r'''(?x)
425 https?://
426 (?:(?:www|m)\.)?soundcloud\.com/
427 (?P<user>[^/]+)
428 (?:/
429 (?P<rsrc>tracks|sets|reposts|likes|spotlight)
430 )?
431 /?(?:[?#].*)?$
432 '''
433 IE_NAME = 'soundcloud:user'
434 _TESTS = [{
435 'url': 'https://soundcloud.com/the-akashic-chronicler',
436 'info_dict': {
437 'id': '114582580',
438 'title': 'The Akashic Chronicler (All)',
439 },
440 'playlist_mincount': 74,
441 }, {
442 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
443 'info_dict': {
444 'id': '114582580',
445 'title': 'The Akashic Chronicler (Tracks)',
446 },
447 'playlist_mincount': 37,
448 }, {
449 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
450 'info_dict': {
451 'id': '114582580',
452 'title': 'The Akashic Chronicler (Playlists)',
453 },
454 'playlist_mincount': 2,
455 }, {
456 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
457 'info_dict': {
458 'id': '114582580',
459 'title': 'The Akashic Chronicler (Reposts)',
460 },
461 'playlist_mincount': 7,
462 }, {
463 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
464 'info_dict': {
465 'id': '114582580',
466 'title': 'The Akashic Chronicler (Likes)',
467 },
468 'playlist_mincount': 321,
469 }, {
470 'url': 'https://soundcloud.com/grynpyret/spotlight',
471 'info_dict': {
472 'id': '7098329',
473 'title': 'Grynpyret (Spotlight)',
474 },
475 'playlist_mincount': 1,
476 }]
477
478 _BASE_URL_MAP = {
479 'all': '%s/profile/soundcloud:users:%%s' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
480 'tracks': '%s/users/%%s/tracks' % SoundcloudPagedPlaylistBaseIE._API_BASE,
481 'sets': '%s/users/%%s/playlists' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
482 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
483 'likes': '%s/users/%%s/likes' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
484 'spotlight': '%s/users/%%s/spotlight' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
485 }
486
487 _TITLE_MAP = {
488 'all': 'All',
489 'tracks': 'Tracks',
490 'sets': 'Playlists',
491 'reposts': 'Reposts',
492 'likes': 'Likes',
493 'spotlight': 'Spotlight',
494 }
495
496 def _real_extract(self, url):
497 mobj = re.match(self._VALID_URL, url)
498 uploader = mobj.group('user')
499
500 url = 'https://soundcloud.com/%s/' % uploader
501 resolv_url = self._resolv_url(url)
502 user = self._download_json(
503 resolv_url, uploader, 'Downloading user info')
504
505 resource = mobj.group('rsrc') or 'all'
506
507 return self._extract_playlist(
508 self._BASE_URL_MAP[resource] % user['id'], compat_str(user['id']),
509 '%s (%s)' % (user['username'], self._TITLE_MAP[resource]))
510
511
512 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
513 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
514 IE_NAME = 'soundcloud:trackstation'
515 _TESTS = [{
516 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
517 'info_dict': {
518 'id': '286017854',
519 'title': 'Track station: your-text',
520 },
521 'playlist_mincount': 47,
522 }]
523
524 def _real_extract(self, url):
525 track_name = self._match_id(url)
526
527 webpage = self._download_webpage(url, track_name)
528
529 track_id = self._search_regex(
530 r'soundcloud:track-stations:(\d+)', webpage, 'track id')
531
532 return self._extract_playlist(
533 '%s/stations/soundcloud:track-stations:%s/tracks'
534 % (self._API_V2_BASE, track_id),
535 track_id, 'Track station: %s' % track_name)
536
537
538 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
539 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
540 IE_NAME = 'soundcloud:playlist'
541 _TESTS = [{
542 'url': 'https://api.soundcloud.com/playlists/4110309',
543 'info_dict': {
544 'id': '4110309',
545 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
546 'description': 're:.*?TILT Brass - Bowery Poetry Club',
547 },
548 'playlist_count': 6,
549 }]
550
551 def _real_extract(self, url):
552 mobj = re.match(self._VALID_URL, url)
553 playlist_id = mobj.group('id')
554 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
555
556 data_dict = {
557 'client_id': self._CLIENT_ID,
558 }
559 token = mobj.group('token')
560
561 if token:
562 data_dict['secret_token'] = token
563
564 data = compat_urllib_parse_urlencode(data_dict)
565 data = self._download_json(
566 base_url + data, playlist_id, 'Downloading playlist')
567
568 entries = self._extract_track_entries(data['tracks'])
569
570 return {
571 '_type': 'playlist',
572 'id': playlist_id,
573 'title': data.get('title'),
574 'description': data.get('description'),
575 'entries': entries,
576 }
577
578
579 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
580 IE_NAME = 'soundcloud:search'
581 IE_DESC = 'Soundcloud search'
582 _MAX_RESULTS = float('inf')
583 _TESTS = [{
584 'url': 'scsearch15:post-avant jazzcore',
585 'info_dict': {
586 'title': 'post-avant jazzcore',
587 },
588 'playlist_count': 15,
589 }]
590
591 _SEARCH_KEY = 'scsearch'
592 _MAX_RESULTS_PER_PAGE = 200
593 _DEFAULT_RESULTS_PER_PAGE = 50
594 _API_V2_BASE = 'https://api-v2.soundcloud.com'
595
596 def _get_collection(self, endpoint, collection_id, **query):
597 limit = min(
598 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
599 self._MAX_RESULTS_PER_PAGE)
600 query['limit'] = limit
601 query['client_id'] = self._CLIENT_ID
602 query['linked_partitioning'] = '1'
603 query['offset'] = 0
604 data = compat_urllib_parse_urlencode(query)
605 next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
606
607 collected_results = 0
608
609 for i in itertools.count(1):
610 response = self._download_json(
611 next_url, collection_id, 'Downloading page {0}'.format(i),
612 'Unable to download API page')
613
614 collection = response.get('collection', [])
615 if not collection:
616 break
617
618 collection = list(filter(bool, collection))
619 collected_results += len(collection)
620
621 for item in collection:
622 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
623
624 if not collection or collected_results >= limit:
625 break
626
627 next_url = response.get('next_href')
628 if not next_url:
629 break
630
631 def _get_n_results(self, query, n):
632 tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
633 return self.playlist_result(tracks, playlist_title=query)