Displaying download progress (speed, eta) for file and video downloads.

This commit is contained in:
Roland 2026-03-12 17:48:35 -06:00
parent fa97b25831
commit 4579562be5
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
16 changed files with 912 additions and 101 deletions

View file

@ -5,6 +5,7 @@ import logging
import os.path
import pathlib
import re
import time
import traceback
from abc import ABC
from datetime import timedelta
@ -23,7 +24,8 @@ from wrolpi.common import logger, get_media_directory, escape_file_name, resolve
trim_file_name, cached_multiprocessing_result, get_absolute_media_path, aiohttp_post
from wrolpi.dates import now
from wrolpi.db import get_db_session
from wrolpi.downloader import Downloader, Download, DownloadResult
from wrolpi.downloader import Downloader, Download, DownloadResult, \
clear_download_progress, _parse_size, make_progress_callback
from wrolpi.errors import UnrecoverableDownloadError, BotBlockedDownloadError
from wrolpi.files.lib import glob_shared_stem, split_path_stem_and_suffix
from wrolpi.files.models import FileGroup
@ -43,6 +45,36 @@ from .video.lib import download_video_info_json
logger = logger.getChild(__name__)
YTDLP_PROGRESS_RE = re.compile(
r'\[download\]\s+'
r'([\d.]+)%\s+' # percent
r'of\s+~?\s*([\d.]+\w+)\s+' # total size (with optional ~)
r'at\s+([\d.]+\w+/s)\s+' # speed
r'ETA\s+(\S+)' # ETA
)
def parse_ytdlp_progress(line: str) -> dict | None:
"""Parse a yt-dlp progress line (with --newline) and return a dict, or None if not a progress line."""
m = YTDLP_PROGRESS_RE.search(line)
if not m:
return None
percent = float(m.group(1))
total_bytes = _parse_size(m.group(2))
speed_str = m.group(3).rstrip('/s')
speed = _parse_size(speed_str)
eta = m.group(4)
if eta == 'Unknown':
eta = None
return dict(
bytes_downloaded=int(percent / 100.0 * total_bytes),
total_bytes=total_bytes,
percent=int(percent),
speed=speed,
eta=eta,
)
VIDEO_RESOLUTION_MAP = {
'360p': [
'134+bestaudio', '230+bestaudio', 'mp4-360p', 'res:360',
@ -585,6 +617,7 @@ class VideoDownloader(Downloader, ABC):
'--convert-thumbnails', DEFAULT_POSTER_FORMAT,
'--merge-output-format', video_format,
'--no-cache-dir',
'--newline',
'--compat-options', 'no-live-chat',
# Get top 20 comments, 10 replies per parent.
'--write-comments',
@ -605,20 +638,27 @@ class VideoDownloader(Downloader, ABC):
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 effective['user_agent']:
cmd = (*cmd, '--add-headers', f'User-Agent:{effective["user_agent"]}')
on_stdout = make_progress_callback(download.id, parse_ytdlp_progress)
try:
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 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,
stdout_callback=on_stdout)
else:
# No cookies available
logger.info(f'No cookies available for video download: {url}')
cmd = (*cmd, '-o', video_path, url)
result = await self.process_runner(download, cmd, out_dir, debug=True)
else:
# No cookies available
logger.info(f'No cookies available for video download: {url}')
cmd = (*cmd, '-o', video_path, url)
result = await self.process_runner(download, cmd, out_dir, debug=True)
result = await self.process_runner(download, cmd, out_dir, debug=True,
stdout_callback=on_stdout)
finally:
clear_download_progress(download.id)
stdout = result.stdout.decode()
stderr = result.stderr.decode()

View file

@ -955,6 +955,17 @@ class Channel(ModelHelper, Base):
self.tag_id = self.tag.id if self.tag else None
return self.tag
@staticmethod
def _get_external_file_paths(session, channel_id: int, directory: pathlib.Path) -> list[pathlib.Path]:
"""Return primary_path for all Videos in this channel whose FileGroup is outside the channel directory."""
dir_str = f'{directory}/'
file_groups = session.query(FileGroup).join(Video, Video.file_group_id == FileGroup.id).filter(
Video.channel_id == channel_id,
FileGroup.directory != str(directory),
~FileGroup.directory.startswith(dir_str),
).all()
return [fg.primary_path for fg in file_groups]
@classmethod
def refresh_files(cls, id_: int, send_events: bool = True) -> str:
"""Refresh all files within this Channel's directory. Returns job_id for awaiting.
@ -962,10 +973,13 @@ class Channel(ModelHelper, Base):
The channel is marked as refreshed after the background task completes post-processing."""
# Get this Channel's info for later. Refresh may take a long time.
with get_db_session() as session:
directory = cls.find_by_id(session, id_).directory
channel = cls.find_by_id(session, id_)
directory = channel.directory
# Find files associated with this channel but outside its directory.
external_paths = cls._get_external_file_paths(session, id_, directory)
# Queue refresh immediately so caller can await the job.
job_id = file_worker.queue_refresh([directory])
job_id = file_worker.queue_refresh([directory] + external_paths)
# Background task handles post-processing after job completes.
async def _():

View file

@ -0,0 +1,198 @@
"""Tests that Channel.refresh_files() and refresh_collection() detect changes to files
that are associated with the channel but located outside the channel's directory."""
import shutil
import pytest
from modules.videos.models import Channel, Video
from wrolpi.collections import Collection
from wrolpi.collections.lib import refresh_collection
from wrolpi.collections.models import CollectionItem
from wrolpi.common import await_background_tasks
from wrolpi.conftest import await_file_worker
from wrolpi.files.models import FileGroup
@pytest.mark.asyncio
class TestChannelRefreshExternalFiles:
async def _setup_channel_with_external_video(
self, test_session, test_directory, video_file_factory, channel_factory, refresh_files):
"""Create a channel with an internal and external video, then delete the external video from disk.
Returns (channel, internal_video_id, external_video_id, external_path)."""
channel = channel_factory(name='MyChannel')
assert channel.directory.is_dir()
# Create a video inside the channel directory.
internal_path = channel.directory / 'internal_video.mp4'
video_file_factory(internal_path)
# Create a video outside the channel directory.
external_dir = test_directory / 'videos' / 'other'
external_dir.mkdir(parents=True, exist_ok=True)
external_path = external_dir / 'external_video.mp4'
video_file_factory(external_path)
# Refresh to index all files and model videos.
await refresh_files()
# Verify both videos exist.
internal_video = test_session.query(Video).join(Video.file_group).filter(
FileGroup.primary_path == internal_path,
).one()
external_video = test_session.query(Video).join(Video.file_group).filter(
FileGroup.primary_path == external_path,
).one()
# Assign the external video to the channel.
external_video.channel_id = channel.id
test_session.commit()
internal_video_id = internal_video.id
external_video_id = external_video.id
# Verify channel has 2 videos.
channel_videos = test_session.query(Video).filter_by(channel_id=channel.id).all()
assert len(channel_videos) == 2, f'Expected 2 channel videos, got {len(channel_videos)}'
# Delete ALL files for the external video by removing the directory.
shutil.rmtree(external_dir)
assert not external_path.exists()
return channel, internal_video_id, external_video_id, external_path
def _assert_external_deleted_internal_kept(self, test_session, internal_video_id, external_video_id, external_path):
"""Assert the external video was cleaned up and the internal video remains."""
test_session.expire_all()
external_fg = test_session.query(FileGroup).filter_by(primary_path=external_path).one_or_none()
assert external_fg is None, \
'External video FileGroup should have been removed after files were deleted from disk'
external_vid = test_session.query(Video).filter_by(id=external_video_id).one_or_none()
assert external_vid is None, \
'External Video record should have been removed after its files were deleted'
internal_vid = test_session.query(Video).filter_by(id=internal_video_id).one_or_none()
assert internal_vid is not None, 'Internal video should still exist'
async def test_channel_refresh_files_detects_deleted_external_video(
self, async_client, test_session, test_directory, video_file_factory, channel_factory, refresh_files):
"""Channel.refresh_files() should detect and remove an external video whose files were deleted."""
channel, internal_id, external_id, external_path = await self._setup_channel_with_external_video(
test_session, test_directory, video_file_factory, channel_factory, refresh_files)
Channel.refresh_files(channel.id)
await await_file_worker()
await await_background_tasks()
self._assert_external_deleted_internal_kept(test_session, internal_id, external_id, external_path)
async def test_refresh_collection_detects_deleted_external_video(
self, async_client, test_session, test_directory, video_file_factory, channel_factory, refresh_files):
"""refresh_collection() should detect and remove an external video whose files were deleted."""
channel, internal_id, external_id, external_path = await self._setup_channel_with_external_video(
test_session, test_directory, video_file_factory, channel_factory, refresh_files)
collection = test_session.query(Collection).filter_by(id=channel.collection_id).one()
refresh_collection(collection.id)
await await_file_worker()
self._assert_external_deleted_internal_kept(test_session, internal_id, external_id, external_path)
async def test_refresh_collection_detects_deleted_external_collection_item(
self, async_client, test_session, test_directory, video_file_factory, refresh_files):
"""refresh_collection() should detect and remove an external CollectionItem-linked FileGroup
whose files were deleted from disk."""
# Create a generic collection with a directory.
collection_dir = test_directory / 'my_collection'
collection_dir.mkdir(parents=True, exist_ok=True)
collection = Collection(name='MyCollection', directory=collection_dir, kind='simple')
test_session.add(collection)
test_session.flush()
# Create a video inside the collection directory.
internal_path = collection_dir / 'internal_video.mp4'
video_file_factory(internal_path)
# Create a video outside the collection directory.
external_dir = test_directory / 'elsewhere'
external_dir.mkdir(parents=True, exist_ok=True)
external_path = external_dir / 'external_video.mp4'
video_file_factory(external_path)
# Refresh to index all files.
await refresh_files()
internal_fg = test_session.query(FileGroup).filter_by(primary_path=internal_path).one()
external_fg = test_session.query(FileGroup).filter_by(primary_path=external_path).one()
external_fg_id = external_fg.id
# Link the external FileGroup to the collection via CollectionItem.
item = CollectionItem(collection_id=collection.id, file_group_id=external_fg.id)
test_session.add(item)
test_session.commit()
# Delete the external files.
shutil.rmtree(external_dir)
assert not external_path.exists()
# Refresh via collection.
refresh_collection(collection.id)
await await_file_worker()
test_session.expire_all()
external_fg = test_session.query(FileGroup).filter_by(id=external_fg_id).one_or_none()
assert external_fg is None, \
'External CollectionItem FileGroup should have been removed after files were deleted from disk'
internal_fg = test_session.query(FileGroup).filter_by(primary_path=internal_path).one_or_none()
assert internal_fg is not None, 'Internal FileGroup should still exist'
async def test_channel_refresh_detects_new_file_in_external_file_group(
self, async_client, test_session, test_directory, video_file_factory, channel_factory, refresh_files):
"""Channel.refresh_files() should detect a new sibling file added to an external video's FileGroup."""
channel = channel_factory(name='MyChannel')
# Create a video outside the channel directory.
external_dir = test_directory / 'videos' / 'other'
external_dir.mkdir(parents=True, exist_ok=True)
external_path = external_dir / 'external_video.mp4'
video_file_factory(external_path)
# Refresh to index the video.
await refresh_files()
external_video = test_session.query(Video).join(Video.file_group).filter(
FileGroup.primary_path == external_path,
).one()
# Assign the external video to the channel.
external_video.channel_id = channel.id
test_session.commit()
# Record the initial file count.
external_fg = external_video.file_group
initial_file_names = {f['path'] for f in external_fg.files}
assert 'external_video.mp4' in initial_file_names
# Add a subtitle file next to the video with the same stem.
subtitle_path = external_dir / 'external_video.en.vtt'
subtitle_path.write_text('WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nHello\n')
# Refresh the channel's files.
Channel.refresh_files(channel.id)
await await_file_worker()
await await_background_tasks()
test_session.expire_all()
# The FileGroup should now include the subtitle file.
external_fg = test_session.query(FileGroup).filter_by(primary_path=external_path).one()
file_names = {f['path'] for f in external_fg.files}
assert 'external_video.en.vtt' in file_names, \
f'Subtitle file should have been detected in external FileGroup, got: {file_names}'
assert 'external_video.mp4' in file_names, 'Original video file should still be present'
assert external_fg.primary_path == external_path, 'Primary path should still be the .mp4'

View file

@ -9,7 +9,8 @@ import pytest
from modules.videos.downloader import VideoDownloader, \
get_or_create_channel, channel_downloader, video_downloader, preview_filename, \
prepare_filename, convert_wrolpi_filename_format, _bot_blocked, _skip_download
prepare_filename, convert_wrolpi_filename_format, _bot_blocked, _skip_download, \
parse_ytdlp_progress
from modules.videos.lib import get_videos_downloader_config
from modules.videos.models import Channel, Video
from wrolpi.conftest import test_directory, await_switches
@ -915,3 +916,50 @@ async def test_video_download_playlist_appended_extension(test_session, test_dir
video: Video = test_session.query(Video).one()
assert video.video_path == video_path_na
def test_parse_ytdlp_progress():
"""yt-dlp progress lines are parsed correctly."""
line = '[download] 50.0% of ~ 45.67MiB at 2.34MiB/s ETA 00:19'
result = parse_ytdlp_progress(line)
assert result is not None
total = int(45.67 * 1024 ** 2)
assert result['total_bytes'] == total
assert result['percent'] == 50
assert result['bytes_downloaded'] == int(0.5 * total)
assert result['speed'] == int(2.34 * 1024 ** 2)
assert result['eta'] == '00:19'
def test_parse_ytdlp_progress_no_estimated():
"""yt-dlp progress lines without ~ estimated marker are parsed."""
line = '[download] 100% of 45.67MiB at 3.45MiB/s ETA 00:00'
result = parse_ytdlp_progress(line)
assert result is not None
assert result['percent'] == 100
assert result['total_bytes'] == int(45.67 * 1024 ** 2)
assert result['speed'] == int(3.45 * 1024 ** 2)
assert result['eta'] == '00:00'
def test_parse_ytdlp_progress_small_percent():
"""yt-dlp progress lines with small percentages are parsed."""
line = '[download] 0.1% of ~ 45.67MiB at 1.23MiB/s ETA 00:37'
result = parse_ytdlp_progress(line)
assert result is not None
assert result['percent'] == 0
assert result['eta'] == '00:37'
def test_parse_ytdlp_progress_completion_line():
"""The final yt-dlp line with 'in' instead of 'at/ETA' returns None (no speed/ETA)."""
line = '[download] 100% of 45.67MiB in 00:13'
result = parse_ytdlp_progress(line)
assert result is None
def test_parse_ytdlp_progress_not_progress_line():
"""Non-progress lines return None."""
assert parse_ytdlp_progress('[info] Downloading video 1 of 1') is None
assert parse_ytdlp_progress('') is None
assert parse_ytdlp_progress('[download] Destination: video.mp4') is None