2 from __future__
import unicode_literals
11 from ..compat
import (
33 class SoundcloudEmbedIE(InfoExtractor
):
34 _VALID_URL
= r
'https?://(?:w|player|p)\.soundcloud\.com/player/?.*?\burl=(?P<id>.+)'
36 # from https://www.soundi.fi/uutiset/ennakkokuuntelussa-timo-kaukolammen-station-to-station-to-station-julkaisua-juhlitaan-tanaan-g-livelabissa/
37 'url': 'https://w.soundcloud.com/player/?visual=true&url=https%3A%2F%2Fapi.soundcloud.com%2Fplaylists%2F922213810&show_artwork=true&maxwidth=640&maxheight=960&dnt=1&secret_token=s-ziYey',
38 'only_matching': True,
42 def _extract_urls(webpage
):
43 return [m
.group('url') for m
in re
.finditer(
44 r
'<iframe[^>]+src=(["\'])(?P
<url
>(?
:https?
://)?
(?
:w\
.)?soundcloud\
.com
/player
.+?
)\
1',
47 def _real_extract(self, url):
48 query = compat_urlparse.parse_qs(
49 compat_urlparse.urlparse(url).query)
50 api_url = query['url
'][0]
51 secret_token = query.get('secret_token
')
53 api_url = update_url_query(api_url, {'secret_token
': secret_token[0]})
54 return self.url_result(api_url)
57 class SoundcloudIE(InfoExtractor):
58 """Information extractor for soundcloud.com
59 To access the media, the uid of the song and a stream token
60 must be extracted from the page source and the script must make
61 a request to media.soundcloud.com/crossdomain.xml. Then
62 the media can be grabbed by requesting from an url composed
63 of the stream token and uid
66 _VALID_URL = r'''(?x)^(?:https?://)?
67 (?:(?:(?:www\.|m\.)?soundcloud\.com/
69 (?P<uploader>[\w\d-]+)/
70 (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
72 (?P<token>[^?]+?)?(?:[?].*)?$)
73 |(?:api(?:-v2)?\.soundcloud\.com/tracks/(?P<track_id>\d+)
74 (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
77 IE_NAME = 'soundcloud
'
80 'url
': 'http
://soundcloud
.com
/ethmusic
/lostin
-powers
-she
-so
-heavy
',
81 'md5
': 'ebef0a451b909710ed1d7787dddbf0d7
',
85 'title
': 'Lostin Powers
- She so
Heavy (SneakPreview
) Adrian Ackers Blueprint
1',
86 '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
',
87 'uploader
': 'E
.T
. ExTerrestrial Music
',
88 'uploader_id
': '1571244',
89 'timestamp
': 1349920598,
90 'upload_date
': '20121011',
92 'license
': 'all
-rights
-reserved
',
99 # not streamable song, preview
101 'url
': 'https
://soundcloud
.com
/the
-concept
-band
/goldrushed
-mastered?
in=the
-concept
-band
/sets
/the
-royal
-concept
-ep
',
105 'title
': 'Goldrushed
',
106 'description
': 'From Stockholm Sweden
\r\nPovel
/ Magnus
/ Filip
/ David
\r\nwww
.theroyalconcept
.com
',
107 'uploader
': 'The Royal Concept
',
108 'uploader_id
': '9615865',
109 'timestamp
': 1337635207,
110 'upload_date
': '20120521',
112 'license
': 'all
-rights
-reserved
',
115 'comment_count
': int,
120 'skip_download
': True,
125 'url
': 'https
://soundcloud
.com
/jaimemf
/youtube
-dl
-test
-video
-a
-y
-baw
/s
-8Pjrp
',
126 'md5
': 'aa0dd32bfea9b0c5ef4f02aacd080604
',
130 'title
': 'Youtube
- Dl Test Video
\'\' Ä↭
',
131 'description
': 'test chars
: \"\'/\\ä↭
',
132 'uploader
': 'jaimeMF
',
133 'uploader_id
': '69767071',
134 'timestamp
': 1386604920,
135 'upload_date
': '20131209',
137 'license
': 'all
-rights
-reserved
',
140 'comment_count
': int,
144 # private link (alt format)
146 'url
': 'https
://api
.soundcloud
.com
/tracks
/123998367?secret_token
=s
-8Pjrp
',
147 'md5
': 'aa0dd32bfea9b0c5ef4f02aacd080604
',
151 'title
': 'Youtube
- Dl Test Video
\'\' Ä↭
',
152 'description
': 'test chars
: \"\'/\\ä↭
',
153 'uploader
': 'jaimeMF
',
154 'uploader_id
': '69767071',
155 'timestamp
': 1386604920,
156 'upload_date
': '20131209',
158 'license
': 'all
-rights
-reserved
',
161 'comment_count
': int,
167 'url
': 'https
://soundcloud
.com
/oddsamples
/bus
-brakes
',
168 'md5
': '7624f2351f8a3b2e7cd51522496e7631
',
172 'title
': 'Bus Brakes
',
173 'description
': 'md5
:0053ca6396e8d2fd7b7e1595ef12ab66
',
174 'uploader
': 'oddsamples
',
175 'uploader_id
': '73680509',
176 'timestamp
': 1389232924,
177 'upload_date
': '20140109',
179 'license
': 'cc
-by
-sa
',
182 'comment_count
': int,
186 # private link, downloadable format
188 'url
': 'https
://soundcloud
.com
/oriuplift
/uponly
-238-no
-talking
-wav
/s
-AyZUd
',
189 'md5
': '64a60b16e617d41d0bef032b7f55441e
',
193 'title
': 'Uplifting Only
238 [No Talking
] (incl
. Alex Feed Guestmix
) (Aug
31, 2017) [wav
]',
194 'description
': 'md5
:fa20ee0fca76a3d6df8c7e57f3715366
',
195 'uploader
': 'Ori Uplift Music
',
196 'uploader_id
': '12563093',
197 'timestamp
': 1504206263,
198 'upload_date
': '20170831',
199 'duration
': 7449.096,
200 'license
': 'all
-rights
-reserved
',
203 'comment_count
': int,
207 # no album art, use avatar pic for thumbnail
209 'url
': 'https
://soundcloud
.com
/garyvee
/sideways
-prod
-mad
-real
',
210 'md5
': '59c7872bc44e5d99b7211891664760c2
',
214 'title
': 'Sideways (Prod
. Mad Real
)',
215 'description
': 'md5
:d41d8cd98f00b204e9800998ecf8427e
',
216 'uploader
': 'garyvee
',
217 'uploader_id
': '2366352',
218 'timestamp
': 1488152409,
219 'upload_date
': '20170226',
221 'thumbnail
': r're
:https?
://.*\
.jpg
',
222 'license
': 'all
-rights
-reserved
',
225 'comment_count
': int,
229 'skip_download
': True,
232 # not available via api.soundcloud.com/i1/tracks/id/streams
234 'url
': 'https
://soundcloud
.com
/giovannisarani
/mezzo
-valzer
',
235 'md5
': 'e22aecd2bc88e0e4e432d7dcc0a1abf7
',
239 'title
': 'Mezzo Valzer
',
240 'description
': 'md5
:4138d582f81866a530317bae316e8b61
',
241 'uploader
': 'Giovanni Sarani
',
242 'uploader_id
': '3352531',
243 'timestamp
': 1551394171,
244 'upload_date
': '20190228',
246 'thumbnail
': r're
:https?
://.*\
.jpg
',
247 'license
': 'all
-rights
-reserved
',
250 'comment_count
': int,
253 'expected_warnings
': ['Unable to download JSON metadata
'],
257 _API_BASE = 'https
://api
.soundcloud
.com
/'
258 _API_V2_BASE = 'https
://api
-v2
.soundcloud
.com
/'
259 _BASE_URL = 'https
://soundcloud
.com
/'
260 _IMAGE_REPL_RE = r'-([0-9a
-z
]+)\
.jpg
'
275 def _store_client_id(self, client_id):
276 self._downloader.cache.store('soundcloud
', 'client_id
', client_id)
278 def _update_client_id(self):
279 webpage = self._download_webpage('https
://soundcloud
.com
/', None)
280 for src in reversed(re.findall(r'<script
[^
>]+src
="([^"]+)"', webpage)):
281 script = self._download_webpage(src, None, fatal=False)
283 client_id = self._search_regex(
284 r'client_id\s*:\s*"([0-9a
-zA
-Z
]{32}
)"',
285 script, 'client id', default=None)
287 self._CLIENT_ID = client_id
288 self._store_client_id(client_id)
290 raise ExtractorError('Unable to extract client id')
292 def _download_json(self, *args, **kwargs):
293 non_fatal = kwargs.get('fatal') is False
296 query = kwargs.get('query', {}).copy()
298 query['client_id'] = self._CLIENT_ID
299 kwargs['query'] = query
301 return super(SoundcloudIE, self)._download_json(*args, **compat_kwargs(kwargs))
302 except ExtractorError as e:
303 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
304 self._store_client_id(None)
305 self._update_client_id()
308 self._downloader.report_warning(error_to_compat_str(e))
312 def _real_initialize(self):
313 self._CLIENT_ID = self._downloader.cache.load('soundcloud', 'client_id') or 'YUKXoArFcqrlQn9tfNHvvyfnDISj04zk'
316 def _resolv_url(cls, url):
317 return SoundcloudIE._API_V2_BASE + 'resolve?url=' + url
319 def _extract_info_dict(self, info, full_title=None, secret_token=None, version=2):
320 track_id = compat_str(info['id'])
321 title = info['title']
322 track_base_url = self._API_BASE + 'tracks/%s' % track_id
326 query = {'client_id': self._CLIENT_ID}
328 query['secret_token'] = secret_token
330 if info.get('downloadable') and info.get('has_downloads_left'):
331 format_url = update_url_query(
332 info.get('download_url') or track_base_url + '/download', query)
333 format_urls.add(format_url)
335 v1_info = self._download_json(
336 track_base_url, track_id, query=query, fatal=False) or {}
340 'format_id': 'download',
341 'ext': v1_info.get('original_format') or 'mp3',
342 'filesize': int_or_none(v1_info.get('original_content_size')),
347 def invalid_url(url):
348 return not url or url in format_urls
350 def add_format(f, protocol, is_preview=False):
351 mobj = re.search(r'\.(?P<abr>\d+)\.(?P<ext>[0-9a-z]{3,4})(?=[/?])', stream_url)
353 for k, v in mobj.groupdict().items():
358 format_id_list.append(protocol)
359 for k in ('ext', 'abr'):
362 format_id_list.append(v)
363 preview = is_preview or re.search(r'/(?:preview|playlist)/0/30/', f['url'])
365 format_id_list.append('preview')
370 'format_id': '_'.join(format_id_list),
371 'protocol': 'm3u8_native' if protocol == 'hls' else 'http',
372 'preference': -10 if preview else None,
377 transcodings = try_get(
378 info, lambda x: x['media']['transcodings'], list) or []
379 for t in transcodings:
380 if not isinstance(t, dict):
382 format_url = url_or_none(t.get('url'))
385 stream = self._download_json(
386 format_url, track_id, query=query, fatal=False)
387 if not isinstance(stream, dict):
389 stream_url = url_or_none(stream.get('url'))
390 if invalid_url(stream_url):
392 format_urls.add(stream_url)
393 stream_format = t.get('format') or {}
394 protocol = stream_format.get('protocol')
395 if protocol != 'hls' and '/hls' in format_url:
398 preset = str_or_none(t.get('preset'))
400 ext = preset.split('_')[0]
401 if ext not in KNOWN_EXTENSIONS:
402 ext = mimetype2ext(stream_format.get('mime_type'))
406 }, 'http' if protocol == 'progressive' else protocol,
407 t.get('snipped') or '/preview/' in format_url)
410 # Old API, does not work for some tracks (e.g.
411 # https://soundcloud.com/giovannisarani/mezzo-valzer)
412 # and might serve preview URLs (e.g.
413 # http://www.soundcloud.com/snbrn/ele)
414 format_dict = self._download_json(
415 track_base_url + '/streams', track_id,
416 'Downloading track url', query=query, fatal=False) or {}
418 for key, stream_url in format_dict.items():
419 if invalid_url(stream_url):
421 format_urls.add(stream_url)
422 mobj = re.search(r'(http|hls)_([^_]+)_(\d+)_url', key)
424 protocol, ext, abr = mobj.groups()
432 # We fallback to the stream_url in the original info, this
433 # cannot be always used, sometimes it can give an HTTP 404 error
434 urlh = self._request_webpage(
435 HEADRequest(info.get('stream_url') or track_base_url + '/stream'),
436 track_id, query=query, fatal=False)
438 stream_url = urlh.geturl()
439 if not invalid_url(stream_url):
440 add_format({'url': stream_url}, 'http')
445 self._sort_formats(formats)
447 user = info.get('user') or {}
450 artwork_url = info.get('artwork_url')
451 thumbnail = artwork_url or user.get('avatar_url')
452 if isinstance(thumbnail, compat_str):
453 if re.search(self._IMAGE_REPL_RE, thumbnail):
454 for image_id, size in self._ARTWORK_MAP.items():
457 'url': re.sub(self._IMAGE_REPL_RE, '-%s.jpg' % image_id, thumbnail),
459 if image_id == 'tiny' and not artwork_url:
461 elif image_id == 'original':
470 thumbnails = [{'url': thumbnail}]
472 def extract_count(key):
473 return int_or_none(info.get('%s_count' % key))
477 'uploader': user.get('username'),
478 'uploader_id': str_or_none(user.get('id')) or user.get('permalink'),
479 'uploader_url': user.get('permalink_url'),
480 'timestamp': unified_timestamp(info.get('created_at')),
482 'description': info.get('description'),
483 'thumbnails': thumbnails,
484 'duration': float_or_none(info.get('duration'), 1000),
485 'webpage_url': info.get('permalink_url'),
486 'license': info.get('license'),
487 'view_count': extract_count('playback'),
488 'like_count': extract_count('favoritings') or extract_count('likes'),
489 'comment_count': extract_count('comment'),
490 'repost_count': extract_count('reposts'),
491 'genre': info.get('genre'),
495 def _real_extract(self, url):
496 mobj = re.match(self._VALID_URL, url)
498 track_id = mobj.group('track_id')
502 info_json_url = self._API_V2_BASE + 'tracks/' + track_id
503 full_title = track_id
504 token = mobj.group('secret_token')
506 query['secret_token'] = token
508 full_title = resolve_title = '%s/%s' % mobj.group('uploader', 'title')
509 token = mobj.group('token')
511 resolve_title += '/%s' % token
512 info_json_url = self._resolv_url(self._BASE_URL + resolve_title)
515 info = self._download_json(
516 info_json_url, full_title, 'Downloading info JSON', query=query, fatal=False)
518 info = self._download_json(
519 info_json_url.replace(self._API_V2_BASE, self._API_BASE),
520 full_title, 'Downloading info JSON', query=query)
523 return self._extract_info_dict(info, full_title, token, version)
526 class SoundcloudPlaylistBaseIE(SoundcloudIE):
527 def _extract_track_entries(self, tracks, token=None):
530 track_id = str_or_none(track.get('id'))
531 url = track.get('permalink_url')
535 url = self._API_V2_BASE + 'tracks/' + track_id
537 url += '?secret_token=' + token
538 entries.append(self.url_result(
539 url, SoundcloudIE.ie_key(), track_id))
543 class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
544 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
545 IE_NAME = 'soundcloud:set'
547 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
550 'title': 'The Royal Concept EP',
552 'playlist_mincount': 5,
554 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
555 'only_matching': True,
558 def _real_extract(self, url):
559 mobj = re.match(self._VALID_URL, url)
561 full_title = '%s/sets/%s' % mobj.group('uploader', 'slug_title')
562 token = mobj.group('token')
564 full_title += '/' + token
566 info = self._download_json(self._resolv_url(
567 self._BASE_URL + full_title), full_title)
570 msgs = (compat_str(err['error_message']) for err in info['errors'])
571 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
573 entries = self._extract_track_entries(info['tracks'], token)
575 return self.playlist_result(
576 entries, str_or_none(info.get('id')), info.get('title'))
579 class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
580 def _extract_playlist(self, base_url, playlist_id, playlist_title):
583 'linked_partitioning': '1',
586 query = COMMON_QUERY.copy()
592 for i in itertools.count():
593 response = self._download_json(
594 next_href, playlist_id,
595 'Downloading track page %s' % (i + 1), query=query)
597 collection = response['collection']
599 if not isinstance(collection, list):
602 # Empty collection may be returned, in this case we proceed
603 # straight to next_href
605 def resolve_entry(candidates):
606 for cand in candidates:
607 if not isinstance(cand, dict):
609 permalink_url = url_or_none(cand.get('permalink_url'))
610 if not permalink_url:
612 return self.url_result(
614 SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
615 str_or_none(cand.get('id')), cand.get('title'))
618 entry = resolve_entry((e, e.get('track'), e.get('playlist')))
620 entries.append(entry)
622 next_href = response.get('next_href')
626 next_href = response['next_href']
627 parsed_next_href = compat_urlparse.urlparse(next_href)
628 query = compat_urlparse.parse_qs(parsed_next_href.query)
629 query.update(COMMON_QUERY)
634 'title': playlist_title,
639 class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
640 _VALID_URL = r'''(?x)
642 (?:(?:www|m)\.)?soundcloud\.com/
645 (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
649 IE_NAME = 'soundcloud:user'
651 'url': 'https://soundcloud.com/soft-cell-official',
654 'title': 'Soft Cell (All)',
656 'playlist_mincount': 28,
658 'url': 'https://soundcloud.com/soft-cell-official/tracks',
661 'title': 'Soft Cell (Tracks)',
663 'playlist_mincount': 27,
665 'url': 'https://soundcloud.com/soft-cell-official/albums',
668 'title': 'Soft Cell (Albums)',
670 'playlist_mincount': 1,
672 'url': 'https://soundcloud.com/jcv246/sets',
675 'title': 'Jordi / cv (Sets)',
677 'playlist_mincount': 2,
679 'url': 'https://soundcloud.com/jcv246/reposts',
682 'title': 'Jordi / cv (Reposts)',
684 'playlist_mincount': 6,
686 'url': 'https://soundcloud.com/clalberg/likes',
689 'title': 'clalberg (Likes)',
691 'playlist_mincount': 5,
693 'url': 'https://soundcloud.com/grynpyret/spotlight',
696 'title': 'Grynpyret (Spotlight)',
698 'playlist_mincount': 1,
702 'all': 'stream/users/%s',
703 'tracks': 'users/%s/tracks',
704 'albums': 'users/%s/albums',
705 'sets': 'users/%s/playlists',
706 'reposts': 'stream/users/%s/reposts',
707 'likes': 'users/%s/likes',
708 'spotlight': 'users/%s/spotlight',
711 def _real_extract(self, url):
712 mobj = re.match(self._VALID_URL, url)
713 uploader = mobj.group('user')
715 user = self._download_json(
716 self._resolv_url(self._BASE_URL + uploader),
717 uploader, 'Downloading user info')
719 resource = mobj.group('rsrc') or 'all'
721 return self._extract_playlist(
722 self._API_V2_BASE + self._BASE_URL_MAP[resource] % user['id'],
723 str_or_none(user.get('id')),
724 '%s (%s)' % (user['username'], resource.capitalize()))
727 class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
728 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
729 IE_NAME = 'soundcloud:trackstation'
731 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
734 'title': 'Track station: your text',
736 'playlist_mincount': 47,
739 def _real_extract(self, url):
740 track_name = self._match_id(url)
742 track = self._download_json(self._resolv_url(url), track_name)
743 track_id = self._search_regex(
744 r'soundcloud:track-stations:(\d+)', track['id'], 'track id')
746 return self._extract_playlist(
747 self._API_V2_BASE + 'stations/%s/tracks' % track['id'],
748 track_id, 'Track station: %s' % track['title'])
751 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
752 _VALID_URL = r'https?://api(?:-v2)?\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
753 IE_NAME = 'soundcloud:playlist'
755 'url': 'https://api.soundcloud.com/playlists/4110309',
758 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
759 'description': 're:.*?TILT Brass - Bowery Poetry Club',
764 def _real_extract(self, url):
765 mobj = re.match(self._VALID_URL, url)
766 playlist_id = mobj.group('id')
769 token = mobj.group('token')
771 query['secret_token'] = token
773 data = self._download_json(
774 self._API_V2_BASE + 'playlists/' + playlist_id,
775 playlist_id, 'Downloading playlist', query=query)
777 entries = self._extract_track_entries(data['tracks'], token)
779 return self.playlist_result(
780 entries, playlist_id, data.get('title'), data.get('description'))
783 class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
784 IE_NAME = 'soundcloud:search'
785 IE_DESC = 'Soundcloud search'
786 _MAX_RESULTS = float('inf')
788 'url': 'scsearch15:post-avant jazzcore',
790 'title': 'post-avant jazzcore',
792 'playlist_count': 15,
795 _SEARCH_KEY = 'scsearch'
796 _MAX_RESULTS_PER_PAGE = 200
797 _DEFAULT_RESULTS_PER_PAGE = 50
799 def _get_collection(self, endpoint, collection_id, **query):
801 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
802 self._MAX_RESULTS_PER_PAGE)
805 'linked_partitioning': 1,
808 next_url = update_url_query(self._API_V2_BASE + endpoint, query)
810 collected_results = 0
812 for i in itertools.count(1):
813 response = self._download_json(
814 next_url, collection_id, 'Downloading page {0}'.format(i),
815 'Unable to download API page')
817 collection = response.get('collection', [])
821 collection = list(filter(bool, collection))
822 collected_results += len(collection)
824 for item in collection:
825 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
827 if not collection or collected_results >= limit:
830 next_url = response.get('next_href')
834 def _get_n_results(self, query, n):
835 tracks = self._get_collection('search/tracks', query, limit=n, q=query)
836 return self.playlist_result(tracks, playlist_title=query)