aboutsummaryrefslogtreecommitdiffstats
path: root/hypervideo_dl/extractor/soundcloud.py
diff options
context:
space:
mode:
Diffstat (limited to 'hypervideo_dl/extractor/soundcloud.py')
-rw-r--r--hypervideo_dl/extractor/soundcloud.py370
1 files changed, 178 insertions, 192 deletions
diff --git a/hypervideo_dl/extractor/soundcloud.py b/hypervideo_dl/extractor/soundcloud.py
index 92535f7..c2344dd 100644
--- a/hypervideo_dl/extractor/soundcloud.py
+++ b/hypervideo_dl/extractor/soundcloud.py
@@ -1,6 +1,3 @@
-# coding: utf-8
-from __future__ import unicode_literals
-
import itertools
import re
import json
@@ -12,7 +9,6 @@ from .common import (
)
from ..compat import (
compat_HTTPError,
- compat_kwargs,
compat_str,
)
from ..utils import (
@@ -23,7 +19,6 @@ from ..utils import (
int_or_none,
KNOWN_EXTENSIONS,
mimetype2ext,
- remove_end,
parse_qs,
str_or_none,
try_get,
@@ -37,18 +32,13 @@ from ..utils import (
class SoundcloudEmbedIE(InfoExtractor):
_VALID_URL = r'https?://(?:w|player|p)\.soundcloud\.com/player/?.*?\burl=(?P<id>.+)'
+ _EMBED_REGEX = [r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1']
_TEST = {
# from https://www.soundi.fi/uutiset/ennakkokuuntelussa-timo-kaukolammen-station-to-station-to-station-julkaisua-juhlitaan-tanaan-g-livelabissa/
'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',
'only_matching': True,
}
- @staticmethod
- def _extract_urls(webpage):
- return [m.group('url') for m in re.finditer(
- r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
- webpage)]
-
def _real_extract(self, url):
query = parse_qs(url)
api_url = query['url'][0]
@@ -70,8 +60,23 @@ class SoundcloudBaseIE(InfoExtractor):
_access_token = None
_HEADERS = {}
+ _IMAGE_REPL_RE = r'-([0-9a-z]+)\.jpg'
+
+ _ARTWORK_MAP = {
+ 'mini': 16,
+ 'tiny': 20,
+ 'small': 32,
+ 'badge': 47,
+ 't67x67': 67,
+ 'large': 100,
+ 't300x300': 300,
+ 'crop': 400,
+ 't500x500': 500,
+ 'original': 0,
+ }
+
def _store_client_id(self, client_id):
- self._downloader.cache.store('soundcloud', 'client_id', client_id)
+ self.cache.store('soundcloud', 'client_id', client_id)
def _update_client_id(self):
webpage = self._download_webpage('https://soundcloud.com/', None)
@@ -96,7 +101,7 @@ class SoundcloudBaseIE(InfoExtractor):
query['client_id'] = self._CLIENT_ID
kwargs['query'] = query
try:
- return super()._download_json(*args, **compat_kwargs(kwargs))
+ return super()._download_json(*args, **kwargs)
except ExtractorError as e:
if isinstance(e.cause, compat_HTTPError) and e.cause.code in (401, 403):
self._store_client_id(None)
@@ -108,7 +113,7 @@ class SoundcloudBaseIE(InfoExtractor):
raise
def _initialize_pre_login(self):
- self._CLIENT_ID = self._downloader.cache.load('soundcloud', 'client_id') or 'a3e059563d7fd3372b49b37f00a00bcf'
+ self._CLIENT_ID = self.cache.load('soundcloud', 'client_id') or 'a3e059563d7fd3372b49b37f00a00bcf'
def _perform_login(self, username, password):
if username != 'oauth':
@@ -189,6 +194,157 @@ class SoundcloudBaseIE(InfoExtractor):
return out
+ def _extract_info_dict(self, info, full_title=None, secret_token=None, extract_flat=False):
+ track_id = compat_str(info['id'])
+ title = info['title']
+
+ format_urls = set()
+ formats = []
+ query = {'client_id': self._CLIENT_ID}
+ if secret_token:
+ query['secret_token'] = secret_token
+
+ if not extract_flat and info.get('downloadable') and info.get('has_downloads_left'):
+ download_url = update_url_query(
+ self._API_V2_BASE + 'tracks/' + track_id + '/download', query)
+ redirect_url = (self._download_json(download_url, track_id, fatal=False) or {}).get('redirectUri')
+ if redirect_url:
+ urlh = self._request_webpage(
+ HEADRequest(redirect_url), track_id, fatal=False)
+ if urlh:
+ format_url = urlh.geturl()
+ format_urls.add(format_url)
+ formats.append({
+ 'format_id': 'download',
+ 'ext': urlhandle_detect_ext(urlh) or 'mp3',
+ 'filesize': int_or_none(urlh.headers.get('Content-Length')),
+ 'url': format_url,
+ 'quality': 10,
+ })
+
+ def invalid_url(url):
+ return not url or url in format_urls
+
+ def add_format(f, protocol, is_preview=False):
+ mobj = re.search(r'\.(?P<abr>\d+)\.(?P<ext>[0-9a-z]{3,4})(?=[/?])', stream_url)
+ if mobj:
+ for k, v in mobj.groupdict().items():
+ if not f.get(k):
+ f[k] = v
+ format_id_list = []
+ if protocol:
+ format_id_list.append(protocol)
+ ext = f.get('ext')
+ if ext == 'aac':
+ f['abr'] = '256'
+ for k in ('ext', 'abr'):
+ v = f.get(k)
+ if v:
+ format_id_list.append(v)
+ preview = is_preview or re.search(r'/(?:preview|playlist)/0/30/', f['url'])
+ if preview:
+ format_id_list.append('preview')
+ abr = f.get('abr')
+ if abr:
+ f['abr'] = int(abr)
+ if protocol == 'hls':
+ protocol = 'm3u8' if ext == 'aac' else 'm3u8_native'
+ else:
+ protocol = 'http'
+ f.update({
+ 'format_id': '_'.join(format_id_list),
+ 'protocol': protocol,
+ 'preference': -10 if preview else None,
+ })
+ formats.append(f)
+
+ # New API
+ transcodings = try_get(
+ info, lambda x: x['media']['transcodings'], list) or []
+ for t in transcodings:
+ if not isinstance(t, dict):
+ continue
+ format_url = url_or_none(t.get('url'))
+ if not format_url:
+ continue
+ stream = None if extract_flat else self._download_json(
+ format_url, track_id, query=query, fatal=False, headers=self._HEADERS)
+ if not isinstance(stream, dict):
+ continue
+ stream_url = url_or_none(stream.get('url'))
+ if invalid_url(stream_url):
+ continue
+ format_urls.add(stream_url)
+ stream_format = t.get('format') or {}
+ protocol = stream_format.get('protocol')
+ if protocol != 'hls' and '/hls' in format_url:
+ protocol = 'hls'
+ ext = None
+ preset = str_or_none(t.get('preset'))
+ if preset:
+ ext = preset.split('_')[0]
+ if ext not in KNOWN_EXTENSIONS:
+ ext = mimetype2ext(stream_format.get('mime_type'))
+ add_format({
+ 'url': stream_url,
+ 'ext': ext,
+ }, 'http' if protocol == 'progressive' else protocol,
+ t.get('snipped') or '/preview/' in format_url)
+
+ for f in formats:
+ f['vcodec'] = 'none'
+
+ if not formats and info.get('policy') == 'BLOCK':
+ self.raise_geo_restricted(metadata_available=True)
+
+ user = info.get('user') or {}
+
+ thumbnails = []
+ artwork_url = info.get('artwork_url')
+ thumbnail = artwork_url or user.get('avatar_url')
+ if isinstance(thumbnail, compat_str):
+ if re.search(self._IMAGE_REPL_RE, thumbnail):
+ for image_id, size in self._ARTWORK_MAP.items():
+ i = {
+ 'id': image_id,
+ 'url': re.sub(self._IMAGE_REPL_RE, '-%s.jpg' % image_id, thumbnail),
+ }
+ if image_id == 'tiny' and not artwork_url:
+ size = 18
+ elif image_id == 'original':
+ i['preference'] = 10
+ if size:
+ i.update({
+ 'width': size,
+ 'height': size,
+ })
+ thumbnails.append(i)
+ else:
+ thumbnails = [{'url': thumbnail}]
+
+ def extract_count(key):
+ return int_or_none(info.get('%s_count' % key))
+
+ return {
+ 'id': track_id,
+ 'uploader': user.get('username'),
+ 'uploader_id': str_or_none(user.get('id')) or user.get('permalink'),
+ 'uploader_url': user.get('permalink_url'),
+ 'timestamp': unified_timestamp(info.get('created_at')),
+ 'title': title,
+ 'description': info.get('description'),
+ 'thumbnails': thumbnails,
+ 'duration': float_or_none(info.get('duration'), 1000),
+ 'webpage_url': info.get('permalink_url'),
+ 'license': info.get('license'),
+ 'view_count': extract_count('playback'),
+ 'like_count': extract_count('favoritings') or extract_count('likes'),
+ 'comment_count': extract_count('comment'),
+ 'repost_count': extract_count('reposts'),
+ 'genre': info.get('genre'),
+ 'formats': formats if not extract_flat else None
+ }
+
@classmethod
def _resolv_url(cls, url):
return cls._API_V2_BASE + 'resolve?url=' + url
@@ -387,173 +543,6 @@ class SoundcloudIE(SoundcloudBaseIE):
},
]
- _IMAGE_REPL_RE = r'-([0-9a-z]+)\.jpg'
-
- _ARTWORK_MAP = {
- 'mini': 16,
- 'tiny': 20,
- 'small': 32,
- 'badge': 47,
- 't67x67': 67,
- 'large': 100,
- 't300x300': 300,
- 'crop': 400,
- 't500x500': 500,
- 'original': 0,
- }
-
- def _extract_info_dict(self, info, full_title=None, secret_token=None):
- track_id = compat_str(info['id'])
- title = info['title']
-
- format_urls = set()
- formats = []
- query = {'client_id': self._CLIENT_ID}
- if secret_token:
- query['secret_token'] = secret_token
-
- if info.get('downloadable') and info.get('has_downloads_left'):
- download_url = update_url_query(
- self._API_V2_BASE + 'tracks/' + track_id + '/download', query)
- redirect_url = (self._download_json(download_url, track_id, fatal=False) or {}).get('redirectUri')
- if redirect_url:
- urlh = self._request_webpage(
- HEADRequest(redirect_url), track_id, fatal=False)
- if urlh:
- format_url = urlh.geturl()
- format_urls.add(format_url)
- formats.append({
- 'format_id': 'download',
- 'ext': urlhandle_detect_ext(urlh) or 'mp3',
- 'filesize': int_or_none(urlh.headers.get('Content-Length')),
- 'url': format_url,
- 'quality': 10,
- })
-
- def invalid_url(url):
- return not url or url in format_urls
-
- def add_format(f, protocol, is_preview=False):
- mobj = re.search(r'\.(?P<abr>\d+)\.(?P<ext>[0-9a-z]{3,4})(?=[/?])', stream_url)
- if mobj:
- for k, v in mobj.groupdict().items():
- if not f.get(k):
- f[k] = v
- format_id_list = []
- if protocol:
- format_id_list.append(protocol)
- ext = f.get('ext')
- if ext == 'aac':
- f['abr'] = '256'
- for k in ('ext', 'abr'):
- v = f.get(k)
- if v:
- format_id_list.append(v)
- preview = is_preview or re.search(r'/(?:preview|playlist)/0/30/', f['url'])
- if preview:
- format_id_list.append('preview')
- abr = f.get('abr')
- if abr:
- f['abr'] = int(abr)
- if protocol == 'hls':
- protocol = 'm3u8' if ext == 'aac' else 'm3u8_native'
- else:
- protocol = 'http'
- f.update({
- 'format_id': '_'.join(format_id_list),
- 'protocol': protocol,
- 'preference': -10 if preview else None,
- })
- formats.append(f)
-
- # New API
- transcodings = try_get(
- info, lambda x: x['media']['transcodings'], list) or []
- for t in transcodings:
- if not isinstance(t, dict):
- continue
- format_url = url_or_none(t.get('url'))
- if not format_url:
- continue
- stream = self._download_json(
- format_url, track_id, query=query, fatal=False, headers=self._HEADERS)
- if not isinstance(stream, dict):
- continue
- stream_url = url_or_none(stream.get('url'))
- if invalid_url(stream_url):
- continue
- format_urls.add(stream_url)
- stream_format = t.get('format') or {}
- protocol = stream_format.get('protocol')
- if protocol != 'hls' and '/hls' in format_url:
- protocol = 'hls'
- ext = None
- preset = str_or_none(t.get('preset'))
- if preset:
- ext = preset.split('_')[0]
- if ext not in KNOWN_EXTENSIONS:
- ext = mimetype2ext(stream_format.get('mime_type'))
- add_format({
- 'url': stream_url,
- 'ext': ext,
- }, 'http' if protocol == 'progressive' else protocol,
- t.get('snipped') or '/preview/' in format_url)
-
- for f in formats:
- f['vcodec'] = 'none'
-
- if not formats and info.get('policy') == 'BLOCK':
- self.raise_geo_restricted(metadata_available=True)
- self._sort_formats(formats)
-
- user = info.get('user') or {}
-
- thumbnails = []
- artwork_url = info.get('artwork_url')
- thumbnail = artwork_url or user.get('avatar_url')
- if isinstance(thumbnail, compat_str):
- if re.search(self._IMAGE_REPL_RE, thumbnail):
- for image_id, size in self._ARTWORK_MAP.items():
- i = {
- 'id': image_id,
- 'url': re.sub(self._IMAGE_REPL_RE, '-%s.jpg' % image_id, thumbnail),
- }
- if image_id == 'tiny' and not artwork_url:
- size = 18
- elif image_id == 'original':
- i['preference'] = 10
- if size:
- i.update({
- 'width': size,
- 'height': size,
- })
- thumbnails.append(i)
- else:
- thumbnails = [{'url': thumbnail}]
-
- def extract_count(key):
- return int_or_none(info.get('%s_count' % key))
-
- return {
- 'id': track_id,
- 'uploader': user.get('username'),
- 'uploader_id': str_or_none(user.get('id')) or user.get('permalink'),
- 'uploader_url': user.get('permalink_url'),
- 'timestamp': unified_timestamp(info.get('created_at')),
- 'title': title,
- 'description': info.get('description'),
- 'thumbnails': thumbnails,
- 'duration': float_or_none(info.get('duration'), 1000),
- 'webpage_url': info.get('permalink_url'),
- 'license': info.get('license'),
- 'view_count': extract_count('playback'),
- 'like_count': extract_count('favoritings') or extract_count('likes'),
- 'comment_count': extract_count('comment'),
- 'repost_count': extract_count('reposts'),
- 'genre': info.get('genre'),
- 'formats': formats
- }
-
def _real_extract(self, url):
mobj = self._match_valid_url(url)
@@ -670,25 +659,20 @@ class SoundcloudPagedPlaylistBaseIE(SoundcloudBaseIE):
'offset': 0,
}
- retries = self.get_param('extractor_retries', 3)
-
for i in itertools.count():
- attempt, last_error = -1, None
- while attempt < retries:
- attempt += 1
- if last_error:
- self.report_warning('%s. Retrying ...' % remove_end(last_error, '.'), playlist_id)
+ for retry in self.RetryManager():
try:
response = self._download_json(
url, playlist_id, query=query, headers=self._HEADERS,
- note='Downloading track page %s%s' % (i + 1, f' (retry #{attempt})' if attempt else ''))
+ note=f'Downloading track page {i + 1}')
break
except ExtractorError as e:
# Downloading page may result in intermittent 502 HTTP error
# See https://github.com/hypervideo/hypervideo/issues/872
- if attempt >= retries or not isinstance(e.cause, compat_HTTPError) or e.cause.code != 502:
+ if not isinstance(e.cause, compat_HTTPError) or e.cause.code != 502:
raise
- last_error = str(e.cause or e.msg)
+ retry.error = e
+ continue
def resolve_entry(*candidates):
for cand in candidates:
@@ -906,6 +890,7 @@ class SoundcloudSearchIE(SoundcloudBaseIE, SearchInfoExtractor):
_TESTS = [{
'url': 'scsearch15:post-avant jazzcore',
'info_dict': {
+ 'id': 'post-avant jazzcore',
'title': 'post-avant jazzcore',
},
'playlist_count': 15,
@@ -932,7 +917,8 @@ class SoundcloudSearchIE(SoundcloudBaseIE, SearchInfoExtractor):
for item in response.get('collection') or []:
if item:
- yield self.url_result(item['uri'], SoundcloudIE.ie_key())
+ yield self.url_result(
+ item['uri'], SoundcloudIE.ie_key(), **self._extract_info_dict(item, extract_flat=True))
next_url = response.get('next_href')
if not next_url: