FileGroups in Collections can be reorganized in the Collection's directory.
Some checks failed
Controller Tests / controller-tests (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled

* Batch reorganization is supported for both Domain and Channel Collections.
* Batch reorganization happens when any Collection does not match the respective file format. For example, a Channel Collection file format that does not match the `yt_dlp_options.file_name_format` will show `needs_reorganization`.
* Individual Collections can always be reorganized. The reorganization is a little more aggressive. Useful for when some files may have been missed in the batch reorganization.
This commit is contained in:
Roland 2026-01-23 19:51:02 -07:00
parent 208ac4fac7
commit 6891ebeb62
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
49 changed files with 6614 additions and 181 deletions

View file

@ -7,7 +7,7 @@ from typing import List, Tuple, Iterable
from sqlalchemy import not_
from sqlalchemy.orm import Session
from wrolpi.cmd import SINGLE_FILE_BIN, CHROMIUM
from wrolpi.cmd import SINGLE_FILE_BIN, CHROMIUM, FIREFOX
from wrolpi.collections import Collection
from wrolpi.common import logger, register_modeler, register_refresh_cleanup, limit_concurrent, split_lines_by_length, \
slow_logger, get_title_from_html, TRACE_LEVEL
@ -86,11 +86,29 @@ class ArchiveDownloader(Downloader, ABC):
async def do_singlefile(self, download: Download) -> bytes:
"""Create a Singlefile from the archive's URL."""
# Get browser settings from config
config = lib.get_archive_downloader_config()
# Determine browser executable
browser_executable = config.browser_executable
if browser_executable:
# Use configured browser path
browser = browser_executable
else:
# Auto-detect: prefer Chromium, fallback to Firefox
browser = CHROMIUM or FIREFOX
if not browser:
raise RuntimeError('No browser found. Install Chromium or Firefox, or configure browser_executable.')
# Get browser args and user agent from config
browser_args = config.browser_args or '["--no-sandbox"]'
user_agent = config.user_agent or DOWNLOAD_USER_AGENT
cmd = ('/usr/bin/nice', '-n15', # Nice above map importing, but very low priority.
str(SINGLE_FILE_BIN),
'--browser-executable-path', CHROMIUM,
'--browser-args', '["--no-sandbox"]',
'--user-agent', DOWNLOAD_USER_AGENT,
'--browser-executable-path', str(browser),
'--browser-args', browser_args,
'--user-agent', user_agent,
'--dump-content',
'--load-deferred-images-dispatch-scroll-event',
download.url,
@ -233,17 +251,7 @@ def model_archive(session: Session, file_group: FileGroup) -> Archive:
file_group.title = file_group.a_text = title or archive.file_group.title
file_group.d_text = contents
# Store paths as filenames only (relative to directory), resolved via file_group.resolve_path()
file_group.data = {
'id': archive.id,
'domain': archive.domain,
'readability_json_path': archive.readability_json_path.name if archive.readability_json_path else None,
'readability_path': archive.readability_path.name if archive.readability_path else None,
'readability_txt_path': archive.readability_txt_path.name if archive.readability_txt_path else None,
'screenshot_path': archive.screenshot_path.name if archive.screenshot_path else None,
'singlefile_path': archive.singlefile_path.name if archive.singlefile_path else None,
'info_json_path': archive.info_json_path.name if archive.info_json_path else None,
}
archive.rebuild_data()
return archive
except Exception as e:

View file

@ -7,12 +7,14 @@ from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from wrolpi.api_utils import json_response, api_app
from wrolpi.cmd import get_installed_browsers
from wrolpi.common import logger, wrol_mode_check, api_param_limiter, TRACE_LEVEL
from wrolpi.db import get_db_session
from wrolpi.errors import ValidationError
from wrolpi.events import Events
from wrolpi.schema import JSONErrorResponse
from wrolpi.switches import register_switch_handler, ActivateSwitchMethod
from wrolpi.vars import DOCKERIZED
from . import lib, schema
NAME = 'archive'
@ -90,6 +92,28 @@ async def post_file_format(_: Request, body: schema.ArchiveFileFormatRequest):
), status=HTTPStatus.BAD_REQUEST)
@archive_bp.get('/browsers')
@openapi.definition(
summary='Get list of installed browsers that can be used for archiving.',
description='Returns browsers installed on the system. Only available on native deployments (not Docker).',
)
async def get_browsers(_: Request):
"""Get list of installed browsers for SingleFile."""
if DOCKERIZED:
# Browser configuration is not available in Docker
return json_response(dict(
browsers=[],
available=False,
message='Browser configuration is not available in Docker deployments.',
))
browsers = get_installed_browsers()
return json_response(dict(
browsers=browsers,
available=True,
))
@archive_bp.get('/upload')
@openapi.definition(
summary='A message to confirm to the user that they have the correct upload URL.'

View file

@ -22,7 +22,7 @@ from wrolpi.cmd import READABILITY_BIN, run_command
from wrolpi.collections import Collection
from wrolpi.common import get_media_directory, get_relative_to_media_directory, logger, extract_domain, \
escape_file_name, aiohttp_post, format_html_string, split_lines_by_length, get_html_soup, get_title_from_html, \
get_wrolpi_config, html_screenshot, ConfigFile
get_wrolpi_config, html_screenshot, ConfigFile, trim_file_name
from wrolpi.dates import now, Seconds
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.errors import UnknownArchive, InvalidOrderBy, InvalidDatetime
@ -218,12 +218,26 @@ class ArchiveDownloaderConfigValidator:
"""Validator for archives_downloader.yaml config."""
file_name_format: str
version: int = 0
# Browser settings (only used on native deployments, not Docker)
browser_executable: str = None # None means auto-detect, or absolute path
browser_args: str = '["--no-sandbox"]' # JSON array of browser arguments
user_agent: str = None # None means use system default
def __post_init__(self):
# Validate file_name_format ends with .%(ext)s (like video format)
if not self.file_name_format.endswith('.%(ext)s'):
raise ValueError('file_name_format must end with .%(ext)s')
# Validate browser_args is valid JSON array
if self.browser_args:
import json
try:
args = json.loads(self.browser_args)
if not isinstance(args, list):
raise ValueError('browser_args must be a JSON array')
except json.JSONDecodeError as e:
raise ValueError(f'browser_args must be valid JSON: {e}')
class ArchiveDownloaderConfig(ConfigFile):
"""
@ -235,6 +249,9 @@ class ArchiveDownloaderConfig(ConfigFile):
Format:
version: 0
file_name_format: '%(download_date)s_%(title)s.%(ext)s'
browser_executable: null # null for auto-detect, or absolute path
browser_args: '["--no-sandbox"]' # JSON array of browser arguments
user_agent: null # null for system default
Variables available in file_name_format:
- %(title)s - Page title (extracted from HTML)
@ -248,18 +265,41 @@ class ArchiveDownloaderConfig(ConfigFile):
Subdirectories can be included in the format, e.g.:
'%(download_year)s/%(download_datetime)s_%(title)s.%(ext)s'
Browser settings (only used on native deployments, not Docker):
- browser_executable: Path to browser or null for auto-detect
- browser_args: JSON array of arguments passed to browser
- user_agent: Custom user agent string or null for default
"""
file_name = 'archives_downloader.yaml'
validator = ArchiveDownloaderConfigValidator
default_config = dict(
version=0,
file_name_format='%(download_datetime)s_%(title)s.%(ext)s',
browser_executable=None,
browser_args='["--no-sandbox"]',
user_agent=None,
)
@property
def file_name_format(self) -> str:
return self._config['file_name_format']
@property
def browser_executable(self) -> Optional[str]:
"""Get the configured browser executable path, or None for auto-detect."""
return self._config.get('browser_executable')
@property
def browser_args(self) -> str:
"""Get the browser arguments as a JSON string."""
return self._config.get('browser_args', '["--no-sandbox"]')
@property
def user_agent(self) -> Optional[str]:
"""Get the custom user agent, or None for system default."""
return self._config.get('user_agent')
def import_config(self, file: pathlib.Path = None, send_events=False):
super().import_config(file, send_events)
self.successful_import = True
@ -314,11 +354,20 @@ def format_archive_filename(
)
try:
return template % variables
result = template % variables
# Trim the filename portion if it's too long (may include subdirectory paths)
if '/' in result:
# Has subdirectories - only trim the filename part
parts = result.rsplit('/', 1)
subdir = parts[0]
filename = trim_file_name(parts[1])
return f'{subdir}/{filename}'
else:
return trim_file_name(result)
except KeyError as e:
logger.error(f'Invalid variable in archive file_name_format: {e}')
# Fallback to default format
return f'{archive_strftime(download_date)}_{escape_file_name(title) if title else "untitled"}.html'
return trim_file_name(f'{archive_strftime(download_date)}_{escape_file_name(title) if title else "untitled"}.html')
def preview_archive_filename(file_name_format: str) -> str:
@ -356,6 +405,69 @@ def preview_archive_filename(file_name_format: str) -> str:
raise RuntimeError(f'Invalid format: {e}')
def format_archive_filename_from_archive(
archive: Archive,
file_name_format: str = None,
) -> str:
"""Single source of truth for archive filenames when reorganizing.
Formats an archive filename using the configured file_name_format template.
Used by collection reorganization to compute new file paths.
Args:
archive: Archive model with metadata
file_name_format: Optional override, defaults to config value
Returns:
Formatted filename (may include subdirectory path like "2025/My Article.html")
"""
config = get_archive_downloader_config()
template = file_name_format or config.file_name_format
file_group = archive.file_group
# Get download date from file_group
download_date = file_group.download_datetime or file_group.published_datetime or now()
# Get title
title = file_group.title or 'untitled'
# Get domain from URL
domain = ''
if file_group.url:
try:
domain = extract_domain(file_group.url)
except Exception:
pass
variables = dict(
title=escape_file_name(title) if title else 'untitled',
domain=domain,
download_datetime=archive_strftime(download_date),
download_date=download_date.strftime('%Y-%m-%d'),
download_year=str(download_date.year),
download_month=f'{download_date.month:02d}',
download_day=f'{download_date.day:02d}',
ext='html',
)
try:
result = template % variables
# Trim the filename portion if it's too long (may include subdirectory paths)
if '/' in result:
# Has subdirectories - only trim the filename part
parts = result.rsplit('/', 1)
subdir = parts[0]
filename = trim_file_name(parts[1])
return f'{subdir}/{filename}'
else:
return trim_file_name(result)
except KeyError as e:
logger.error(f'Invalid variable in archive file_name_format: {e}')
# Fallback to default format
return trim_file_name(f'{archive_strftime(download_date)}_{escape_file_name(title) if title else "untitled"}.html')
@dataclass
class ArchiveFiles:
"""Every Archive will have some of these files."""
@ -416,17 +528,18 @@ def get_new_archive_files(url: str, title: Optional[str], destination: pathlib.P
full_path.parent.mkdir(parents=True, exist_ok=True)
singlefile_path = full_path
stem = full_path.stem
readability_path = full_path.parent / f'{stem}.readability.html'
readability_txt_path = full_path.parent / f'{stem}.readability.txt'
readability_json_path = full_path.parent / f'{stem}.readability.json'
screenshot_path = full_path.parent / f'{stem}.png'
parent_dir = full_path.parent
readability_path = trim_file_name(parent_dir / f'{stem}.readability.html')
readability_txt_path = trim_file_name(parent_dir / f'{stem}.readability.txt')
readability_json_path = trim_file_name(parent_dir / f'{stem}.readability.json')
screenshot_path = trim_file_name(parent_dir / f'{stem}.png')
else:
singlefile_path = directory / formatted_filename
stem = singlefile_path.stem
readability_path = directory / f'{stem}.readability.html'
readability_txt_path = directory / f'{stem}.readability.txt'
readability_json_path = directory / f'{stem}.readability.json'
screenshot_path = directory / f'{stem}.png'
readability_path = trim_file_name(directory / f'{stem}.readability.html')
readability_txt_path = trim_file_name(directory / f'{stem}.readability.txt')
readability_json_path = trim_file_name(directory / f'{stem}.readability.json')
screenshot_path = trim_file_name(directory / f'{stem}.png')
paths = (singlefile_path, readability_path, readability_txt_path, readability_json_path, screenshot_path)
@ -592,6 +705,15 @@ async def model_archive_result(url: str, singlefile: str, readability: dict, scr
archive.file_group.download_datetime = now()
archive.url = url
archive.collection = get_or_create_domain_collection(session, url)
# Update collection's file_format to track the format used for this file
config = get_archive_downloader_config()
if archive.collection and config.file_name_format:
if not archive.collection.file_format:
# Set initial file_format on collection
archive.collection.file_format = config.file_name_format
save_domains_config.activate_switch()
archive.flush()
return archive

View file

@ -351,6 +351,23 @@ class Archive(Base, ModelHelper):
if metadata.modified_datetime:
self.file_group.published_modified_datetime = metadata.modified_datetime
def rebuild_data(self):
"""Rebuild the data field with current file paths.
Called during validate() to ensure data field reflects actual filenames
after reorganization or other file operations.
"""
self.file_group.data = {
'id': self.id,
'domain': self.domain,
'readability_json_path': self.readability_json_path.name if self.readability_json_path else None,
'readability_path': self.readability_path.name if self.readability_path else None,
'readability_txt_path': self.readability_txt_path.name if self.readability_txt_path else None,
'screenshot_path': self.screenshot_path.name if self.screenshot_path else None,
'singlefile_path': self.singlefile_path.name if self.singlefile_path else None,
'info_json_path': self.info_json_path.name if self.info_json_path else None,
}
def validate(self):
"""Fill in any missing data about this Archive from its files."""
try:
@ -359,6 +376,7 @@ class Archive(Base, ModelHelper):
self.apply_domain()
self.apply_singlefile_title()
self.apply_metadata()
self.rebuild_data()
except Exception as e:
logger.warning(f'Unable to validate {self}', exc_info=e)
if PYTEST:

View file

@ -342,18 +342,9 @@ async def test_archive_generate_screenshot(test_session, async_client, archive_f
assert original_screenshot_path is not None, 'Archive should have a screenshot'
assert original_screenshot_path.is_file(), 'Screenshot file should exist'
# Simulate the bug: archive has screenshot file but data['screenshot_path'] is not set
# (This could happen if the archive was created before set_screenshot was implemented)
if archive.file_group.data and 'screenshot_path' in archive.file_group.data:
data = dict(archive.file_group.data)
del data['screenshot_path']
archive.file_group.data = data
test_session.commit()
test_session.expire_all()
archive = test_session.query(Archive).filter_by(id=archive.id).one()
# Verify data was cleared but file still exists
assert 'screenshot_path' not in (archive.file_group.data or {}), 'screenshot_path should not be in data yet'
assert archive.screenshot_path is not None, 'But screenshot file should still exist'
# Note: Previously this test simulated a bug where data['screenshot_path'] could be missing
# while the file existed. This scenario is now auto-fixed by Archive.validate() which calls
# rebuild_data(), so the simulation is no longer necessary.
request, response = await async_client.post(f'/api/archive/{archive.id}/generate_screenshot')
assert response.status_code == HTTPStatus.OK
@ -364,11 +355,11 @@ async def test_archive_generate_screenshot(test_session, async_client, archive_f
assert archive.screenshot_path == original_screenshot_path, 'Screenshot path should be unchanged'
assert archive.screenshot_path.is_file(), 'Screenshot file should still exist'
assert archive.screenshot_file is not None, 'Screenshot file should still be tracked'
# IMPORTANT: Also verify FileGroup.data was updated (this catches the bug where only files was updated)
# IMPORTANT: Also verify FileGroup.data has screenshot_path (always synced via rebuild_data)
assert 'screenshot_path' in archive.file_group.data, \
'screenshot_path should be in FileGroup.data after ensuring tracking'
assert str(archive.file_group.data['screenshot_path']) == str(original_screenshot_path), \
'screenshot_path in data should match the file path'
'screenshot_path should be in FileGroup.data'
assert archive.file_group.data['screenshot_path'] == original_screenshot_path.name, \
'screenshot_path in data should be filename only'
# Test error case: Archive has no singlefile
archive_no_singlefile = archive_factory('example.com', 'https://example.com/no-singlefile', screenshot=False)
@ -428,3 +419,28 @@ async def test_archive_file_format_preview(async_client):
request, response = await async_client.post('/api/archive/file_format', content=json.dumps(data))
assert response.status_code == HTTPStatus.BAD_REQUEST
assert 'error' in response.json
@pytest.mark.asyncio
async def test_archive_browsers_endpoint(async_client):
"""Test the browsers endpoint returns installed browsers."""
# During tests, DOCKERIZED is False, so we should get the available=True response
request, response = await async_client.get('/api/archive/browsers')
assert response.status_code == HTTPStatus.OK
assert 'browsers' in response.json
assert 'available' in response.json
# available should be True in non-Docker environment
assert response.json['available'] is True
# browsers is a list
assert isinstance(response.json['browsers'], list)
@pytest.mark.asyncio
async def test_archive_browsers_endpoint_dockerized(async_client):
"""Test the browsers endpoint returns not available when dockerized."""
with patch('modules.archive.api.DOCKERIZED', True):
request, response = await async_client.get('/api/archive/browsers')
assert response.status_code == HTTPStatus.OK
assert response.json['browsers'] == []
assert response.json['available'] is False
assert 'message' in response.json

View file

@ -365,14 +365,17 @@ async def test_get_title_from_html(test_directory, test_session, fake_now, async
@skip_circleci
def test_get_new_archive_files_length(test_directory, fake_now):
"""Archive titles are truncated to fit file system length limit. (255-character limit for most file systems)"""
"""Archive titles are truncated to fit file system BYTE limit (200 bytes - see MAXIMUM_FILE_BYTES)."""
from wrolpi.common import MAXIMUM_FILE_BYTES
fake_now(datetime(2001, 1, 1))
archive_files = get_new_archive_files('https://example.com', 'a' * 500)
assert len(str(archive_files.singlefile.name)) == 225
assert len(str(archive_files.readability.name)) == 237
assert len(str(archive_files.readability_txt.name)) == 236
assert len(str(archive_files.readability_json.name)) == 237
assert len(str(archive_files.screenshot.name)) == 224
# All filenames should be <= MAXIMUM_FILE_BYTES (bytes, not characters)
assert len(str(archive_files.singlefile.name).encode('utf-8')) <= MAXIMUM_FILE_BYTES
assert len(str(archive_files.readability.name).encode('utf-8')) <= MAXIMUM_FILE_BYTES
assert len(str(archive_files.readability_txt.name).encode('utf-8')) <= MAXIMUM_FILE_BYTES
assert len(str(archive_files.readability_json.name).encode('utf-8')) <= MAXIMUM_FILE_BYTES
assert len(str(archive_files.screenshot.name).encode('utf-8')) <= MAXIMUM_FILE_BYTES
@skip_circleci
@ -1289,6 +1292,26 @@ def test_archive_downloader_config_validation():
with pytest.raises(ValueError, match='must end with'):
ArchiveDownloaderConfigValidator(file_name_format='%(download_date)s_%(title)s')
# Valid browser_args (JSON array)
ArchiveDownloaderConfigValidator(
file_name_format='%(title)s.%(ext)s',
browser_args='["--no-sandbox", "--headless"]'
)
# Invalid browser_args (not valid JSON)
with pytest.raises(ValueError, match='must be valid JSON'):
ArchiveDownloaderConfigValidator(
file_name_format='%(title)s.%(ext)s',
browser_args='not valid json'
)
# Invalid browser_args (not an array)
with pytest.raises(ValueError, match='must be a JSON array'):
ArchiveDownloaderConfigValidator(
file_name_format='%(title)s.%(ext)s',
browser_args='{"key": "value"}'
)
def test_format_archive_filename_default(test_directory, fake_now):
"""format_archive_filename uses default format."""

View file

@ -128,3 +128,53 @@ async def test_set_screenshot(async_client, test_session, archive_factory, image
# Verify no screenshot was set
assert archive_no_screenshot.screenshot_path is None
@pytest.mark.asyncio
async def test_archive_validate_rebuilds_data_after_filename_change(async_client, test_session, test_directory,
archive_factory):
"""Archive.validate() should rebuild data field when filenames change.
This tests the bug where reorganization updates files[] but not data{}.
The data field contains cached path names that must stay in sync.
The bug scenario: files are renamed during reorganization (e.g., fixing separator
from '___' to '_'), files[] is updated but data{} is not. The UI then uses
stale data.singlefile_path and gets 404 errors.
"""
# Create an archive using the factory
archive = archive_factory(domain='test.com', url='https://test.com/article')
test_session.commit()
# Verify initial data field has singlefile_path
assert archive.file_group.data is not None
original_singlefile = archive.file_group.data.get('singlefile_path')
assert original_singlefile is not None
# Simulate what reorganization does: update files[] but not data{}
# (This mimics _bulk_update_file_groups_reorganize behavior)
# Use a realistic rename: change the title part of the filename
# Original: '2000-01-01-07-00-01_NA.html' -> '2000-01-01-07-00-01_New-Title.html'
new_filename = original_singlefile.replace('_NA.html', '_New-Title.html')
old_files = archive.file_group.files
new_files = []
for f in old_files:
new_f = dict(f)
if f['path'].endswith('.html') and not f['path'].endswith('.readability.html'):
new_f['path'] = new_filename
new_files.append(new_f)
archive.file_group.files = new_files
archive.file_group.primary_path = archive.file_group.directory / new_filename
# Rename the actual file on disk to match the new filename
old_path = archive.file_group.directory / original_singlefile
new_path = archive.file_group.directory / new_filename
old_path.rename(new_path)
# data field still has OLD filename (this is the bug)
assert archive.file_group.data['singlefile_path'] == original_singlefile
# After validate(), data field should have NEW filename
archive.validate()
assert archive.file_group.data['singlefile_path'] == new_filename

View file

@ -260,6 +260,9 @@ async def test_channel_post_directory(test_session, async_client, test_directory
async def test_channel_by_id(test_session, async_client, simple_channel, simple_video):
request, response = await async_client.get(f'/api/videos/channels/{simple_channel.id}')
assert response.status_code == HTTPStatus.OK
channel = response.json['channel']
# needs_reorganization should be included for UI to display reorganization status
assert 'needs_reorganization' in channel
@pytest.mark.asyncio

View file

@ -139,7 +139,10 @@ def convert_wrolpi_filename_format(filename_format: str) -> str:
def preview_filename(filename_format: str) -> str:
"""Return an example video file name formatted using the provided filename format.
"""Return an example video file name using simple string formatting.
This is a lightweight implementation that doesn't require YoutubeDL instantiation,
which is expensive (~1500 extractors loaded, regexes compiled).
@raise RuntimeError: If the format is invalid.
"""
@ -149,21 +152,31 @@ def preview_filename(filename_format: str) -> str:
# Convert WROLPi-specific variables to yt-dlp syntax
converted_format = convert_wrolpi_filename_format(filename_format)
options = get_videos_downloader_config().yt_dlp_options
options['outtmpl'] = converted_format
ydl = YoutubeDL(copy.deepcopy(options))
entry = dict(
sample_date = now()
variables = dict(
uploader='WROLPi',
timestamp=int(now().timestamp()),
upload_date=now().strftime('%Y%m%d'),
channel='WROLPi',
upload_date=sample_date.strftime('%Y%m%d'),
id='Qz-FuenRylQ',
title='The title of the video',
ext='mp4',
description='A description of the video',
timestamp=int(sample_date.timestamp()),
)
filename = prepare_filename(entry, ydl=ydl).lstrip('/')
return filename
# Handle yt-dlp's date extraction syntax %(upload_date>%Y)s and %(upload_date>%m)s
# Replace these with their values before standard Python % formatting
def replace_date_format(match):
date_format = match.group(1)
return sample_date.strftime(date_format)
converted_format = re.sub(r'%\(upload_date>([^)]+)\)s', replace_date_format, converted_format)
try:
filename = converted_format % variables
return filename.lstrip('/')
except KeyError as e:
raise RuntimeError(f'Invalid variable: {e}')
@cached_multiprocessing_result
@ -545,6 +558,17 @@ class VideoDownloader(Downloader, ABC):
video_id, video_info_json_path = video.id, video.info_json_path
if video_info_json_path and (new_info_json := video.clean_info_json()):
video.replace_info_json(new_info_json, clean=False)
# Update channel's collection's file_format to track the format used
if channel_id:
from modules.videos.models import Channel
from modules.videos.lib import save_channels_config
channel_obj = session.query(Channel).get(channel_id)
if channel_obj and channel_obj.collection and not channel_obj.collection.file_format:
video_config = get_videos_downloader_config()
channel_obj.collection.file_format = video_config.file_name_format
save_channels_config.activate_switch()
session.commit()
with get_db_session(commit=True) as session:

View file

@ -16,7 +16,7 @@ from modules.videos.models import Video
from wrolpi import dates, flags
from wrolpi.captions import extract_captions
from wrolpi.common import ConfigFile, extract_domain, logger, \
escape_file_name, get_media_directory, background_task, Base, get_wrolpi_config
escape_file_name, get_media_directory, background_task, Base, get_wrolpi_config, trim_file_name
from wrolpi.dates import Seconds, from_timestamp
from wrolpi.db import get_db_curs, get_db_session
from wrolpi.downloader import Download, download_manager
@ -948,3 +948,85 @@ def browser_profile_to_yt_dlp_arg(profile: pathlib.Path) -> str:
"""Takes a Path and returns a string that can be used as a yt-dlp `--cookies-from-browser` argument."""
*_, browser, profile = str(profile).split('/')
return f'{browser}:{profile}'
def format_video_filename(
video: Video,
file_name_format: str = None,
) -> str:
"""Single source of truth for video filenames.
Formats a video filename using the configured file_name_format template.
Used by both the video downloader (initial download) and collection reorganization.
Args:
video: Video model with metadata (upload_date, uploader, title, source_id)
file_name_format: Optional override, defaults to config value
Returns:
Formatted filename (may include subdirectory path like "2025/01/video.mp4")
Example:
With format '%(upload_year)s/%(upload_month)s/%(uploader)s_%(upload_date)s_%(id)s_%(title)s.%(ext)s':
Returns '2025/01/WROLPi_20250115_abc123_My Video Title.mp4'
"""
from modules.videos.downloader import convert_wrolpi_filename_format
config = get_videos_downloader_config()
template = file_name_format or config.file_name_format
# Get metadata from video
file_group = video.file_group
info_json = video.get_info_json() or {}
# Extract upload date info
upload_date = file_group.published_datetime
if not upload_date and info_json.get('upload_date'):
upload_date = dates.strpdate(info_json['upload_date'])
# Build variables dict matching yt-dlp's expected variables
# Use info_json if available, fall back to derived values
uploader = info_json.get('uploader') or info_json.get('channel') or ''
title = file_group.title or info_json.get('title') or info_json.get('fulltitle') or 'untitled'
source_id = video.source_id or info_json.get('id') or ''
# Get video file extension
video_path = video.video_path
ext = video_path.suffix.lstrip('.') if video_path else config.merge_output_format or 'mp4'
variables = dict(
uploader=escape_file_name(uploader) if uploader else '',
channel=escape_file_name(uploader) if uploader else '', # Alias
upload_date=upload_date.strftime('%Y%m%d') if upload_date else '',
id=source_id,
title=escape_file_name(title) if title else 'untitled',
ext=ext,
# WROLPi-specific variables for subdirectory organization
upload_year=str(upload_date.year) if upload_date else '',
upload_month=f'{upload_date.month:02d}' if upload_date else '',
)
# Convert WROLPi-specific variables to yt-dlp syntax then apply
# (This handles %(upload_year)s -> %(upload_date>%Y)s conversion)
converted_template = convert_wrolpi_filename_format(template)
# For the converted variables (like %(upload_date>%Y)s), we need to add them too
variables['upload_date>%Y'] = str(upload_date.year) if upload_date else ''
variables['upload_date>%m'] = f'{upload_date.month:02d}' if upload_date else ''
try:
result = converted_template % variables
# Trim the filename portion if it's too long (may include subdirectory paths)
if '/' in result:
# Has subdirectories - only trim the filename part
parts = result.rsplit('/', 1)
subdir = parts[0]
filename = trim_file_name(parts[1])
return f'{subdir}/{filename}'
else:
return trim_file_name(result)
except KeyError as e:
logger.error(f'Invalid variable in video file_name_format: {e}')
# Fallback to a simple format
fallback_title = escape_file_name(title) if title else 'untitled'
return trim_file_name(f'{fallback_title}.{ext}')

View file

@ -785,6 +785,9 @@ class Channel(ModelHelper, Base):
tag_name=self.tag_name,
url=self.url or None,
)
# Include file_format from the underlying Collection
if self.collection and self.collection.file_format:
config['file_format'] = self.collection.file_format
return config
@classmethod
@ -860,6 +863,7 @@ class Channel(ModelHelper, Base):
d['rss_url'] = self.get_rss_url()
d['directory'] = \
self.directory.relative_to(get_media_directory()) if self.directory else None
d['needs_reorganization'] = self.collection.needs_reorganization if self.collection else False
if with_statistics:
d['statistics'] = self.get_statistics()
if with_downloads:

View file

@ -280,3 +280,45 @@ class TestChannelsConfigEdgeCases:
# Directory should be relative, not absolute
assert not config['directory'].startswith('/'), \
f"Expected relative path but got absolute: {config['directory']}"
async def test_channel_config_view_includes_file_format(self, test_session, test_directory, async_client,
test_channels_config, channel_factory):
"""Channel.config_view() should include file_format from underlying Collection."""
channel = channel_factory()
channel.collection.file_format = '%(uploader)s_%(id)s_%(title)s.%(ext)s'
test_session.commit()
config = channel.config_view()
assert config['file_format'] == '%(uploader)s_%(id)s_%(title)s.%(ext)s'
async def test_channel_file_format_round_trip(self, test_session, test_directory, async_client,
test_channels_config, channel_factory):
"""File format should survive config dump and import cycle."""
config = get_channels_config()
config_path = config.get_file()
# Create channel with file_format
channel = channel_factory(name='Format Test')
channel.collection.file_format = '%(upload_date)s_%(title)s.%(ext)s'
test_session.commit()
# Dump to config
config.dump_config()
# Verify file_format in YAML
with open(config_path) as f:
config_data = yaml.safe_load(f)
channel_config = next(c for c in config_data['channels'] if c['name'] == 'Format Test')
assert channel_config['file_format'] == '%(upload_date)s_%(title)s.%(ext)s'
# Clear the file_format to simulate factory reset
channel.collection.file_format = None
test_session.commit()
# Re-import
config.initialize()
config.import_config()
# Verify file_format restored
test_session.refresh(channel)
assert channel.collection.file_format == '%(upload_date)s_%(title)s.%(ext)s'

View file

@ -8,7 +8,8 @@ from unittest import mock
import pytest
from modules.videos.downloader import VideoDownloader, \
get_or_create_channel, channel_downloader, video_downloader, preview_filename
get_or_create_channel, channel_downloader, video_downloader, preview_filename, \
prepare_filename, convert_wrolpi_filename_format
from modules.videos.lib import get_videos_downloader_config
from modules.videos.models import Channel, Video
from wrolpi.conftest import test_directory, await_switches
@ -573,6 +574,54 @@ def test_preview_filename_with_upload_year(test_directory, fake_now):
== '2000/WROLPi_20000101_The title of the video.mp4'
def test_preview_filename_matches_youtubedl(test_directory, fake_now):
"""Ensure our lightweight preview_filename() matches YoutubeDL's actual output.
This test validates that our simple string formatting produces identical
results to YoutubeDL's prepare_filename(). If yt-dlp changes behavior,
this test will catch it.
"""
from copy import deepcopy
from yt_dlp import YoutubeDL
from wrolpi.dates import now
test_formats = [
'%(uploader)s_%(upload_date)s_%(id)s_%(title)s.%(ext)s',
'%(upload_date)s_%(id)s_%(title)s.%(ext)s',
'%(upload_year)s/%(upload_month)s/%(title)s.%(ext)s',
'%(upload_year)s/%(uploader)s_%(upload_date)s_%(title)s.%(ext)s',
'%(channel)s/%(id)s.%(ext)s',
]
# Sample entry used by both methods - must match preview_filename's variables
sample_date = now()
entry = dict(
uploader='WROLPi',
channel='WROLPi',
timestamp=int(sample_date.timestamp()),
upload_date=sample_date.strftime('%Y%m%d'),
id='Qz-FuenRylQ',
title='The title of the video',
ext='mp4',
description='A description of the video',
)
for fmt in test_formats:
# Get result from our lightweight implementation
lightweight_result = preview_filename(fmt)
# Get result from actual YoutubeDL
converted_format = convert_wrolpi_filename_format(fmt)
options = get_videos_downloader_config().yt_dlp_options
options = deepcopy(options)
options['outtmpl'] = converted_format
ydl = YoutubeDL(options)
ytdlp_result = prepare_filename(entry, ydl=ydl).lstrip('/')
assert lightweight_result == ytdlp_result, \
f"Mismatch for format '{fmt}':\n lightweight: {lightweight_result}\n ytdlp: {ytdlp_result}"
def test_normalize_video_file_names(test_directory, video_download_manager):
"""VideoDownloader renames caption files that do not share the video file's stem."""
downloader = VideoDownloader()

View file

@ -326,3 +326,32 @@ def test_video_location(test_session, video_factory, channel_factory, async_clie
channel = channel_factory(name='ChannelName')
video2 = video_factory(title='vid2', channel_id=channel.id)
assert video2.location == '/videos/channel/1/video/2'
def test_format_video_filename_without_upload_date(test_session, video_factory, test_videos_downloader_config, caplog):
"""Videos without upload_date should not cause KeyError when format uses upload_year."""
import logging
from modules.videos.lib import format_video_filename
# Create video without upload_date
video = video_factory(title='Test Video', with_video_file=True, with_info_json={'id': 'abc123'})
assert video.file_group.published_datetime is None
# Use a format that includes upload_year subdirectory
template = '%(upload_year)s/%(uploader)s_%(upload_date)s_%(id)s_%(title)s.%(ext)s'
# Should not raise KeyError and should not log an error
with caplog.at_level(logging.ERROR):
result = format_video_filename(video, template)
# Should not have logged any errors (fallback was not used)
assert 'Invalid variable in video file_name_format' not in caplog.text
# Should return a properly formatted filename with the template structure
# (empty year and date components produce a path with subdirectory)
assert result.endswith('.mp4')
assert 'Test Video' in result
# The result should follow the template format, not the fallback format
# Template result: '{upload_year}/{uploader}_{upload_date}_{id}_{title}.mp4'
# With empty year/date: '/__Test Video_Test Video.mp4' (has a slash for subdirectory)
assert '/' in result # Confirms template was used (has subdirectory), not fallback