mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-29 03:16:22 -05:00
Unifying video download settings so that global/channel/rss/video
download settings have inheritance. Allowing more granular control of potentially failed downloads.
This commit is contained in:
parent
6be6fe6e19
commit
0ffbc05e91
13 changed files with 683 additions and 71 deletions
|
|
@ -50,6 +50,14 @@ async def channel_tag_info(request: Request, body: schema.ChannelTagInfoRequest)
|
|||
return json_response(ret)
|
||||
|
||||
|
||||
@content_bp.get('/download-defaults')
|
||||
@openapi.description('Get flattened global inheritable video download settings for form pre-fill.')
|
||||
async def get_download_defaults(_: Request):
|
||||
config = lib.get_videos_downloader_config()
|
||||
defaults = lib._extract_global_inheritable(config)
|
||||
return json_response(defaults)
|
||||
|
||||
|
||||
@content_bp.post('/file_format')
|
||||
@openapi.definition(
|
||||
description='Preview the video file format',
|
||||
|
|
|
|||
|
|
@ -34,8 +34,8 @@ from .common import get_no_channel_directory, update_view_counts_and_censored, \
|
|||
ffmpeg_video_complete
|
||||
from .errors import UnknownChannel
|
||||
from .cookies import cookies_unlocked, cookies_for_download
|
||||
from .lib import get_videos_downloader_config, YDL, ydl_logger, format_videos_destination, get_yt_dlp_http_headers, \
|
||||
get_yt_dlp_sleep_opts
|
||||
from .lib import get_videos_downloader_config, get_effective_video_settings, CHANNEL_INHERITABLE_SETTINGS, YDL, \
|
||||
ydl_logger, format_videos_destination, get_yt_dlp_http_headers, get_yt_dlp_sleep_opts
|
||||
from .models import Video, Channel
|
||||
from .normalize_video_url import normalize_video_url
|
||||
from .schema import ChannelPostRequest
|
||||
|
|
@ -364,10 +364,10 @@ class ChannelDownloader(Downloader, ABC):
|
|||
settings['destination'] = str(destination) # Need str for JSON conversion
|
||||
if download.tag_names:
|
||||
settings['tag_names'] = download.tag_names
|
||||
if video_resolutions := download_settings.get('video_resolutions'):
|
||||
settings['video_resolutions'] = video_resolutions
|
||||
if video_format := download_settings.get('video_format'):
|
||||
settings['video_format'] = video_format
|
||||
# Pass all channel-level inheritable settings to child video downloads.
|
||||
for key in CHANNEL_INHERITABLE_SETTINGS:
|
||||
if key in download_settings:
|
||||
settings[key] = download_settings[key]
|
||||
|
||||
is_a_playlist = self.is_a_playlist(info)
|
||||
try:
|
||||
|
|
@ -554,16 +554,16 @@ class VideoDownloader(Downloader, ABC):
|
|||
logger.debug(f'Downloading {url} with {tag_names=}')
|
||||
|
||||
config = get_videos_downloader_config()
|
||||
effective = get_effective_video_settings(settings)
|
||||
|
||||
logs = None # noqa
|
||||
try:
|
||||
# Use user-provided/channel-provided first, or fallback to defaults from config.
|
||||
video_resolutions = settings.get('video_resolutions') or config.video_resolutions
|
||||
video_resolutions = effective['video_resolutions']
|
||||
# yt-dlp expects a string like so: 299+140,298+140,bestvideo*+bestaudio/best
|
||||
video_resolutions = ','.join(j for i in video_resolutions for j in VIDEO_RESOLUTION_MAP[i])
|
||||
video_resolutions_str = ','.join(j for i in video_resolutions for j in VIDEO_RESOLUTION_MAP[i])
|
||||
|
||||
video_format = settings.get('video_format') or config.merge_output_format
|
||||
video_path, entry = self.prepare_filename(url, out_dir, video_resolutions, video_format)
|
||||
video_format = effective['video_format']
|
||||
video_path, entry = self.prepare_filename(url, out_dir, video_resolutions_str, video_format)
|
||||
|
||||
if settings.get('download_metadata_only'):
|
||||
# User has requested refresh of video metadata, skip the rest of the video downloader.
|
||||
|
|
@ -571,13 +571,12 @@ class VideoDownloader(Downloader, ABC):
|
|||
|
||||
cmd = (
|
||||
str(YT_DLP_BIN),
|
||||
'-f', video_resolutions,
|
||||
'-f', video_resolutions_str,
|
||||
'--match-filter', '!is_live', # Do not attempt to download Live videos.
|
||||
'--sub-format', DEFAULT_CAPTION_FORMAT,
|
||||
'--convert-subs', DEFAULT_CAPTION_FORMAT,
|
||||
'--convert-thumbnails', DEFAULT_POSTER_FORMAT,
|
||||
'--merge-output-format', video_format,
|
||||
# '--remux-video', video_format,
|
||||
'--no-cache-dir',
|
||||
'--compat-options', 'no-live-chat',
|
||||
# Get top 20 comments, 10 replies per parent.
|
||||
|
|
@ -586,26 +585,26 @@ class VideoDownloader(Downloader, ABC):
|
|||
# Use experimental feature to merge files.
|
||||
'--ppa', 'Merger+ffmpeg_o1:-strict -2',
|
||||
)
|
||||
if config.continue_dl:
|
||||
if effective['continue_dl']:
|
||||
cmd = (*cmd, '--continue')
|
||||
if config.writesubtitles:
|
||||
if effective['writesubtitles']:
|
||||
cmd = (*cmd, '--write-subs', '--write-auto-subs')
|
||||
if config.writethumbnail:
|
||||
if effective['writethumbnail']:
|
||||
cmd = (*cmd, '--write-thumbnail')
|
||||
if config.writeinfojson:
|
||||
if effective['writeinfojson']:
|
||||
cmd = (*cmd, '--write-info-json')
|
||||
if config.yt_dlp_extra_args:
|
||||
cmd = (*cmd, *config.yt_dlp_extra_args.split(' '))
|
||||
if config.sleep_requests > 0:
|
||||
cmd = (*cmd, '--sleep-requests', str(config.sleep_requests))
|
||||
if effective['yt_dlp_extra_args']:
|
||||
cmd = (*cmd, *effective['yt_dlp_extra_args'].split(' '))
|
||||
if effective['sleep_requests'] > 0:
|
||||
cmd = (*cmd, '--sleep-requests', str(effective['sleep_requests']))
|
||||
|
||||
if cookies_unlocked():
|
||||
# Use encrypted cookies file
|
||||
logger.info(f'Using encrypted cookies for video download: {url}')
|
||||
with cookies_for_download() as cookies_path:
|
||||
cmd = (*cmd, '--cookies', str(cookies_path))
|
||||
if config.user_agent:
|
||||
cmd = (*cmd, '--add-headers', f'User-Agent:{config.user_agent}')
|
||||
if effective['user_agent']:
|
||||
cmd = (*cmd, '--add-headers', f'User-Agent:{effective["user_agent"]}')
|
||||
cmd = (*cmd, '-o', video_path, url)
|
||||
result = await self.process_runner(download, cmd, out_dir, debug=True)
|
||||
else:
|
||||
|
|
|
|||
|
|
@ -562,9 +562,14 @@ class VideoDownloaderConfig(ConfigFile):
|
|||
return self._config['yt_dlp_options']['nooverwrites']
|
||||
|
||||
@property
|
||||
def merge_output_format(self) -> bool:
|
||||
def merge_output_format(self) -> str:
|
||||
return self._config['yt_dlp_options']['merge_output_format']
|
||||
|
||||
@property
|
||||
def video_format(self) -> str:
|
||||
"""Alias for merge_output_format, matching the name used in Download.settings."""
|
||||
return self.merge_output_format
|
||||
|
||||
@property
|
||||
def quiet(self) -> bool:
|
||||
return self._config['yt_dlp_options']['quiet']
|
||||
|
|
@ -652,6 +657,51 @@ def set_test_downloader_config(enabled: bool):
|
|||
TEST_VIDEOS_DOWNLOADER_CONFIG = VideoDownloaderConfig() if enabled else None
|
||||
|
||||
|
||||
# Names of settings that can be overridden at channel/RSS or video level.
|
||||
# Actual default values come from VideoDownloaderConfig.
|
||||
INHERITABLE_VIDEO_SETTINGS = {
|
||||
'video_resolutions', 'video_format', 'writesubtitles', 'writeautomaticsub',
|
||||
'writethumbnail', 'writeinfojson', 'yt_dlp_extra_args', 'sleep_requests',
|
||||
'user_agent', 'continue_dl', 'nooverwrites',
|
||||
}
|
||||
|
||||
# Subset of inheritable settings allowed at channel/RSS level.
|
||||
# continue_dl and nooverwrites are global+video only.
|
||||
CHANNEL_INHERITABLE_SETTINGS = INHERITABLE_VIDEO_SETTINGS - {'continue_dl', 'nooverwrites'}
|
||||
|
||||
|
||||
def _extract_global_inheritable(config: VideoDownloaderConfig) -> dict:
|
||||
"""Read current global config values for all inheritable settings, flattened."""
|
||||
return {
|
||||
'video_resolutions': config.video_resolutions,
|
||||
'video_format': config.merge_output_format,
|
||||
'writesubtitles': config.writesubtitles,
|
||||
'writeautomaticsub': config.writeautomaticsub,
|
||||
'writethumbnail': config.writethumbnail,
|
||||
'writeinfojson': config.writeinfojson,
|
||||
'yt_dlp_extra_args': config.yt_dlp_extra_args,
|
||||
'sleep_requests': config.sleep_requests,
|
||||
'user_agent': config.user_agent,
|
||||
'continue_dl': config.continue_dl,
|
||||
'nooverwrites': config.nooverwrites,
|
||||
}
|
||||
|
||||
|
||||
def get_effective_video_settings(download_settings: dict = None) -> dict:
|
||||
"""Merge global defaults with download-level overrides.
|
||||
|
||||
At download time: effective = {**global, **download_settings}
|
||||
Only inheritable keys present in download_settings override the global value.
|
||||
"""
|
||||
config = get_videos_downloader_config()
|
||||
effective = _extract_global_inheritable(config)
|
||||
if download_settings:
|
||||
for key in INHERITABLE_VIDEO_SETTINGS:
|
||||
if key in download_settings:
|
||||
effective[key] = download_settings[key]
|
||||
return effective
|
||||
|
||||
|
||||
def get_yt_dlp_http_headers() -> dict:
|
||||
"""Get HTTP headers for yt-dlp, including user-agent if configured.
|
||||
|
||||
|
|
|
|||
|
|
@ -695,3 +695,129 @@ async def test_channel_downloader_sets_collection_id(test_session, channel_facto
|
|||
test_session.refresh(download)
|
||||
assert download.collection_id == channel.collection_id, \
|
||||
'ChannelDownloader should link download to channel collection'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_passes_all_inheritable_settings_to_video(test_session, channel_factory,
|
||||
mock_video_extract_info,
|
||||
video_download_manager, await_switches):
|
||||
"""ChannelDownloader passes all CHANNEL_INHERITABLE_SETTINGS to child video downloads."""
|
||||
from modules.videos.lib import CHANNEL_INHERITABLE_SETTINGS
|
||||
|
||||
channel = channel_factory(url='https://example.com/channel', source_id='UCtest456')
|
||||
|
||||
channel_settings = {
|
||||
'video_resolutions': ['720p'],
|
||||
'video_format': 'mkv',
|
||||
'writesubtitles': False,
|
||||
'sleep_requests': 3.0,
|
||||
'user_agent': 'TestBot/1.0',
|
||||
}
|
||||
|
||||
download = Download(
|
||||
url='https://example.com/channel',
|
||||
downloader=channel_downloader.name,
|
||||
frequency=99,
|
||||
settings=channel_settings,
|
||||
)
|
||||
test_session.add(download)
|
||||
test_session.commit()
|
||||
|
||||
mock_info = {
|
||||
'id': 'UCtest456',
|
||||
'channel_id': 'UCtest456',
|
||||
'uploader': channel.name,
|
||||
'entries': [{'id': 'vid1', 'url': 'https://youtube.com/watch?v=vid1', 'title': 'Video 1'}],
|
||||
'webpage_url_basename': 'videos',
|
||||
}
|
||||
mock_video_extract_info.return_value = mock_info
|
||||
|
||||
with mock.patch('modules.videos.downloader.VideoDownloader.do_download') as mock_video_do_download, \
|
||||
mock.patch.object(Channel, 'refresh_files', return_value='test-job-id'), \
|
||||
mock.patch('modules.videos.downloader.file_worker.wait_for_job', new_callable=mock.AsyncMock):
|
||||
mock_video_do_download.return_value = DownloadResult(success=True)
|
||||
result = await channel_downloader.do_download(download)
|
||||
|
||||
# Verify all channel-level inheritable settings are passed through
|
||||
for key in ('video_resolutions', 'video_format', 'writesubtitles', 'sleep_requests', 'user_agent'):
|
||||
assert key in result.settings, f'{key} missing from DownloadResult.settings'
|
||||
assert result.settings[key] == channel_settings[key], \
|
||||
f'{key}: expected {channel_settings[key]}, got {result.settings[key]}'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_does_not_pass_continue_dl_nooverwrites(test_session, channel_factory,
|
||||
mock_video_extract_info,
|
||||
video_download_manager, await_switches):
|
||||
"""continue_dl and nooverwrites should NOT be passed from channel to video."""
|
||||
channel = channel_factory(url='https://example.com/channel', source_id='UCtest789')
|
||||
|
||||
channel_settings = {
|
||||
'continue_dl': False,
|
||||
'nooverwrites': False,
|
||||
'video_format': 'mkv',
|
||||
}
|
||||
|
||||
download = Download(
|
||||
url='https://example.com/channel',
|
||||
downloader=channel_downloader.name,
|
||||
frequency=99,
|
||||
settings=channel_settings,
|
||||
)
|
||||
test_session.add(download)
|
||||
test_session.commit()
|
||||
|
||||
mock_info = {
|
||||
'id': 'UCtest789',
|
||||
'channel_id': 'UCtest789',
|
||||
'uploader': channel.name,
|
||||
'entries': [{'id': 'vid2', 'url': 'https://youtube.com/watch?v=vid2', 'title': 'Video 2'}],
|
||||
'webpage_url_basename': 'videos',
|
||||
}
|
||||
mock_video_extract_info.return_value = mock_info
|
||||
|
||||
with mock.patch('modules.videos.downloader.VideoDownloader.do_download') as mock_video_do_download, \
|
||||
mock.patch.object(Channel, 'refresh_files', return_value='test-job-id'), \
|
||||
mock.patch('modules.videos.downloader.file_worker.wait_for_job', new_callable=mock.AsyncMock):
|
||||
mock_video_do_download.return_value = DownloadResult(success=True)
|
||||
result = await channel_downloader.do_download(download)
|
||||
|
||||
assert 'continue_dl' not in result.settings, 'continue_dl should not be passed to child video downloads'
|
||||
assert 'nooverwrites' not in result.settings, 'nooverwrites should not be passed to child video downloads'
|
||||
assert result.settings['video_format'] == 'mkv', 'video_format should be passed through'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_download_uses_effective_settings(test_session, test_directory, mock_video_extract_info,
|
||||
video_download_manager, mock_video_process_runner,
|
||||
image_file, simple_channel, test_videos_downloader_config):
|
||||
"""VideoDownloader uses merged effective settings from global + download overrides."""
|
||||
simple_channel.source_id = example_video_json['channel_id']
|
||||
simple_channel.directory = test_directory / 'videos/channel name'
|
||||
simple_channel.directory.mkdir(parents=True)
|
||||
|
||||
video_path = simple_channel.directory / 'a video.mp4'
|
||||
shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', video_path)
|
||||
image_file.rename(video_path.with_suffix('.jpg'))
|
||||
|
||||
url = 'https://www.youtube.com/watch?v=31jPEBiAC3c'
|
||||
|
||||
# Download with writesubtitles=False override (global default is True)
|
||||
settings = {'writesubtitles': False, 'sleep_requests': 5.0}
|
||||
|
||||
with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename:
|
||||
mock_video_extract_info.return_value = example_video_json
|
||||
mock_prepare_filename.return_value = (video_path, {'id': 'foo'})
|
||||
|
||||
video_download_manager.create_download(test_session, url, video_downloader.name, settings=settings)
|
||||
await video_download_manager.wait_for_all_downloads()
|
||||
|
||||
mock_video_process_runner.assert_called_once()
|
||||
download, cmd, out_dir = mock_video_process_runner.call_args[0]
|
||||
|
||||
# writesubtitles=False means no --write-subs in command
|
||||
assert '--write-subs' not in cmd, 'writesubtitles=False should prevent --write-subs'
|
||||
# sleep_requests=5.0 should appear
|
||||
assert '--sleep-requests' in cmd, 'sleep_requests override should appear in command'
|
||||
sleep_idx = cmd.index('--sleep-requests')
|
||||
assert cmd[sleep_idx + 1] == '5.0', f'Expected sleep_requests=5.0, got {cmd[sleep_idx + 1]}'
|
||||
|
|
|
|||
|
|
@ -439,3 +439,65 @@ def test_format_video_filename_uses_channel_name_over_info_json(test_session, vi
|
|||
# Should use WROLPi channel name, NOT the YouTube uploader
|
||||
assert 'My Custom Channel' in result
|
||||
assert 'Learning Self Reliance' not in result
|
||||
|
||||
|
||||
def test_extract_global_inheritable(test_directory, test_videos_downloader_config):
|
||||
"""Verify _extract_global_inheritable returns all expected keys with correct mapping."""
|
||||
config = lib.get_videos_downloader_config()
|
||||
result = lib._extract_global_inheritable(config)
|
||||
assert set(result.keys()) == lib.INHERITABLE_VIDEO_SETTINGS
|
||||
# merge_output_format maps to video_format
|
||||
assert result['video_format'] == config.merge_output_format
|
||||
assert result['video_resolutions'] == config.video_resolutions
|
||||
assert result['writesubtitles'] == config.writesubtitles
|
||||
assert result['continue_dl'] == config.continue_dl
|
||||
|
||||
|
||||
def test_get_effective_video_settings_no_overrides(test_directory, test_videos_downloader_config):
|
||||
"""With no download settings, effective settings equal global defaults."""
|
||||
config = lib.get_videos_downloader_config()
|
||||
effective = lib.get_effective_video_settings()
|
||||
assert effective['video_resolutions'] == config.video_resolutions
|
||||
assert effective['video_format'] == config.merge_output_format
|
||||
assert effective['writesubtitles'] == config.writesubtitles
|
||||
|
||||
|
||||
def test_get_effective_video_settings_partial_override(test_directory, test_videos_downloader_config):
|
||||
"""Download settings override only the keys they specify."""
|
||||
config = lib.get_videos_downloader_config()
|
||||
overrides = {'writesubtitles': False, 'sleep_requests': 2.0}
|
||||
effective = lib.get_effective_video_settings(overrides)
|
||||
assert effective['writesubtitles'] is False
|
||||
assert effective['sleep_requests'] == 2.0
|
||||
# Everything else stays at global default
|
||||
assert effective['video_resolutions'] == config.video_resolutions
|
||||
assert effective['writethumbnail'] == config.writethumbnail
|
||||
|
||||
|
||||
def test_get_effective_video_settings_global_change_propagates(test_directory, test_videos_downloader_config):
|
||||
"""Changing global config propagates to downloads without overrides."""
|
||||
config = lib.get_videos_downloader_config()
|
||||
# Change global
|
||||
config.update({**config._config, 'sleep_requests': 5.0})
|
||||
# Download with no override should pick up new global
|
||||
effective = lib.get_effective_video_settings({})
|
||||
assert effective['sleep_requests'] == 5.0
|
||||
# Download with override should keep its value
|
||||
effective = lib.get_effective_video_settings({'sleep_requests': 1.0})
|
||||
assert effective['sleep_requests'] == 1.0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_download_defaults_endpoint(async_client, test_directory, test_videos_downloader_config):
|
||||
"""GET /api/videos/download-defaults returns flattened global settings."""
|
||||
request, response = await async_client.get('/api/videos/download-defaults')
|
||||
assert response.status == HTTPStatus.OK
|
||||
data = response.json
|
||||
assert 'video_resolutions' in data
|
||||
assert 'video_format' in data
|
||||
assert 'writesubtitles' in data
|
||||
assert 'continue_dl' in data
|
||||
assert 'nooverwrites' in data
|
||||
# Should NOT contain global-only settings
|
||||
assert 'file_name_format' not in data
|
||||
assert 'quiet' not in data
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue