Handling edge case when configs have absolute directories.

This commit is contained in:
Roland 2026-01-23 15:11:12 -07:00
parent d60f7f237a
commit 31af5120b8
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
15 changed files with 126 additions and 69 deletions

View file

@ -484,7 +484,8 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f
destination=str(test_directory / 'videos/Channel Name'))
test_session.commit()
save_channels_config()
assert get_channels_config().channels[0]['directory'] == str(test_directory / 'videos/Channel Name')
# Config stores relative paths for portability
assert get_channels_config().channels[0]['directory'] == 'videos/Channel Name'
# Channel download downloads into the Channel's directory.
assert channel.downloads[0].destination == test_directory / 'videos/Channel Name'
# Make extra file in the Channel's directory, it should be moved.
@ -527,7 +528,8 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f
# No new files were created.
assert len([i for i in walk(videos_directory) if i.is_file()]) == 3
assert get_channels_config().channels[0]['directory'] == str(test_directory / 'videos/Tag Name/Channel Name')
# Config stores relative paths for portability
assert get_channels_config().channels[0]['directory'] == 'videos/Tag Name/Channel Name'
# Remove tag, Channel/Videos should be moved back.
body = dict(tag_name=None, directory='videos/Channel Name')

View file

@ -767,9 +767,16 @@ class Channel(ModelHelper, Base):
"""
Retrieve the data about this Channel that should be stored in a config file.
"""
# Store relative path for portability across different media directories
try:
directory = str(get_relative_to_media_directory(self.directory))
except ValueError:
# Directory outside media directory, store as-is
directory = str(self.directory)
config = dict(
calculate_duration=self.calculate_duration,
directory=str(self.directory),
directory=directory,
download_missing_data=self.download_missing_data,
downloads=[{'url': i.url, 'frequency': i.frequency} for i in self.downloads],
generate_posters=self.generate_posters,

View file

@ -268,3 +268,15 @@ class TestChannelsConfigEdgeCases:
channel = test_session.query(Channel).filter_by(url='https://example.com/new').first()
assert channel is not None
assert channel.name == 'Update Me'
async def test_channel_config_view_uses_relative_directory(self, test_session, test_directory, async_client,
test_channels_config, channel_factory):
"""Channel.config_view() should export directory as relative path for portability."""
channel = channel_factory()
test_session.commit()
config = channel.config_view()
# Directory should be relative, not absolute
assert not config['directory'].startswith('/'), \
f"Expected relative path but got absolute: {config['directory']}"

View file

@ -9,7 +9,7 @@ from PIL import Image
from modules.videos.models import Channel, Video
from wrolpi.collections import Collection
from wrolpi.common import get_absolute_media_path, get_wrolpi_config
from wrolpi.common import get_absolute_media_path, get_wrolpi_config, get_relative_to_media_directory
from wrolpi.downloader import Download, DownloadFrequency
from wrolpi.vars import PROJECT_DIR
from .. import common
@ -261,8 +261,9 @@ async def test_import_channel_delete_missing_channels(await_switches, test_sessi
test_session.commit()
# Capture directory values before deletion (channels will be detached after deletion)
channel1_dir = str(channel1.directory)
channel2_dir = str(channel2.directory)
# Config stores relative paths for portability
channel1_dir = str(get_relative_to_media_directory(channel1.directory))
channel2_dir = str(get_relative_to_media_directory(channel2.directory))
# Write Channels to the config file.
save_channels_config()
@ -314,9 +315,9 @@ async def test_import_channel_deletes_orphaned_collections(await_switches, test_
# Verify both Collections exist
assert test_session.query(Collection).filter_by(kind='channel').count() == 2
# Capture directory values before deletion
channel1_dir = str(channel1.directory)
channel2_dir = str(channel2.directory)
# Capture directory values before deletion (config stores relative paths)
channel1_dir = str(get_relative_to_media_directory(channel1.directory))
channel2_dir = str(get_relative_to_media_directory(channel2.directory))
collection2_id = channel2.collection_id
# Write Channels to the config file

View file

@ -166,8 +166,12 @@ class Collection(ModelHelper, Base):
config['description'] = self.description
if self.directory:
# Store absolute path for consistency with Channel config
config['directory'] = str(self.directory)
# Store relative path for portability across different media directories
try:
config['directory'] = str(get_relative_to_media_directory(self.directory))
except ValueError:
# Directory outside media directory, store as-is
config['directory'] = str(self.directory)
config['tag_name'] = self.tag_name

View file

@ -65,8 +65,8 @@ async def test_collection_lifecycle_end_to_end(async_client, test_session: Sessi
data = yaml.safe_load(config_file.read_text())
assert isinstance(data, dict)
dumped = data.get('collections', [])
# Config stores absolute paths
assert any(c.get('name') == 'Lifecycle Test Collection' and c.get('directory') == str(coll_dir) and c.get(
# Config stores relative paths for portability
assert any(c.get('name') == 'Lifecycle Test Collection' and c.get('directory') == str(rel_dir) and c.get(
'kind') == 'channel' for c in dumped)
# 5) Add a new video to the same directory; ensure fetch methods include it after population

View file

@ -44,13 +44,13 @@ async def test_tagging_directory_collection_moves_files_and_updates_config(
# Verify it populated
assert {i.file_group_id for i in coll.get_items(test_session)} == {v1.file_group_id, v2.file_group_id}
# Dump config and verify (config stores absolute paths)
# Dump config and verify (config stores relative paths for portability)
collections_config.dump_config()
cfg_file = collections_config.get_file()
data = yaml.safe_load(cfg_file.read_text())
dumped = data.get('collections', [])
assert any(
c.get('name') == 'Funny Clips' and c.get('directory') == str(src_dir) and c.get('kind') == 'channel' for c in
c.get('name') == 'Funny Clips' and c.get('directory') == str(rel_dir) and c.get('kind') == 'channel' for c in
dumped)
# Tag the collection -> should move to videos/<Tag>/<Collection Name>
@ -79,12 +79,13 @@ async def test_tagging_directory_collection_moves_files_and_updates_config(
assert str(dest_dir) in str(v1.file_group.primary_path)
assert str(dest_dir) in str(v2.file_group.primary_path)
# Dump config again and verify updated directory and tag (config stores absolute paths)
# Dump config again and verify updated directory and tag (config stores relative paths)
collections_config.dump_config()
data = yaml.safe_load(cfg_file.read_text())
dumped = data.get('collections', [])
rel_dest_dir = dest_dir.relative_to(get_media_directory())
assert any(
c.get('name') == 'Funny Clips' and c.get('directory') == str(dest_dir) and c.get('tag_name') == 'Funny' for
c.get('name') == 'Funny Clips' and c.get('directory') == str(rel_dest_dir) and c.get('tag_name') == 'Funny' for
c in dumped)

View file

@ -11,6 +11,7 @@ import pytest
from sqlalchemy.orm import Session
from wrolpi.collections.models import Collection
from wrolpi.common import get_media_directory
@pytest.mark.asyncio
@ -376,9 +377,10 @@ async def test_tag_domain_comprehensive(
config = get_domains_config()
domain_entry = next((c for c in config.collections if c['name'] == 'example.com'), None)
assert domain_entry is not None, "Domain not in config"
# Config stores absolute paths
assert domain_entry['directory'] == str(domain_directory), \
f"Config directory should be: {domain_entry['directory']}"
# Config stores relative paths for portability
rel_domain_directory = domain_directory.relative_to(get_media_directory())
assert domain_entry['directory'] == str(rel_domain_directory), \
f"Config directory should be: {rel_domain_directory}"
# Domain download downloads into the domain's directory
assert collection.downloads[0].destination == domain_directory, \
@ -431,7 +433,8 @@ async def test_tag_domain_comprehensive(
config = get_domains_config()
domain_entry = next((c for c in config.collections if c['name'] == 'example.com'), None)
assert domain_entry is not None, "Domain should still be in config"
assert domain_entry['directory'] == str(new_domain_directory), \
rel_new_domain_directory = new_domain_directory.relative_to(get_media_directory())
assert domain_entry['directory'] == str(rel_new_domain_directory), \
f"Config directory should be updated: {domain_entry['directory']}"
# Remove tag, domain/archives should be moved back

View file

@ -213,3 +213,22 @@ class TestDomainsConfig:
assert domains_config is not None
assert isinstance(domains_config, DomainsConfig)
assert domains_config.file_name == 'domains.yaml'
def test_collection_to_config_uses_relative_directory(self, test_session, test_directory, async_client):
"""Collection.to_config() should export directory as relative path for portability."""
directory = test_directory / 'archive' / 'example.com'
directory.mkdir(parents=True)
collection = Collection.from_config(test_session, {
'name': 'example.com',
'kind': 'domain',
'directory': str(directory),
})
test_session.commit()
config = collection.to_config()
# Directory should be relative, not absolute
assert not config['directory'].startswith('/'), \
f"Expected relative path but got absolute: {config['directory']}"
assert config['directory'] == 'archive/example.com'

View file

@ -17,7 +17,7 @@ import sys
import tempfile
from asyncio import Task
from copy import deepcopy
from dataclasses import dataclass, asdict, field, fields
from dataclasses import dataclass, field, fields
from datetime import datetime, date
from decimal import Decimal
from functools import wraps
@ -25,7 +25,7 @@ from itertools import islice, filterfalse, tee
from multiprocessing.managers import DictProxy
from pathlib import Path
from types import GeneratorType
from typing import Optional, List, Any, AsyncGenerator
from typing import Optional, List, AsyncGenerator
from typing import Union, Callable, Tuple, Dict, Iterable, Generator, Any, Set
from urllib.parse import urlparse, urlunsplit
@ -43,7 +43,7 @@ from sqlalchemy.orm import Session
from wrolpi.dates import now, from_timestamp
from wrolpi.errors import WROLModeEnabled, NativeOnly, LogLevelError, InvalidConfig, \
ValidationError
from wrolpi.log_levels import TRACE_LEVEL, name_to_int as log_level_name_to_int, int_to_name as log_level_int_to_name
from wrolpi.log_levels import TRACE_LEVEL
from wrolpi.vars import PYTEST, DOCKERIZED, CONFIG_DIR, MEDIA_DIRECTORY, DEFAULT_HTTP_HEADERS
@ -680,7 +680,8 @@ class ConfigFile:
# Check for fields in default_config that are missing from validator
missing_from_validator = default_fields - allowed_fields
if missing_from_validator:
logger.error(f'{self.file_name}: Fields in default_config but missing from validator: {missing_from_validator}')
logger.error(
f'{self.file_name}: Fields in default_config but missing from validator: {missing_from_validator}')
try:
# Remove keys no longer in the config.
config_items = config.items()
@ -1848,10 +1849,10 @@ async def await_background_tasks(timeout: int = 15):
elapsed = time.time() - start_time
if elapsed > timeout:
task_names = [t.get_name() if hasattr(t, 'get_name') else str(t) for t in BACKGROUND_TASKS]
logger_.error(f'await_background_tasks: TIMEOUT after {elapsed:.1f}s, {iteration} iterations')
logger_.error(f' BACKGROUND_TASKS={len(BACKGROUND_TASKS)}: {task_names}')
logger_.error(f' public_queue={file_worker.public_queue.qsize()}, private_queue_empty={file_worker.private_queue.empty()}')
if __debug__ and logger_.isEnabledFor(TRACE_LEVEL):
task_names = [t.get_name() if hasattr(t, 'get_name') else str(t) for t in BACKGROUND_TASKS]
logger_.trace(
f'await_background_tasks: TIMEOUT after {elapsed:.1f}s with {len(BACKGROUND_TASKS)} tasks: {task_names}')
# Cancel stuck tasks and clear to prevent cascading failures
for task in list(BACKGROUND_TASKS):
if not task.done():
@ -1860,10 +1861,10 @@ async def await_background_tasks(timeout: int = 15):
break
if iteration > max_iterations:
task_names = [t.get_name() if hasattr(t, 'get_name') else str(t) for t in BACKGROUND_TASKS]
logger_.error(f'await_background_tasks: SAFETY LIMIT REACHED after {iteration} iterations')
logger_.error(f' BACKGROUND_TASKS={len(BACKGROUND_TASKS)}: {task_names}')
logger_.error(f' public_queue={file_worker.public_queue.qsize()}, private_queue_empty={file_worker.private_queue.empty()}')
if __debug__ and logger_.isEnabledFor(TRACE_LEVEL):
task_names = [t.get_name() if hasattr(t, 'get_name') else str(t) for t in BACKGROUND_TASKS]
logger_.trace(
f'await_background_tasks: SAFETY LIMIT after {iteration} iterations with {len(BACKGROUND_TASKS)} tasks: {task_names}')
break
# Process file worker queue

View file

@ -2,10 +2,11 @@ import pathlib
import traceback
from abc import ABC
from wrolpi.common import get_media_directory, logger, TRACE_LEVEL
from wrolpi.common import get_media_directory, logger
from wrolpi.downloader import Downloader, Download, DownloadResult
from wrolpi.errors import UnrecoverableDownloadError, IgnoredDirectoryError
from wrolpi.files.lib import upsert_file, get_file_location_href
from wrolpi.log_levels import TRACE_LEVEL
from wrolpi.vars import PYTEST
__all__ = ['FileDownloader', 'file_downloader']

View file

@ -1072,7 +1072,7 @@ def get_file_statistics():
curs.execute('''
SELECT
-- All items in file_group.files are real individual files.
SUM(jsonb_array_length(files)) AS "total_count",
SUM(jsonb_array_length(files)) AS "total_count",
COUNT(id) FILTER (WHERE file_group.mimetype = 'application/pdf') AS "pdf_count",
COUNT(id) FILTER (WHERE file_group.mimetype = 'application/zip') AS "zip_count",
COUNT(id) FILTER (WHERE file_group.mimetype LIKE 'video/%') AS "video_count",
@ -1207,7 +1207,7 @@ def get_refresh_progress() -> RefreshProgress:
stmt = '''
SELECT
-- Sum all the files in each FileGroup.
SUM(jsonb_array_length(files)) FILTER (WHERE idempotency = %(idempotency)s) AS "total_file_groups",
SUM(jsonb_array_length(files)) FILTER (WHERE idempotency = %(idempotency)s) AS "total_file_groups",
COUNT(id) FILTER (WHERE indexed IS TRUE AND idempotency = %(idempotency)s) AS "indexed",
COUNT(id) FILTER (WHERE indexed IS FALSE AND idempotency = %(idempotency)s) AS "unindexed",
COUNT(id) FILTER (WHERE model IS NOT NULL AND idempotency = %(idempotency)s) AS "modeled"
@ -1218,7 +1218,7 @@ def get_refresh_progress() -> RefreshProgress:
stmt = '''
SELECT
-- Sum all the files in each FileGroup.
SUM(jsonb_array_length(files)) AS "total_file_groups",
SUM(jsonb_array_length(files)) AS "total_file_groups",
COUNT(id) FILTER (WHERE indexed IS TRUE) AS "indexed",
COUNT(id) FILTER (WHERE indexed IS FALSE) AS "unindexed",
COUNT(id) FILTER (WHERE model IS NOT NULL) AS "modeled"

View file

@ -20,12 +20,12 @@ from typing import AsyncGenerator, Callable, Set, Dict, List, Tuple
from sqlalchemy import text, or_
from wrolpi import flags
from wrolpi.common import apply_modelers, apply_refresh_cleanup
from wrolpi.common import get_media_directory, get_wrolpi_config, logger, walk, chunks, unique_by_predicate
from wrolpi.dates import now
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.errors import NoPrimaryFile
from wrolpi.events import Events
from wrolpi.common import apply_modelers, apply_refresh_cleanup
from wrolpi.files.lib import (
split_path_stem_and_suffix, _upsert_files, get_unique_files_by_stem, glob_shared_stem,
group_files_by_stem, get_primary_file, delete_directory, apply_indexers,
@ -1102,8 +1102,9 @@ class FileWorker:
# Batch check: find all primary_paths that already exist on OTHER FileGroups
curs.execute(
'''SELECT primary_path, id FROM file_group
WHERE primary_path = ANY(%s)''',
'''SELECT primary_path, id
FROM file_group
WHERE primary_path = ANY (%s)''',
(all_new_paths,)
)
existing_path_to_id = {row[0]: row[1] for row in curs.fetchall()}
@ -1125,7 +1126,8 @@ class FileWorker:
'''UPDATE file_group AS fg
SET primary_path = v.new_path
FROM (SELECT unnest(%s::integer[]) AS id, unnest(%s::text[]) AS new_path) AS v
WHERE fg.id = v.id AND fg.primary_path != v.new_path''',
WHERE fg.id = v.id
AND fg.primary_path != v.new_path''',
([u[0] for u in valid_updates], [u[1] for u in valid_updates])
)
@ -1240,18 +1242,21 @@ class FileWorker:
with get_db_curs(commit=True) as curs:
# Single UNION ALL query to fetch all models at once (reduces 3 queries to 1)
curs.execute('''
SELECT 'video' AS model_type, v.id AS model_id, fg.id AS fg_id, fg.primary_path
FROM video v JOIN file_group fg ON v.file_group_id = fg.id
WHERE fg.id = ANY(%s)
UNION ALL
SELECT 'archive', a.id, fg.id, fg.primary_path
FROM archive a JOIN file_group fg ON a.file_group_id = fg.id
WHERE fg.id = ANY(%s)
UNION ALL
SELECT 'ebook', e.id, fg.id, fg.primary_path
FROM ebook e JOIN file_group fg ON e.file_group_id = fg.id
WHERE fg.id = ANY(%s)
''', (file_group_ids, file_group_ids, file_group_ids))
SELECT 'video' AS model_type, v.id AS model_id, fg.id AS fg_id, fg.primary_path
FROM video v
JOIN file_group fg ON v.file_group_id = fg.id
WHERE fg.id = ANY (%s)
UNION ALL
SELECT 'archive', a.id, fg.id, fg.primary_path
FROM archive a
JOIN file_group fg ON a.file_group_id = fg.id
WHERE fg.id = ANY (%s)
UNION ALL
SELECT 'ebook', e.id, fg.id, fg.primary_path
FROM ebook e
JOIN file_group fg ON e.file_group_id = fg.id
WHERE fg.id = ANY (%s)
''', (file_group_ids, file_group_ids, file_group_ids))
# Group results by model type
video_ids_to_delete = []
@ -1272,25 +1277,28 @@ class FileWorker:
if video_ids_to_delete:
logger.info(f'Deleting {len(video_ids_to_delete)} Videos whose primary file was removed')
curs.execute('''
UPDATE file_group SET model = NULL
WHERE id IN (SELECT file_group_id FROM video WHERE id = ANY(%s))
''', (video_ids_to_delete,))
UPDATE file_group
SET model = NULL
WHERE id IN (SELECT file_group_id FROM video WHERE id = ANY (%s))
''', (video_ids_to_delete,))
curs.execute('DELETE FROM video WHERE id = ANY(%s)', (video_ids_to_delete,))
if archive_ids_to_delete:
logger.info(f'Deleting {len(archive_ids_to_delete)} Archives whose primary file was removed')
curs.execute('''
UPDATE file_group SET model = NULL
WHERE id IN (SELECT file_group_id FROM archive WHERE id = ANY(%s))
''', (archive_ids_to_delete,))
UPDATE file_group
SET model = NULL
WHERE id IN (SELECT file_group_id FROM archive WHERE id = ANY (%s))
''', (archive_ids_to_delete,))
curs.execute('DELETE FROM archive WHERE id = ANY(%s)', (archive_ids_to_delete,))
if ebook_ids_to_delete:
logger.info(f'Deleting {len(ebook_ids_to_delete)} EBooks whose primary file was removed')
curs.execute('''
UPDATE file_group SET model = NULL
WHERE id IN (SELECT file_group_id FROM ebook WHERE id = ANY(%s))
''', (ebook_ids_to_delete,))
UPDATE file_group
SET model = NULL
WHERE id IN (SELECT file_group_id FROM ebook WHERE id = ANY (%s))
''', (ebook_ids_to_delete,))
curs.execute('DELETE FROM ebook WHERE id = ANY(%s)', (ebook_ids_to_delete,))
def _validate_move_paths(

View file

@ -23,7 +23,7 @@ from wrolpi.api_utils import json_response, api_app
from wrolpi.collections.api import collection_bp
from wrolpi.common import logger, get_wrolpi_config, wrol_mode_enabled, get_media_directory, \
wrol_mode_check, native_only, disable_wrol_mode, enable_wrol_mode, get_global_statistics, url_strip_host, \
set_global_log_level, get_relative_to_media_directory, search_other_estimates, log_level_int_to_name
set_global_log_level, get_relative_to_media_directory, search_other_estimates
from wrolpi.config_api import config_bp
from wrolpi.dates import now
from wrolpi.downloader import download_manager
@ -31,6 +31,7 @@ from wrolpi.errors import WROLModeEnabled, InvalidConfig, ValidationError
from wrolpi.events import get_events, Events
from wrolpi.files import files_bp
from wrolpi.files.lib import get_file_statistics, search_file_suggestion_count
from wrolpi.log_levels import int_to_name
from wrolpi.tags import Tag
from wrolpi.vars import DOCKERIZED, IS_RPI, IS_RPI4, IS_RPI5, API_HOST, API_PORT, API_WORKERS, API_DEBUG, \
API_ACCESS_LOG, truthy_arg, API_AUTO_RELOAD
@ -230,7 +231,7 @@ async def update_settings(_: Request, body: schema.SettingsRequest):
if isinstance(log_level, int):
set_global_log_level(log_level)
# Persist log level to config
wrolpi_config.log_level = log_level_int_to_name(log_level)
wrolpi_config.log_level = int_to_name(log_level)
# Save config settings (hotspot control is now through Controller endpoints)
wrolpi_config.update(new_config)

View file

@ -101,11 +101,8 @@ async def switch_worker():
# Get new switch and its context. Handle each switch one at a time.
# During testing, don't block the event loop - check for pending switches directly.
# In production, use blocking wait which is more efficient for long-running processes.
if PYTEST:
# Non-blocking: return immediately if no switches pending.
# The perpetual_signal decorator will call again in 0.1s.
if not api_app.shared_ctx.switches:
return
if PYTEST and not api_app.shared_ctx.switches:
return
else:
switches_changed.wait(timeout=1)
switches: dict = api_app.shared_ctx.switches