mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-29 03:16:22 -05:00
A Zim's Search toggle is saved in zims.yaml so a rebuilt database or a newer Zim keeps it (#931)
The toggle was only the zim.auto_search column, which defaults to on. The database is rebuilt from files and configs, and a Zim's newer version is a new row, so every rebuild and every subscription update turned search back on for every Zim. On a large library the global search then searched all of them. zims.yaml records auto_search for each Zim, keyed by the Zim's name without its date, so a newer version of a Zim is the same Zim. A Zim the file does not name is searched (the default stays on). The config is imported on startup with the usual version gating, saved when the toggle changes, and a newly modeled Zim takes its setting from it. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
6fc147ccdf
commit
851b12b060
5 changed files with 255 additions and 5 deletions
|
|
@ -1 +1 @@
|
|||
Subproject commit 90d4aaa861fd633fee65d66cbce973d4e7c7561f
|
||||
Subproject commit 9cf3296b1285695409ae6ee522ab53354c137e33
|
||||
|
|
@ -4,6 +4,7 @@ import json
|
|||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from collections import OrderedDict
|
||||
from typing import Callable, List, Tuple, Dict, OrderedDict as OrderedDictType
|
||||
|
|
@ -20,8 +21,10 @@ from modules.zim.models import Zim, Zims, TagZimEntry, ZimSubscription, ZimMetad
|
|||
from wrolpi import flags, tags
|
||||
from wrolpi.cmd import run_command
|
||||
from wrolpi.common import register_modeler, logger, extract_html_text, extract_headlines, get_media_directory, walk, \
|
||||
register_refresh_cleanup, background_task, get_wrolpi_config, aiohttp_post
|
||||
from wrolpi.switches import register_switch_handler
|
||||
register_refresh_cleanup, background_task, get_wrolpi_config, aiohttp_post, ConfigFile, \
|
||||
get_relative_to_media_directory
|
||||
from wrolpi.config_version import register_ownership, IMPORT, SAVE, set_config_version
|
||||
from wrolpi.switches import register_switch_handler, ActivateSwitchMethod
|
||||
from wrolpi.dates import Seconds
|
||||
from wrolpi.events import Events
|
||||
from wrolpi.db import get_db_session, session_curs
|
||||
|
|
@ -44,7 +47,11 @@ __all__ = [
|
|||
'get_kiwix_catalog',
|
||||
'get_zim',
|
||||
'get_zims',
|
||||
'get_zims_config',
|
||||
'import_zims_config',
|
||||
'model_zim',
|
||||
'save_zims_config',
|
||||
'zims_config',
|
||||
'restart_kiwix_handler',
|
||||
'zim_download_url_to_name',
|
||||
'zim_modeler',
|
||||
|
|
@ -62,8 +69,10 @@ def model_zim(file_group: FileGroup, session: Session) -> Zim:
|
|||
# Check if a Zim already exists for this FileGroup
|
||||
zim = session.query(Zim).filter_by(file_group_id=file_group.id).one_or_none()
|
||||
if not zim:
|
||||
# Create new Zim if it doesn't exist
|
||||
zim = Zim(file_group=file_group, path=file_group.primary_path)
|
||||
# Create new Zim if it doesn't exist. Its settings come from zims.yaml: a rebuilt database, or a newer
|
||||
# version of a Zim, keeps what the user chose.
|
||||
zim = Zim(file_group=file_group, path=file_group.primary_path,
|
||||
auto_search=zims_config.auto_search_of(file_group.primary_path))
|
||||
session.add(zim)
|
||||
# Trigger Kiwix restart so the new zim file is available for browsing.
|
||||
restart_kiwix_handler.activate_switch()
|
||||
|
|
@ -750,7 +759,127 @@ async def restart_kiwix():
|
|||
return result.return_code
|
||||
|
||||
|
||||
def zim_config_name(path: pathlib.Path) -> str:
|
||||
"""The name zims.yaml keys a Zim by: its file name without the date, so a newer version of the Zim is the same
|
||||
Zim (wikipedia_en_all_maxi_2026-02.zim -> wikipedia_en_all_maxi). A Zim named without a date keeps its stem."""
|
||||
try:
|
||||
return parse_name(path)[0]
|
||||
except ValueError:
|
||||
return path.stem
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZimsConfigValidator:
|
||||
version: int = 0
|
||||
auto_search: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
class ZimsConfig(ConfigFile):
|
||||
"""zims.yaml: the settings of each Zim that must survive a rebuilt database, keyed by `zim_config_name`.
|
||||
|
||||
Format:
|
||||
auto_search:
|
||||
stackoverflow.com_en_all: false
|
||||
wikipedia_en_all_maxi: true
|
||||
|
||||
`auto_search` is whether the global search searches the Zim. A Zim the file does not name is searched (the
|
||||
default), so removing a line restores the default."""
|
||||
file_name = 'zims.yaml'
|
||||
validator = ZimsConfigValidator
|
||||
default_config = dict(version=0, auto_search={})
|
||||
|
||||
@property
|
||||
def auto_search(self) -> Dict[str, bool]:
|
||||
return dict(self._config.get('auto_search') or {})
|
||||
|
||||
def auto_search_of(self, path: pathlib.Path) -> bool:
|
||||
"""Whether the Zim at `path` should be searched by default, per the config."""
|
||||
return bool(self.auto_search.get(zim_config_name(path), True))
|
||||
|
||||
def import_config(self, file: pathlib.Path = None, send_events=False):
|
||||
"""Read the file, then apply `auto_search` to every Zim in the database."""
|
||||
file = file or self.get_file()
|
||||
if not file.is_file():
|
||||
# A missing config is not an empty one: the defaults, and the database, stand.
|
||||
logger.info(f'No config file, skipping import: {get_relative_to_media_directory(file)}')
|
||||
self.successful_import = True
|
||||
return
|
||||
forced, self.force_import = self.force_import, False
|
||||
super().import_config(file, send_events)
|
||||
try:
|
||||
decision, db_version = self.version_decision(self.version or 0, forced)
|
||||
if decision == SAVE:
|
||||
self.save_database_instead()
|
||||
return
|
||||
config = self.auto_search
|
||||
changed = 0
|
||||
with get_db_session(commit=True) as session:
|
||||
for zim in session.query(Zim):
|
||||
name = zim_config_name(zim.path)
|
||||
if name in config:
|
||||
want = bool(config[name])
|
||||
elif decision == IMPORT:
|
||||
# Not in the file: the default.
|
||||
want = True
|
||||
else:
|
||||
# The file may be older than the database; only apply what it names.
|
||||
continue
|
||||
if bool(zim.auto_search) != want:
|
||||
zim.auto_search = want
|
||||
changed += 1
|
||||
if decision == IMPORT:
|
||||
session.flush()
|
||||
set_config_version(session, self.file_name, self.version or 0)
|
||||
logger.info(f'Imported {self.file_name} ({decision}): {changed} Zims changed')
|
||||
if decision != IMPORT:
|
||||
# The database may have Zims the file does not list; save them (see `record_saved_version`).
|
||||
self.background_dump.activate_switch()
|
||||
except Exception as e:
|
||||
self.successful_import = False
|
||||
message = f'Failed to import {self.file_name}'
|
||||
logger.error(message, exc_info=e)
|
||||
if send_events:
|
||||
Events.send_config_import_failed(message)
|
||||
raise
|
||||
|
||||
def dump_config(self, file: pathlib.Path = None, send_events=False, overwrite=False):
|
||||
"""Save every Zim's settings. Of several versions of one Zim, the newest decides."""
|
||||
with get_db_session() as session:
|
||||
version = self.db_version_for_dump(session)
|
||||
# Sorted by path, so the newest version of a Zim (its date sorts last) wins.
|
||||
auto_search = dict()
|
||||
for zim in session.query(Zim).order_by(Zim.path):
|
||||
auto_search[zim_config_name(zim.path)] = bool(zim.auto_search)
|
||||
self._config['auto_search'] = dict(sorted(auto_search.items()))
|
||||
self._config['version'] = version
|
||||
logger.info(f'Dumping {len(auto_search)} Zim settings to config')
|
||||
self.save(file, send_events, overwrite)
|
||||
|
||||
|
||||
zims_config = ZimsConfig()
|
||||
register_ownership(ZimsConfig.file_name, Zim, columns={'auto_search'})
|
||||
|
||||
|
||||
def get_zims_config() -> ZimsConfig:
|
||||
return zims_config
|
||||
|
||||
|
||||
@register_switch_handler('save_zims_config')
|
||||
def save_zims_config():
|
||||
"""Save the zims config when the switch is activated."""
|
||||
zims_config.background_dump.activate_switch()
|
||||
|
||||
|
||||
save_zims_config: ActivateSwitchMethod
|
||||
|
||||
|
||||
def import_zims_config():
|
||||
logger.info('Importing zims config')
|
||||
zims_config.import_config()
|
||||
|
||||
|
||||
def set_zim_auto_search(session: Session, zim_id: int, auto_search: bool):
|
||||
zim = Zim.find_by_id(session, zim_id)
|
||||
zim.auto_search = auto_search
|
||||
session.commit()
|
||||
save_zims_config.activate_switch()
|
||||
|
|
|
|||
99
modules/zim/test/test_config.py
Normal file
99
modules/zim/test/test_config.py
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
import pytest
|
||||
|
||||
from modules.zim import lib
|
||||
from modules.zim.models import Zim
|
||||
from wrolpi.conftest import config_versions_lost
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dump_and_import(test_session, test_directory, async_client, test_wrolpi_config, zim_factory,
|
||||
await_switches):
|
||||
"""zims.yaml is the source of truth for each Zim's auto_search; a lost database is rebuilt from it."""
|
||||
wikipedia = zim_factory('wikipedia_en_all_maxi_2026-02.zim')
|
||||
stackoverflow = zim_factory('stackoverflow.com_en_all_2022-11.zim')
|
||||
# A Zim named without a date is keyed by its file name.
|
||||
plants = zim_factory('edibleplantdb.zim')
|
||||
test_session.commit()
|
||||
assert all(i.auto_search for i in (wikipedia, stackoverflow, plants)), 'Search is enabled by default'
|
||||
|
||||
# Turning off a Zim's search saves the config, keyed by the Zim's name without its date.
|
||||
request, response = await async_client.post(f'/api/zim/{stackoverflow.id}/auto_search',
|
||||
json=dict(auto_search=False))
|
||||
assert response.status_code == 204
|
||||
await await_switches()
|
||||
config = lib.get_zims_config()
|
||||
assert config.get_file().is_file()
|
||||
assert config.read_config_file()['auto_search'] == {
|
||||
'edibleplantdb': True,
|
||||
'stackoverflow.com_en_all': False,
|
||||
'wikipedia_en_all_maxi': True,
|
||||
}
|
||||
|
||||
# Lose the database.
|
||||
test_session.query(Zim).delete()
|
||||
test_session.query(FileGroup).delete()
|
||||
test_session.commit()
|
||||
config_versions_lost(test_session)
|
||||
wikipedia = zim_factory('wikipedia_en_all_maxi_2026-02.zim')
|
||||
stackoverflow = zim_factory('stackoverflow.com_en_all_2022-11.zim')
|
||||
test_session.commit()
|
||||
assert stackoverflow.auto_search is True, 'The rebuilt row has the default'
|
||||
|
||||
config.import_config()
|
||||
test_session.expire_all()
|
||||
assert stackoverflow.auto_search is False, 'The import restored the choice'
|
||||
assert wikipedia.auto_search is True
|
||||
|
||||
# Removing a Zim from the file restores the default.
|
||||
await await_switches() # The import without deletes saved the file; the versions are now in step.
|
||||
data = config.read_config_file()
|
||||
del data['auto_search']['stackoverflow.com_en_all']
|
||||
data['version'] += 1
|
||||
config.write_config_data(data, config.get_file())
|
||||
config.import_config()
|
||||
test_session.expire_all()
|
||||
assert stackoverflow.auto_search is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_new_zim_version_keeps_the_setting(test_session, test_directory, async_client, test_wrolpi_config,
|
||||
zim_path_factory):
|
||||
"""A newer version of a Zim, modeled after its download, has the setting of the Zim it replaces."""
|
||||
config = lib.get_zims_config()
|
||||
config.write_config_data(dict(version=1, auto_search={'stackoverflow.com_en_all': False}), config.get_file())
|
||||
config.import_config()
|
||||
|
||||
for name in ('stackoverflow.com_en_all_2023-05.zim', 'wikipedia_en_all_maxi_2026-02.zim'):
|
||||
file_group = FileGroup.from_paths(test_session, zim_path_factory(name))
|
||||
lib.model_zim(file_group, test_session)
|
||||
test_session.commit()
|
||||
|
||||
zims = {lib.zim_config_name(i.path): i.auto_search for i in test_session.query(Zim)}
|
||||
assert zims == {'stackoverflow.com_en_all': False, 'wikipedia_en_all_maxi': True}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_older_file_saves_the_database(test_session, test_directory, async_client, test_wrolpi_config,
|
||||
zim_factory, await_switches):
|
||||
"""A file older than the database (the database changed, WROLPi restarted before it was saved) does not undo
|
||||
the change; the database is saved instead."""
|
||||
zim = zim_factory('wikipedia_en_all_maxi_2026-02.zim')
|
||||
test_session.commit()
|
||||
config = lib.get_zims_config()
|
||||
config.dump_config()
|
||||
await await_switches()
|
||||
saved_version = config.read_config_file()['version']
|
||||
|
||||
# The database changes (counted against the config's version) but is not saved.
|
||||
lib.set_zim_auto_search(test_session, zim.id, False)
|
||||
assert zim.auto_search is False
|
||||
|
||||
# The file still says True, and is older.
|
||||
config.import_config()
|
||||
test_session.expire_all()
|
||||
assert zim.auto_search is False, 'The older file must not undo the database'
|
||||
await await_switches()
|
||||
data = config.read_config_file()
|
||||
assert data['auto_search'] == {'wikipedia_en_all_maxi': False}
|
||||
assert data['version'] > saved_version
|
||||
|
|
@ -1498,6 +1498,10 @@ def get_all_configs() -> Dict[str, ConfigFile]:
|
|||
if repos_config := get_repos_config():
|
||||
all_configs[repos_config.file_name] = repos_config
|
||||
|
||||
from modules.zim.lib import get_zims_config
|
||||
if zims_config := get_zims_config():
|
||||
all_configs[zims_config.file_name] = zims_config
|
||||
|
||||
from wrolpi.files.progress import get_recently_viewed_config
|
||||
if recently_viewed_config := get_recently_viewed_config():
|
||||
all_configs[recently_viewed_config.file_name] = recently_viewed_config
|
||||
|
|
@ -1630,6 +1634,16 @@ async def import_all_db_configs() -> dict[str, bool]:
|
|||
logger.warning(f'Failed to import repos config: {e}')
|
||||
results['repos'] = False
|
||||
|
||||
# Zims (auto_search of each Zim; a rebuilt database gets the user's choices back)
|
||||
try:
|
||||
from modules.zim.lib import import_zims_config
|
||||
await asyncio.to_thread(import_zims_config)
|
||||
results['zims'] = True
|
||||
logger.debug('zims config imported')
|
||||
except Exception as e:
|
||||
logger.warning(f'Failed to import zims config: {e}')
|
||||
results['zims'] = False
|
||||
|
||||
# Map pins (YAML-only, no DB)
|
||||
try:
|
||||
from modules.map.pins import get_map_pins_config
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ def attach_shared_contexts(app: Sanic):
|
|||
app.shared_ctx.videos_downloader_config = manager.dict()
|
||||
app.shared_ctx.domains_config = manager.dict()
|
||||
app.shared_ctx.repos_config = manager.dict()
|
||||
app.shared_ctx.zims_config = manager.dict()
|
||||
app.shared_ctx.playlists_config = manager.dict()
|
||||
app.shared_ctx.archive_downloader_config = manager.dict()
|
||||
app.shared_ctx.download_cache_config = manager.dict()
|
||||
|
|
@ -131,6 +132,7 @@ def reset_shared_contexts(app: Sanic):
|
|||
app.shared_ctx.videos_downloader_config.clear()
|
||||
app.shared_ctx.domains_config.clear()
|
||||
app.shared_ctx.repos_config.clear()
|
||||
app.shared_ctx.zims_config.clear()
|
||||
app.shared_ctx.playlists_config.clear()
|
||||
app.shared_ctx.archive_downloader_config.clear()
|
||||
app.shared_ctx.download_cache_config.clear()
|
||||
|
|
@ -306,6 +308,12 @@ def initialize_configs_contexts(app: Sanic):
|
|||
except Exception as e:
|
||||
logger.error(f'Failed to initialize in-memory repos config: {e}')
|
||||
|
||||
try:
|
||||
from modules.zim.lib import zims_config
|
||||
zims_config.initialize(app.shared_ctx.zims_config)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to initialize in-memory zims config: {e}')
|
||||
|
||||
try:
|
||||
from wrolpi.collections.config import playlists_config
|
||||
playlists_config.initialize(app.shared_ctx.playlists_config)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue