From d34301a0858ed039533c472c6cf8f803705bb075 Mon Sep 17 00:00:00 2001 From: Roland Date: Thu, 26 Sep 2024 09:13:29 -0600 Subject: [PATCH] Configs are imported manually in main. Configs now have dump/save/import methods. Configs will refuse to save if they have not been imported. --- ...9ec4c765ef8d_remove_inventories_version.py | 40 ++ main.py | 56 ++- modules/archive/test/test_lib.py | 2 +- modules/inventory/__init__.py | 3 +- modules/inventory/api.py | 12 +- modules/inventory/common.py | 111 ++--- modules/inventory/inventory.py | 64 +-- modules/inventory/test/test_inventory.py | 46 +- modules/map/test/test_lib.py | 2 +- modules/videos/common.py | 2 - modules/videos/lib.py | 166 ++++---- modules/videos/test/test_common.py | 2 +- modules/zim/test/test_lib.py | 7 +- wrolpi/__init__.py | 20 - wrolpi/api_utils.py | 1 + wrolpi/common.py | 184 +++++--- wrolpi/conftest.py | 11 +- wrolpi/contexts.py | 8 +- wrolpi/downloader.py | 198 +++++---- wrolpi/files/test/test_api.py | 3 +- wrolpi/root_api.py | 50 +-- wrolpi/tags.py | 396 +++++++++--------- wrolpi/test/test_admin.py | 2 +- wrolpi/test/test_common.py | 75 +++- wrolpi/test/test_root_api.py | 8 +- wrolpi/test/test_tags.py | 9 +- 26 files changed, 796 insertions(+), 682 deletions(-) create mode 100644 alembic/versions/9ec4c765ef8d_remove_inventories_version.py diff --git a/alembic/versions/9ec4c765ef8d_remove_inventories_version.py b/alembic/versions/9ec4c765ef8d_remove_inventories_version.py new file mode 100644 index 00000000..cbd54f8d --- /dev/null +++ b/alembic/versions/9ec4c765ef8d_remove_inventories_version.py @@ -0,0 +1,40 @@ +"""Remove inventories version. + +Revision ID: 9ec4c765ef8d +Revises: d4e446637f18 +Create Date: 2024-09-24 16:01:41.716017 + +""" +import os + +from alembic import op +from sqlalchemy.orm import Session + +# revision identifiers, used by Alembic. +revision = '9ec4c765ef8d' +down_revision = 'd4e446637f18' +branch_labels = None +depends_on = None + +DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False + + +def upgrade(): + bind = op.get_bind() + session = Session(bind=bind) + + session.execute('DROP TABLE IF EXISTS inventories_version') + + +def downgrade(): + bind = op.get_bind() + session = Session(bind=bind) + + session.execute(''' + CREATE TABLE inventories_version ( + version SERIAL PRIMARY KEY NOT NULL + ) + ''') + + if not DOCKERIZED: + session.execute('ALTER TABLE public.inventories_version OWNER TO wrolpi') diff --git a/main.py b/main.py index e0ee085e..0bc26489 100755 --- a/main.py +++ b/main.py @@ -4,11 +4,15 @@ import asyncio import logging import os import sys +from contextlib import suppress from sanic import Sanic from sanic.signals import Event -from wrolpi import flags, BEFORE_STARTUP_FUNCTIONS, admin +from modules.inventory import init_inventory +from modules.inventory.common import import_inventories_config +from modules.videos.lib import import_channels_config +from wrolpi import flags, admin from wrolpi import root_api # noqa from wrolpi import tags from wrolpi.api_utils import api_app, perpetual_signal @@ -145,7 +149,7 @@ def main(): @api_app.main_process_ready -async def startup(app: Sanic): +async def main_process_startup(app: Sanic): """ Initializes multiprocessing tools, flags, etc. @@ -153,7 +157,7 @@ async def startup(app: Sanic): @warning: This is NOT run after auto-reload! You must stop and start Sanic. """ - logger.debug('startup') + logger.debug('main_process_startup') check_media_directory() @@ -163,7 +167,7 @@ async def startup(app: Sanic): # Initialize multiprocessing shared contexts before forking Sanic processes. attach_shared_contexts(app) - logger.debug('startup done') + logger.debug('main_process_startup done') @api_app.listener('after_server_start') # FileConfigs need to be initialized first. @@ -208,14 +212,34 @@ async def start_single_tasks(app: Sanic): return app.shared_ctx.single_tasks_started.set() - from modules.zim.lib import flag_outdated_zim_files - logger.debug(f'start_single_tasks started') + + # Import configs, ignore errors so the service will start. Configs will refuse to save if they failed to import. + with suppress(Exception): + get_wrolpi_config().import_config() + logger.debug('wrolpi config imported') + with suppress(Exception): + tags.import_tags_config() + logger.debug('tags config imported') + with suppress(Exception): + await import_downloads_config() + logger.debug('downloads config imported') + # Channels uses both downloads and tags. + with suppress(Exception): + import_channels_config() + logger.debug('channels config imported') + with suppress(Exception): + import_inventories_config() + logger.debug('inventories config imported') + with suppress(Exception): + init_inventory() + if get_wrolpi_config().download_on_startup: download_manager.enable() else: download_manager.disable() + from modules.zim.lib import flag_outdated_zim_files try: flag_outdated_zim_files() except Exception as e: @@ -225,10 +249,6 @@ async def start_single_tasks(app: Sanic): async with flags.db_up.wait_for(): logger.debug('start_single_tasks db is up') - tags.import_tags_config() - - await import_downloads_config() - if flags.refresh_complete.is_set(): # Set all downloads to new. download_manager.retry_downloads() @@ -253,19 +273,11 @@ async def start_single_tasks(app: Sanic): else: logger.info('CPU throttle on startup is disabled') - # Run the startup functions - for func in BEFORE_STARTUP_FUNCTIONS: - try: - logger.debug(f'Calling {func} before startup.') - func() - except Exception as e: - logger.warning(f'Startup {func} failed!', exc_info=e) - logger.debug(f'start_single_tasks done') @perpetual_signal(sleep=1) -async def periodic_check_log_level(): +async def perpetual_check_log_level(): """Copies global log level into this Sanic worker's logger.""" log_level = api_app.shared_ctx.log_level.value if log_level != logger.getEffectiveLevel(): @@ -297,7 +309,7 @@ async def perpetual_have_internet_worker(): @perpetual_signal(sleep=30) -async def periodic_start_video_missing_comments_download(): +async def perpetual_start_video_missing_comments_download(): from modules.videos.video.lib import get_missing_videos_comments async with flags.refresh_complete.wait_for(): @@ -310,10 +322,10 @@ async def periodic_start_video_missing_comments_download(): # Fetch comments for videos every hour. if download_manager.is_disabled or download_manager.is_stopped: logger.debug('Waiting for downloads to be enabled before downloading comments...') - await asyncio.sleep(10) + return elif not flags.have_internet.is_set(): logger.debug('Waiting for internet before downloading comments...') - await asyncio.sleep(30) + return else: try: await get_missing_videos_comments() diff --git a/modules/archive/test/test_lib.py b/modules/archive/test/test_lib.py index bd3ae8f7..130629d4 100644 --- a/modules/archive/test/test_lib.py +++ b/modules/archive/test/test_lib.py @@ -821,7 +821,7 @@ def test_get_url_from_singlefile(): @pytest.mark.asyncio -async def test_get_custom_archive_directory(async_client, test_directory, test_config): +async def test_get_custom_archive_directory(async_client, test_directory, test_wrolpi_config): """Custom directory can be used for archive directory.""" # Default location. assert lib.get_archive_directory() == (test_directory / 'archive') diff --git a/modules/inventory/__init__.py b/modules/inventory/__init__.py index f51bbc31..6c9f8199 100644 --- a/modules/inventory/__init__.py +++ b/modules/inventory/__init__.py @@ -7,8 +7,7 @@ from .models import Item, Inventory INVENTORY_INITIALIZED = False -@wrolpi.before_startup -def init(force=False): +def init_inventory(force=False): """ Initialize inventory categories, but only if none already exist. Initializes the inventories, but only if none already exist. diff --git a/modules/inventory/api.py b/modules/inventory/api.py index 545ee36e..d9275203 100644 --- a/modules/inventory/api.py +++ b/modules/inventory/api.py @@ -47,7 +47,7 @@ def get_inventory(_: Request, inventory_id: int): body=schema.InventoryPostRequest, ) @validate(schema.InventoryPostRequest) -@run_after(common.save_inventories_file) +@run_after(common.save_inventories_config) def post_inventory(_: Request, body: schema.InventoryPostRequest): data = remove_whitespace(body.__dict__) @@ -61,7 +61,7 @@ def post_inventory(_: Request, body: schema.InventoryPostRequest): body=schema.InventoryPutRequest, ) @validate(schema.InventoryPutRequest) -@run_after(common.save_inventories_file) +@run_after(common.save_inventories_config) def put_inventory(_: Request, inventory_id: int, body: schema.InventoryPutRequest): data = remove_whitespace(body.__dict__) @@ -71,7 +71,7 @@ def put_inventory(_: Request, inventory_id: int, body: schema.InventoryPutReques @inventory_bp.delete('/') @openapi.description('Delete an inventory.') -@run_after(common.save_inventories_file) +@run_after(common.save_inventories_config) def inventory_delete(_: Request, inventory_id: int): inventory.delete_inventory(inventory_id) return response.empty() @@ -90,7 +90,7 @@ def items_get(_: Request, inventory_id: int): body=schema.ItemPostRequest, ) @validate(schema.ItemPostRequest) -@run_after(common.save_inventories_file) +@run_after(common.save_inventories_config) def post_item(_: Request, inventory_id: int, body: schema.ItemPostRequest): data = remove_whitespace(body.__dict__) @@ -104,7 +104,7 @@ def post_item(_: Request, inventory_id: int, body: schema.ItemPostRequest): body=schema.ItemPutRequest, ) @validate(schema.ItemPutRequest) -@run_after(common.save_inventories_file) +@run_after(common.save_inventories_config) def put_item(_: Request, item_id: int, body: schema.ItemPutRequest): data = remove_whitespace(body.__dict__) @@ -115,7 +115,7 @@ def put_item(_: Request, item_id: int, body: schema.ItemPutRequest): @inventory_bp.delete('/item/', name='item_delete_many') @inventory_bp.delete('/item/', name='item_delete_one') @openapi.description('Delete items from an inventory.') -@run_after(common.save_inventories_file) +@run_after(common.save_inventories_config) def item_delete(_: Request, item_ids: str): try: if isinstance(item_ids, int): diff --git a/modules/inventory/common.py b/modules/inventory/common.py index c5498462..f8749149 100644 --- a/modules/inventory/common.py +++ b/modules/inventory/common.py @@ -1,3 +1,4 @@ +import pathlib from decimal import Decimal from functools import partial from pathlib import Path @@ -5,12 +6,10 @@ from typing import List, Tuple from pint import Quantity -from wrolpi import before_startup from wrolpi.common import logger, Base, ConfigFile from wrolpi.db import get_db_session -from .errors import NoInventories, InventoriesVersionMismatch -from .inventory import get_items, get_inventories, increment_inventories_version, \ - get_inventories_version, get_unit_registry +from .errors import NoInventories +from .inventory import get_items, get_inventories, get_unit_registry from .models import Inventory, Item MY_DIR: Path = Path(__file__).parent @@ -121,7 +120,7 @@ class InventoriesConfig(ConfigFile): file_name = 'inventories.yaml' default_config = dict( inventories=[], - version=1, + version=0, ) @property @@ -132,13 +131,56 @@ class InventoriesConfig(ConfigFile): def inventories(self, value: dict): self.update({'inventories': value}) - @property - def version(self) -> int: - return self._config['version'] + def dump_config(self, file: pathlib.Path = None): + inventories = [] + for inventory in get_inventories(): + inventories.append(inventory.dict()) - @version.setter - def version(self, value: int): - self.update({'version': value}) + if not inventories: + raise NoInventories('No Inventories are in the database!') + + self._config['inventories'] = inventories + super().dump_config(file) + + def import_config(self, file: pathlib.Path = None): + super().import_config(file) + + try: + with get_db_session(commit=True) as session: + db_inventories = get_inventories(session) + config_inventory_names = {i['name'] for i in self.inventories} + keep_inventories_names = [] + for inventory in db_inventories: + if inventory.name in config_inventory_names: + keep_inventories_names.append(inventory.name) + # TODO delete missing items, add new items. + else: + # Inventory was deleted from the config file. + inventory.delete() + continue + + new_inventories = [i for i in self.inventories if i['name'] not in keep_inventories_names] + for inventory_dict in new_inventories: + # New Inventory in config, copy it into the DB. + inventory = Inventory( + name=inventory_dict['name'], + created_at=inventory_dict['created_at'], + deleted_at=inventory_dict['deleted_at'], + ) + session.add(inventory) + # Get the Inventory from the DB so we can use its ID. + inventory.flush() + + for item in inventory_dict['items']: + del item['inventory_id'] + item = Item(inventory_id=inventory.id, **item) + item.inventory_id = inventory.id + session.add(item) + + self.successful_import = True + except Exception as e: + logger.error(f'Failed to import {self.file_name}', exc_info=e) + raise INVENTORIES_CONFIG: InventoriesConfig = InventoriesConfig() @@ -162,49 +204,10 @@ def set_test_inventories_config(enabled: bool): TEST_INVENTORIES_CONFIG = None -def save_inventories_file(): +def save_inventories_config(): """Write all inventories and their respective items to a WROLPi Config file.""" - config = get_inventories_config() - - inventories = [] - for inventory in get_inventories(): - inventories.append(inventory.dict()) - - if not inventories: - raise NoInventories('No Inventories are in the database!') - - with increment_inventories_version() as version: - if config.version and config.version > version: - raise InventoriesVersionMismatch( - f'Inventories config version is {config.version} but DB version is {get_inventories_version()}') - - config.inventories = inventories - config.version = version - config.background_save.activate_switch() + get_inventories_config().background_dump.activate_switch() -@before_startup -def import_inventories_file(): - config = get_inventories_config() - - inventories = get_inventories() - inventories_names = {i.name for i in inventories} - new_inventories = [i for i in config.inventories if i['name'] not in inventories_names] - with get_db_session(commit=True) as session: - for inventory in new_inventories: - items = inventory['items'] - inventory = Inventory( - name=inventory['name'], - created_at=inventory['created_at'], - deleted_at=inventory['deleted_at'], - ) - session.add(inventory) - # Get the Inventory from the DB so we can use it's ID. - session.flush() - session.refresh(inventory) - - for item in items: - del item['inventory_id'] - item = Item(inventory_id=inventory.id, **item) - item.inventory_id = inventory.id - session.add(item) +def import_inventories_config(): + get_inventories_config().import_config() diff --git a/modules/inventory/inventory.py b/modules/inventory/inventory.py index 91208440..5604a243 100644 --- a/modules/inventory/inventory.py +++ b/modules/inventory/inventory.py @@ -1,4 +1,3 @@ -import contextlib from functools import partial from operator import itemgetter from typing import List, Tuple @@ -6,12 +5,11 @@ from typing import List, Tuple import pint import psycopg2 from sqlalchemy.orm import Session -from sqlalchemy.orm.exc import NoResultFound from wrolpi.common import logger, Base -from wrolpi.db import get_db_session, get_db_curs +from wrolpi.db import get_db_session, get_db_curs, optional_session from wrolpi.errors import APIError -from .models import Inventory, Item, InventoriesVersion +from .models import Inventory, Item logger = logger.getChild(__name__) @@ -23,11 +21,8 @@ __all__ = [ 'get_brands', 'get_categories', 'get_inventories', - 'get_inventories_version', 'get_items', - 'get_next_inventories_version', 'get_unit_registry', - 'increment_inventories_version', 'logger', 'save_inventory', 'save_item', @@ -90,15 +85,15 @@ DEFAULT_INVENTORIES = [ sort_categories = partial(sorted, key=itemgetter(1, 0)) -def get_inventories() -> List[Inventory]: - with get_db_session() as session: - inventories = session.query(Inventory).filter( - Inventory.deleted_at == None, # noqa - ).order_by( - Inventory.viewed_at.desc(), - ).all() - inventories = list(inventories) - return inventories +@optional_session +def get_inventories(session: Session = None) -> List[Inventory]: + inventories = session.query(Inventory).filter( + Inventory.deleted_at == None, # noqa + ).order_by( + Inventory.viewed_at.desc(), + ).all() + inventories = list(inventories) + return inventories IGNORED_INVENTORY_KEYS = {'viewed_at', 'created_at', 'deleted_at'} @@ -210,40 +205,3 @@ def delete_items(items_ids: List[int]): deleted_ids = {i['id'] for i in curs.fetchall()} if set(items_ids) != deleted_ids: raise APIError('Could not delete the items') - - -def get_inventories_version(): - """ - The inventory_version table contains a single row with the Inventories version integer. - """ - with get_db_session() as session: - try: - version = session.query(InventoriesVersion).one() - return version.version - except NoResultFound: - # No version is saved yet. - pass - - -def get_next_inventories_version(): - """ - Get the current inventories version, increment it if there is one. - """ - version = get_inventories_version() - if version: - return version + 1 - return 1 - - -@contextlib.contextmanager -def increment_inventories_version(): - """ - Context manager that will increment the Inventories Version by 1 when exiting. - """ - version = get_next_inventories_version() - yield version - with get_db_session(commit=True) as session: - if session.query(InventoriesVersion).count() == 0: - session.add(InventoriesVersion(version=version)) - else: - session.query(InventoriesVersion).one().version = version diff --git a/modules/inventory/test/test_inventory.py b/modules/inventory/test/test_inventory.py index fbe0fa01..fd45ba90 100644 --- a/modules/inventory/test/test_inventory.py +++ b/modules/inventory/test/test_inventory.py @@ -4,17 +4,16 @@ from typing import List, Iterable import pytest import sqlalchemy -import yaml from pint import Quantity from wrolpi.common import Base from wrolpi.db import get_db_session from wrolpi.switches import await_switches from wrolpi.test.common import PytestCase -from .. import init +from .. import init_inventory from ..common import sum_by_key, get_inventory_by_category, get_inventory_by_subcategory, get_inventory_by_name, \ - compact_unit, cleanup_quantity, save_inventories_file, import_inventories_file, get_inventories_config -from ..errors import NoInventories, InventoriesVersionMismatch + compact_unit, cleanup_quantity, save_inventories_config, import_inventories_config +from ..errors import NoInventories from ..inventory import get_inventories, save_inventory, update_inventory, \ delete_inventory, get_categories, get_unit_registry from ..models import Item, Inventory @@ -67,7 +66,7 @@ class TestInventory(PytestCase): """ This exists rather than setUp because the DB is wrapped. """ - init(force=True) + init_inventory(force=True) with get_db_session(commit=True) as session: for item in TEST_ITEMS: @@ -266,42 +265,14 @@ def test_sum_by_key(items, expected): assert sum_by_key(items, lambda i: (i.category,)) == expected -def test_no_inventories(test_session, test_directory): +def test_no_inventories(async_client, test_session, test_directory): """Can't save empty inventories.""" try: - save_inventories_file() + save_inventories_config() except NoInventories: pass -@pytest.mark.asyncio -async def test_inventories_version(async_client, test_session, test_directory, init_test_inventory): - """You can't save over a newer version of an inventory.""" - config = get_inventories_config() - - for item in TEST_ITEMS: - item = Item(**item) - test_session.add(item) - test_session.commit() - - # Version is set to 1 on first save. - save_inventories_file() - await await_switches() - assert config.version == 1 - - # Version is incremented when saving. - save_inventories_file() - await await_switches() - assert config.version == 2 - - # Version is greater than what will be saved. - with config.get_file().open('wt') as fh: - config._config['version'] = 5 - yaml.dump(config._config, fh) - with pytest.raises(InventoriesVersionMismatch): - save_inventories_file() - - @pytest.mark.asyncio async def test_inventories_config(async_client, test_session, test_directory, init_test_inventory): for item in TEST_ITEMS: @@ -310,14 +281,15 @@ async def test_inventories_config(async_client, test_session, test_directory, in test_session.commit() # Save the Inventories/Items that were created above. - save_inventories_file() + save_inventories_config() + await await_switches() # Clear out the DB so the import will be tested test_session.query(Item).delete() test_session.query(Inventory).delete() test_session.commit() - import_inventories_file() + import_inventories_config() inventories = get_inventories() assert len(inventories) == 1 diff --git a/modules/map/test/test_lib.py b/modules/map/test/test_lib.py index a1ed847b..be7c7121 100644 --- a/modules/map/test/test_lib.py +++ b/modules/map/test/test_lib.py @@ -102,7 +102,7 @@ def test_seconds_to_import_rpi5(size, expected): assert lib.seconds_to_import(size, True) == expected -def test_get_custom_map_directory(test_directory, test_config): +def test_get_custom_map_directory(test_directory, test_wrolpi_config): """Custom directory can be used for map directory.""" # Default location. assert lib.get_map_directory() == (test_directory / 'map') diff --git a/modules/videos/common.py b/modules/videos/common.py index 9ba724f2..03862799 100644 --- a/modules/videos/common.py +++ b/modules/videos/common.py @@ -26,8 +26,6 @@ from .models import Channel logger = logger.getChild(__name__) -REQUIRED_OPTIONS = ['name', 'directory'] - class ConfigError(Exception): pass diff --git a/modules/videos/lib.py b/modules/videos/lib.py index d6329cb7..68720c48 100644 --- a/modules/videos/lib.py +++ b/modules/videos/lib.py @@ -12,10 +12,10 @@ from sqlalchemy.orm import Session from yt_dlp import YoutubeDL from modules.videos.models import Video -from wrolpi import before_startup, dates, flags +from wrolpi import dates, flags from wrolpi.captions import extract_captions -from wrolpi.common import ConfigFile, limit_concurrent, get_wrolpi_config, extract_domain, \ - escape_file_name, get_media_directory, background_task, Base +from wrolpi.common import ConfigFile, extract_domain, \ + escape_file_name, get_media_directory, background_task, Base, get_wrolpi_config from wrolpi.dates import Seconds, from_timestamp from wrolpi.db import get_db_curs, get_db_session from wrolpi.downloader import Download @@ -24,7 +24,7 @@ from wrolpi.files.lib import split_path_stem_and_suffix from wrolpi.switches import register_switch_handler, ActivateSwitchMethod from wrolpi.vars import YTDLP_CACHE_DIR, PYTEST from .common import is_valid_poster, convert_image, \ - generate_video_poster, logger, REQUIRED_OPTIONS, ConfigError, \ + generate_video_poster, logger, ConfigError, \ get_video_duration from .errors import UnknownChannel from .models import Channel @@ -33,6 +33,8 @@ logger = logger.getChild(__name__) DEFAULT_DOWNLOAD_FREQUENCY = Seconds.week +REQUIRED_OPTIONS = ['name', 'directory'] + @dataclasses.dataclass class VideoInfoJSON: @@ -214,6 +216,7 @@ class ChannelsConfig(ConfigFile): directory='videos/wrolpi', download_frequency=604800, )], + version=0, ) @property @@ -224,6 +227,80 @@ class ChannelsConfig(ConfigFile): def channels(self, value: dict): self.update({'channels': value}) + def import_config(self, file: pathlib.Path = None): + from modules.videos.channel.lib import get_channel + super().import_config() + try: + channels = self.channels + channel_directories = [i['directory'] for i in channels] + if len(channel_directories) != len(set(channel_directories)): + raise RuntimeError('Refusing to import channels config because it contains duplicate directories!') + updated_channel_ids = set() + + with get_db_session(commit=True) as session: + for data in channels: + # A Channel's directory is saved (in config) relative to the media directory. + directory = get_media_directory() / data['directory'] + for option in (i for i in REQUIRED_OPTIONS if i not in data): + raise ConfigError(f'Channel "{directory}" is required to have "{option}"') + + # Try to find Channel by directory because it is unique. + channel = Channel.get_by_path(directory, session) + if not channel: + try: + # Try to find Channel using other attributes before creating new Channel. + channel = get_channel( + session, + source_id=data.get('source_id'), + url=data.get('url'), + directory=str(directory), + return_dict=False, + ) + except UnknownChannel: + # Channel not yet in the DB, add it. + channel = Channel(directory=directory) + session.add(channel) + channel.flush() + # TODO refresh the files in the channel. + logger.warning(f'Creating new Channel from config {channel}') + + # Copy existing channel data, update all values from the config. This is necessary to clear out + # values not in the config. + full_data = channel.dict() + full_data.update(data) + channel.update(full_data) + updated_channel_ids.add(channel.id) + + if not channel.source_id and channel.url and flags.have_internet.is_set(): + # If we can download from a channel, we must have its source_id. + logger.info(f'Fetching channel source id for {channel}') + background_task(fetch_channel_source_id(channel.id)) + + channel_import_logger.debug(f'Updated {repr(channel.name)}' + f' url={channel.url}' + f' source_id={channel.source_id}' + f' directory={channel.directory}' + ) + + with get_db_session(commit=True) as session: + # Delete any Channels that were deleted from the config. + for channel in session.query(Channel): + if channel.id not in updated_channel_ids: + logger.warning(f'Deleting {channel} because it is not in the config.') + channel.delete_with_videos() + + # Create any missing Downloads. Associated Downloads with any necessary Channels. + with get_db_session() as session: + link_channel_and_downloads(session) + + self.successful_import = True + channel_import_logger.info('Importing channels config complete') + except Exception as e: + channel_import_logger.warning('Failed to load channels config!', exc_info=e) + if PYTEST: + # Do not interrupt startup, only raise during testing. + raise + CHANNELS_CONFIG: ChannelsConfig = ChannelsConfig() TEST_CHANNELS_CONFIG: ChannelsConfig = None @@ -259,6 +336,7 @@ class VideoDownloaderConfig(ConfigFile): file_name_format='%(uploader)s_%(upload_date)s_%(id)s_%(title)s.%(ext)s', nooverwrites=True, quiet=False, + version=0, writeautomaticsub=True, writeinfojson=True, writesubtitles=True, @@ -408,91 +486,15 @@ async def fetch_channel_source_id(channel_id: int): logger.error(f'Failed to get Channel source id of id={channel_id}', exc_info=e) -@before_startup -@limit_concurrent(1) def import_channels_config(): """Import channel settings to the DB. Existing channels will be updated.""" if PYTEST and not get_channels_config(): logger.warning('Skipping import_channels_config for this test') return - from .channel.lib import get_channel channel_import_logger.info('Importing channels config') - try: - config = get_channels_config() - channels = config.channels - channel_directories = [i['directory'] for i in channels] - if len(channel_directories) != len(set(channel_directories)): - logger.error('Refusing to import channels config because it contains duplicate directories!') - return - updated_channel_ids = set() - - with get_db_session(commit=True) as session: - for data in channels: - if isinstance(data, str): - # Outdated style config. - # TODO remove this after beta. - data = channels[data] - # A Channel's directory is saved (in config) relative to the media directory. - directory = get_media_directory() / data['directory'] - for option in (i for i in REQUIRED_OPTIONS if i not in data): - raise ConfigError(f'Channel "{directory}" is required to have "{option}"') - - # Try to find Channel by directory because it is unique. - channel = Channel.get_by_path(directory, session) - if not channel: - try: - # Try to find Channel using other attributes before creating new Channel. - channel = get_channel( - session, - source_id=data.get('source_id'), - url=data.get('url'), - directory=str(directory), - return_dict=False, - ) - except UnknownChannel: - # Channel not yet in the DB, add it. - channel = Channel(directory=directory) - session.add(channel) - channel.flush() - # TODO refresh the files in the channel. - logger.warning(f'Creating new Channel from config {channel}') - - # Copy existing channel data, update all values from the config. This is necessary to clear out - # values not in the config. - full_data = channel.dict() - full_data.update(data) - channel.update(full_data) - updated_channel_ids.add(channel.id) - - if not channel.source_id and channel.url and flags.have_internet.is_set(): - # If we can download from a channel, we must have its source_id. - logger.info(f'Fetching channel source id for {channel}') - background_task(fetch_channel_source_id(channel.id)) - - channel_import_logger.debug(f'Updated {repr(channel.name)}' - f' url={channel.url}' - f' source_id={channel.source_id}' - f' directory={channel.directory}' - ) - - with get_db_session(commit=True) as session: - # Delete any Channels that were deleted from the config. - for channel in session.query(Channel): - if channel.id not in updated_channel_ids: - logger.warning(f'Deleting {channel} because it is not in the config.') - channel.delete_with_videos() - - # Create any missing Downloads. Associated Downloads with any necessary Channels. - with get_db_session() as session: - link_channel_and_downloads(session) - - channel_import_logger.info('Importing channels config complete') - except Exception as e: - channel_import_logger.warning('Failed to load channels config!', exc_info=e) - if PYTEST: - # Do not interrupt startup, only raise during testing. - raise + get_channels_config().import_config() + channel_import_logger.info('Importing channels config completed') def link_channel_and_downloads(session: Session, channel_: Type[Base] = Channel): diff --git a/modules/videos/test/test_common.py b/modules/videos/test/test_common.py index f4fff178..e6a93f3c 100644 --- a/modules/videos/test/test_common.py +++ b/modules/videos/test/test_common.py @@ -324,7 +324,7 @@ def test_get_videos_directory(test_directory): assert (test_directory / 'videos').is_dir() -def test_get_custom_videos_directory(test_directory, test_config): +def test_get_custom_videos_directory(test_directory, test_wrolpi_config): """Custom directory can be used for videos directory.""" config = get_wrolpi_config() config.videos_destination = 'custom/directory/videos' diff --git a/modules/zim/test/test_lib.py b/modules/zim/test/test_lib.py index 3555d035..2fd44553 100644 --- a/modules/zim/test/test_lib.py +++ b/modules/zim/test/test_lib.py @@ -267,17 +267,18 @@ async def test_zim_tag_migration(async_client, test_session, test_directory, zim test_session.commit() assert test_session.query(TagZimEntry).count() == 4 await await_switches() + assert tags.get_tags_config().successful_import is True # All Zims have been tagged. tags_config = tags.get_tags_config() - tags_config.save_tags(session=test_session) + tags_config.dump_config() assert 'wikipedia_en_all_maxi_2020-01.zim' in (config_text := tags_config.get_file().read_text()) assert 'wikipedia_en_all_maxi_2020-02.zim' in config_text assert 'wikipedia_en_all_maxi_2020-03.zim' in config_text # Zim was deleted, as well as it's ZimTagEntry(s). zim1.delete() - tags.import_tags_config(test_session) + tags.import_tags_config() tag_zim_entries = sorted([(i.tag.name, i.zim.path, i.zim_entry) for i in test_session.query(TagZimEntry)]) assert tag_zim_entries == [ @@ -390,7 +391,7 @@ async def test_zim_modeler(test_session, zim_factory): assert fg.a_text == 'the zim title' -def test_get_custom_zims_directory(test_directory, test_config): +def test_get_custom_zims_directory(test_directory, test_wrolpi_config): """Custom directory can be used for zims directory.""" assert lib.get_zim_directory() == (test_directory / 'zims') diff --git a/wrolpi/__init__.py b/wrolpi/__init__.py index 0bcb7fa7..587e215d 100644 --- a/wrolpi/__init__.py +++ b/wrolpi/__init__.py @@ -1,23 +1,3 @@ import wrolpi.files.api # noqa Import from files so the blueprint is attached. import wrolpi.scrape_downloader # noqa import wrolpi.status # noqa - -BEFORE_STARTUP_FUNCTIONS = [] - - -def before_startup(func: callable): - """ - Run a callable before startup of the WROLPi API. This will be called (and blocked on) once. - """ - if func not in BEFORE_STARTUP_FUNCTIONS: - BEFORE_STARTUP_FUNCTIONS.append(func) - return func - - -def after_startup(func: callable): - """ - Run a function after the startup of the WROLPi Sanic API. This will be run for each process! - """ - from wrolpi.api_utils import api_app - api_app.after_server_start(func) - return func diff --git a/wrolpi/api_utils.py b/wrolpi/api_utils.py index f325935b..a316e76c 100644 --- a/wrolpi/api_utils.py +++ b/wrolpi/api_utils.py @@ -120,6 +120,7 @@ async def start_perpetual_tasks(app: Sanic): if app.shared_ctx.perpetual_tasks_started.is_set(): return logger.info('start_perpetual_tasks started') + logger.debug(f'start_perpetual_tasks: {PERPETUAL_WORKERS}') app.shared_ctx.perpetual_tasks_started.set() try: diff --git a/wrolpi/common.py b/wrolpi/common.py index 4ef5c99a..e7eb8a3c 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -338,13 +338,13 @@ def get_media_directory() -> Path: return MEDIA_DIRECTORY -TESTING_SKIP_BACKUP = False - - class ConfigFile: """ - This class keeps track of the contents of a config file. You can update the config (and it's file) by - calling .update(). + This is used to keep the DB and config files in sync. Importing the config reads the config from file, then + applies it to this config instance, AND the database. Dumping the config copies data from the database and saves it + to the config file. Updating this config is automatically saved to the config file. + + Configs cannot be saved until they are imported without error. """ file_name: str = None default_config: dict = None @@ -357,6 +357,9 @@ class ConfigFile: # Do not load a global config on import while testing. A global instance should never be used for testing. self._config = self.default_config.copy() + if self._config['version'] != 0: + raise RuntimeError('Configs should start at version 0') + from wrolpi.switches import register_switch_handler @register_switch_handler(f'background_save_{self.file_name}') @@ -365,6 +368,12 @@ class ConfigFile: self.background_save = background_save + @register_switch_handler(f'background_dump_{self.file_name}') + def background_dump(file: pathlib.Path = None): + self.dump_config(file) + + self.background_dump = background_dump + def __repr__(self): return f'<{self.__class__.__name__} file={self.get_file()}>' @@ -375,14 +384,30 @@ class ConfigFile: # Use the default settings to initialize the config. self._config.update(deepcopy(self.default_config)) - config_file = self.get_file() - if config_file.is_file(): - # Use the config file to get the values the user set. - with config_file.open('rt') as fh: - config_data = yaml.load(fh, Loader=yaml.Loader) - self._config.update(config_data) + file = self.get_file() + if file.is_file(): + config_data = {k: v for k, v in self.read_config_file(file).items() if k in self.default_config} + self._config.update(config_data) return self + @property + def successful_import(self) -> bool: + from wrolpi.api_utils import api_app + return bool(api_app.shared_ctx.configs_imported.get(self.file_name)) + + @successful_import.setter + def successful_import(self, value: bool): + from wrolpi.api_utils import api_app + api_app.shared_ctx.configs_imported[self.file_name] = value + + def read_config_file(self, file: pathlib.Path = None) -> Dict: + file = file or self.get_file() + with file.open('rt') as fh: + config_data = yaml.load(fh, Loader=yaml.Loader) + if not isinstance(config_data, dict): + raise RuntimeError(f'Config file is invalid: {file}') + return config_data + def _get_backup_filename(self): """Returns the path for the backup file for today.""" # TODO what if the RPi clock is not working? Change this so the "version" of the config is used each day. @@ -392,61 +417,67 @@ class ConfigFile: path = path.with_name(name) return path - def save(self): + def save(self, file: pathlib.Path = None): """ Write this config to its file. - - Use the existing config file as a template; if any values are missing in the new config, use the values from the - config file. """ from wrolpi.api_utils import api_app - config_file = self.get_file() - logger_.debug(f'Save config called for {config_file}') + file = file or self.get_file() + if self.file_name not in file.name: + raise RuntimeError(f'Refusing to save config to file which does not match {self.__class__.__name__}') + + rel_path = get_relative_to_media_directory(file) + + if file.exists(): + if not self.successful_import: + raise RuntimeError(f'Refusing to save config because it was never successfully imported! {rel_path}') + version = self.read_config_file(file).get('version') + if version and version > self.version: + raise RuntimeError(f'Refusing to overwrite newer config ({rel_path}): ' + f'{version} > {self.version}') + # Don't overwrite a real config while testing. - if PYTEST and not str(config_file).startswith('/tmp'): - raise ValueError(f'Refusing to save config file while testing: {config_file}') + if PYTEST and not str(file).startswith('/tmp'): + raise ValueError(f'Refusing to save config file while testing: {rel_path}') + + logger_.debug(f'Save config called for {rel_path}') # Only one process can write to a config. - lock = api_app.shared_ctx.config_save_lock - acquired = lock.acquire(block=True, timeout=5.0) + with api_app.shared_ctx.config_save_lock: + try: + # Config directory may not exist. + if not file.parent.is_dir(): + file.parent.mkdir() - try: - # Config directory may not exist. - if not config_file.parent.is_dir(): - config_file.parent.mkdir() - - backup_file = self._get_backup_filename() - - # Read the existing config, replace all values, then save. - if config_file.is_file(): - with config_file.open('rt') as fh: - config = yaml.load(fh, Loader=yaml.Loader) - # Skip backups when testing when the test needs it. - if not PYTEST or TESTING_SKIP_BACKUP is False: - # Copy the existing config to the backup directory. One for each day. + # Backup the existing config file. + if file.is_file(): + backup_file = self._get_backup_filename() if not backup_file.parent.exists(): backup_file.parent.mkdir(parents=True) - shutil.copy(config_file, backup_file) - logger_.debug(f'Copied backup config: {config_file} -> {backup_file}') - else: - # Config file does not yet exist. - config = dict() + shutil.copy(file, backup_file) + logger_.debug(f'Copied backup config: {rel_path} -> {backup_file}') - config.update({k: v for k, v in self._config.items() if v is not None}) - with config_file.open('wt') as fh: - yaml.dump(config, fh, width=self.width, sort_keys=True) - # Wait for data to be written before releasing lock. - fh.flush() - os.fsync(fh.fileno()) - logger_.info(f'Saved config: {config_file}') - except Exception as e: - # Configs are vital, raise a big error when this fails. - logger_.critical(f'Failed to save config: {config_file}', exc_info=e) - raise e - finally: - if acquired: - lock.release() + # Write the config in-memory to the file. Track version changes to avoid overriding newer config. + self._config['version'] += 1 + config = deepcopy(self._config) + self.write_config_data(config, file) + + # Set successful_import in case this was the first time the config was written. + self.successful_import = True + + logger_.info(f'Saved config: {rel_path}') + except Exception as e: + # Configs are vital, raise a big error when this fails. + logger_.critical(f'Failed to save config: {rel_path}', exc_info=e) + raise e + + def write_config_data(self, config: dict, config_file: pathlib.Path): + with config_file.open('wt') as fh: + yaml.dump(config, fh, width=self.width, sort_keys=True) + # Wait for data to be written before releasing lock. + fh.flush() + os.fsync(fh.fileno()) def get_file(self) -> Path: if not self.file_name: @@ -457,10 +488,33 @@ class ConfigFile: return CONFIG_DIR / self.file_name - def update(self, config: dict, ignore_lock: bool = False): + def import_config(self, file: pathlib.Path = None): + """Read config file data, apply it to the in-memory config and database.""" + file = file or self.get_file() + file_str = str(get_relative_to_media_directory(file)) + if file.is_file(): + data = self.read_config_file(file) + new_data, extra_data = partition(lambda i: i[0] in self.default_config, data.items()) + new_data, extra_data = dict(new_data), dict(extra_data) + if extra_data: + logger_.warning(f'Ignoring extra config data ({file_str}): {extra_data}') + self._config.update(new_data) + # Import call above this will set successful_import. + # self.successful_import = True + else: + logger_.error(f'Failed to import {file_str} because it does not exist.') + + def dump_config(self, file: pathlib.Path = None): + """Dump database data, copy it to this the in-memory config, then write it to the config file.""" + # Copy the data as-is by default. Other classes will overwrite this and dump the database before saving. + self.save(file) + + def update(self, config: dict): """Update any values of this config. Save the config to its file.""" - config = {k: v for k, v in config.items() if k in self._config} - self._config.update(config) + from wrolpi.api_utils import api_app + with api_app.shared_ctx.config_update_lock: + config = {k: v for k, v in config.items() if k in self._config} + self._config.update(config) self.background_save.activate_switch() def dict(self) -> dict: @@ -470,6 +524,12 @@ class ConfigFile: return deepcopy(self._config) + # `version` is used to prevent overwriting of newer configs. Cannot not be modified directly. + + @property + def version(self) -> int: + return self._config['version'] + class WROLPiConfig(ConfigFile): file_name = 'wrolpi.yaml' @@ -486,6 +546,7 @@ class WROLPiConfig(ConfigFile): map_destination='map', nav_color='violet', throttle_on_startup=False, + version=0, videos_destination='videos/%(channel_tag)s/%(channel_name)s', wrol_mode=False, zims_destination='zims', @@ -512,6 +573,15 @@ class WROLPiConfig(ConfigFile): # Not testing, and can't find file deep in media directory. Use the default. return default_config_path + def import_config(self, file: pathlib.Path = None): + try: + super().import_config(file) + # WROLPiConfig does not sync to database. + self.successful_import = True + except Exception as e: + logger.error(f'Failed to import {self.file_name}', exc_info=e) + raise + @property def download_on_startup(self) -> bool: return self._config['download_on_startup'] diff --git a/wrolpi/conftest.py b/wrolpi/conftest.py index ebeeff3a..b8e61780 100644 --- a/wrolpi/conftest.py +++ b/wrolpi/conftest.py @@ -120,7 +120,7 @@ def test_directory() -> pathlib.Path: @pytest.fixture -def test_config(test_directory) -> pathlib.Path: +def test_wrolpi_config(test_directory) -> pathlib.Path: """ Create a test config based off the example config. """ @@ -130,13 +130,6 @@ def test_config(test_directory) -> pathlib.Path: set_test_config(False) -@pytest.fixture -def skip_config_backups(): - """Do not backup configs during testing.""" - with mock.patch('wrolpi.common.TESTING_SKIP_BACKUP', True): - yield - - ROUTES_ATTACHED = False @@ -468,7 +461,7 @@ async def set_wrol_mode(enabled: bool): @pytest.fixture -def wrol_mode_fixture(test_config, test_download_manager) -> Callable[[bool], Coroutine]: +def wrol_mode_fixture(test_wrolpi_config, test_download_manager) -> Callable[[bool], Coroutine]: return set_wrol_mode diff --git a/wrolpi/contexts.py b/wrolpi/contexts.py index ece31ef0..d42c11ea 100644 --- a/wrolpi/contexts.py +++ b/wrolpi/contexts.py @@ -30,7 +30,6 @@ def attach_shared_contexts(app: Sanic): app.shared_ctx.uploaded_files = manager.dict() app.shared_ctx.status = manager.dict() app.shared_ctx.map_importing = manager.dict() - # Shared lists. # Shared ints app.shared_ctx.log_level = multiprocessing.Value(ctypes.c_int, LOG_LEVEL_INT) @@ -52,8 +51,10 @@ def attach_shared_contexts(app: Sanic): # Warnings app.shared_ctx.warn_once = manager.dict() - # Locks + # Configs app.shared_ctx.config_save_lock = multiprocessing.Lock() + app.shared_ctx.config_update_lock = multiprocessing.Lock() + app.shared_ctx.configs_imported = manager.dict() # Events. app.shared_ctx.events_lock = multiprocessing.Lock() @@ -95,6 +96,9 @@ def reset_shared_contexts(app: Sanic): killed_downloads=[], )) + # Configs + app.shared_ctx.configs_imported.clear() + # Switches app.shared_ctx.switches.clear() app.shared_ctx.switches_changed.clear() diff --git a/wrolpi/downloader.py b/wrolpi/downloader.py index ee0d991a..82d2608b 100644 --- a/wrolpi/downloader.py +++ b/wrolpi/downloader.py @@ -27,7 +27,7 @@ from wrolpi import flags from wrolpi.api_utils import api_app, perpetual_signal from wrolpi.cmd import pid_is_running from wrolpi.common import Base, ModelHelper, logger, wrol_mode_check, zig_zag, ConfigFile, WROLPI_CONFIG, \ - limit_concurrent, wrol_mode_enabled, background_task + wrol_mode_enabled, background_task from wrolpi.dates import TZDateTime, now, Seconds from wrolpi.db import get_db_session, get_db_curs, optional_session from wrolpi.errors import InvalidDownload, UnrecoverableDownloadError, UnknownDownload @@ -42,12 +42,16 @@ async def perpetual_download_worker(): async with flags.db_up.wait_for(): pass - async with flags.have_internet.wait_for(timeout=5): - pass - if download_manager.is_stopped: return + try: + async with flags.have_internet.wait_for(timeout=5): + pass + except TimeoutError: + # Internet is not up. + return + await download_manager.do_downloads() @@ -1142,8 +1146,9 @@ async def signal_download_download(download_id: int, download_url: str): class DownloadManagerConfig(ConfigFile): file_name = 'download_manager.yaml' default_config = dict( - skip_urls=[], downloads=[], + skip_urls=[], + version=0, ) @property @@ -1162,6 +1167,99 @@ class DownloadManagerConfig(ConfigFile): def downloads(self, value: List[dict]): self.update({'downloads': value}) + def dump_config(self, file: pathlib.Path = None): + with get_db_session() as session: + downloads: Iterable[Download] = session.query(Download).order_by(Download.url) + new_downloads = [] + for download in downloads: + if download.last_successful_download and not download.frequency: + # This once-download has completed, do not save it. + continue + new_downloads.append(dict( + downloader=download.downloader, + frequency=download.frequency, + last_successful_download=download.last_successful_download, + next_download=download.next_download, + settings=download.settings, + status=download.status, + sub_downloader=download.sub_downloader, + url=download.url, + )) + get_download_manager_config().downloads = new_downloads + + def import_config(self, file: pathlib.Path = None): + super().import_config(file) + with get_db_session(commit=True) as session: + from modules.zim.lib import zim_download_url_to_name + from modules.zim.models import ZimSubscription + + try: + logger.warning('Importing downloads in config') + + downloads_by_url = {i['url']: i for i in get_download_manager_config().downloads} + existing_downloads: List[Download] = list(session.query(Download)) + for existing in existing_downloads: + download = downloads_by_url.pop(existing.url, None) + if download: + # Download in config already exists, update the DB record. + # The config is the source of truth. + existing.downloader = download['downloader'] + existing.frequency = download['frequency'] + existing.last_successful_download = download['last_successful_download'] + existing.next_download = download['next_download'] + existing.status = download['status'] + existing.sub_downloader = download['sub_downloader'] + existing.settings = download.get('settings') or dict() + existing.flush() + else: + logger.warning(f'Deleting Download {existing.url} because it is no longer in the config') + session.delete(existing) + + for download in downloads_by_url.values(): + # These downloads are new, import them. + download = Download( + downloader=download['downloader'], + frequency=download['frequency'], + last_successful_download=download['last_successful_download'], + next_download=download['next_download'], + settings=download['settings'] or dict(), + status=download['status'], + sub_downloader=download['sub_downloader'], + url=(url := download['url']), + ) + session.add(download) + logger.info(f'Adding new download {url}') + + session.commit() + except Exception as e: + logger.error('Failed to import downloads', exc_info=e) + raise + + try: + # Claim any Kiwix subscriptions for ZimSubscription(s). + downloads: List[Download] = session.query(Download) + need_commit = False + for download in downloads: + if not download.url.startswith('https://download.kiwix.org/') or not download.frequency: + # ZimSubscription requires download.kiwix.org AND a frequency. + continue + + name, language = zim_download_url_to_name(download.url) + subscription = session.query(ZimSubscription).filter_by(name=name, language=language).one_or_none() + if not subscription: + subscription = ZimSubscription(name=name, language=language) + subscription.change_download(download.url, download.frequency, session=session) + session.add(subscription) + need_commit = True + + if need_commit: + session.commit() + except Exception as e: + logger.error('Failed to restore ZimSubscriptions', exc_info=e) + raise + + self.successful_import = True + DOWNLOAD_MANAGER_CONFIG: DownloadManagerConfig = DownloadManagerConfig() TEST_DOWNLOAD_MANAGER_CONFIG: DownloadManagerConfig = None @@ -1188,26 +1286,7 @@ def get_download_manager_config() -> DownloadManagerConfig: @register_switch_handler('save_downloads_config') def save_downloads_config(): """Fetch all Downloads from the DB, save them to the Download Manager Config.""" - with get_db_session() as session: - downloads: Iterable[Download] = session.query(Download).order_by(Download.url) - config = [] - for download in downloads: - if download.last_successful_download and not download.frequency: - # This once-download has completed, do not save it. - continue - config.append(dict( - downloader=download.downloader, - frequency=download.frequency, - last_successful_download=download.last_successful_download, - next_download=download.next_download, - settings=download.settings, - status=download.status, - sub_downloader=download.sub_downloader, - url=download.url, - )) - if config != get_download_manager_config().downloads: - # Only save if there are changes. - get_download_manager_config().downloads = config + get_download_manager_config().dump_config() logger.info('save_downloads_config completed') @@ -1215,7 +1294,6 @@ save_downloads_config: ActivateSwitchMethod @optional_session -@limit_concurrent(1) async def import_downloads_config(session: Session): """Upsert all Downloads in the Download Manager Config into the DB. @@ -1224,73 +1302,7 @@ async def import_downloads_config(session: Session): logger.warning(f'Refusing to import downloads config when DB is not up.') return - from modules.zim.lib import zim_download_url_to_name - from modules.zim.models import ZimSubscription - - try: - logger.warning('Importing downloads in config') - - downloads_by_url = {i['url']: i for i in get_download_manager_config().downloads} - existing_downloads: List[Download] = list(session.query(Download)) - for existing in existing_downloads: - download = downloads_by_url.pop(existing.url, None) - if download: - # Download in config already exists, update the DB record. - # The config is the source of truth. - existing.downloader = download['downloader'] - existing.frequency = download['frequency'] - existing.last_successful_download = download['last_successful_download'] - existing.next_download = download['next_download'] - existing.status = download['status'] - existing.sub_downloader = download['sub_downloader'] - existing.settings = download.get('settings') or dict() - existing.flush() - else: - logger.warning(f'Deleting Download {existing.url} because it is no longer in the config') - session.delete(existing) - - for download in downloads_by_url.values(): - # These downloads are new, import them. - download = Download( - downloader=download['downloader'], - frequency=download['frequency'], - last_successful_download=download['last_successful_download'], - next_download=download['next_download'], - settings=download['settings'] or dict(), - status=download['status'], - sub_downloader=download['sub_downloader'], - url=(url := download['url']), - ) - session.add(download) - logger.info(f'Adding new download {url}') - - session.commit() - except Exception as e: - logger.error('Failed to import downloads', exc_info=e) - raise - - try: - # Claim any Kiwix subscriptions for ZimSubscription(s). - downloads: List[Download] = session.query(Download) - need_commit = False - for download in downloads: - if not download.url.startswith('https://download.kiwix.org/') or not download.frequency: - # ZimSubscription requires download.kiwix.org AND a frequency. - continue - - name, language = zim_download_url_to_name(download.url) - subscription = session.query(ZimSubscription).filter_by(name=name, language=language).one_or_none() - if not subscription: - subscription = ZimSubscription(name=name, language=language) - subscription.change_download(download.url, download.frequency, session=session) - session.add(subscription) - need_commit = True - - if need_commit: - session.commit() - except Exception as e: - logger.error('Failed to restore ZimSubscriptions', exc_info=e) - raise + get_download_manager_config().import_config() def parse_feed(url: str) -> FeedParserDict: diff --git a/wrolpi/files/test/test_api.py b/wrolpi/files/test/test_api.py index 8778d803..44fb513c 100644 --- a/wrolpi/files/test/test_api.py +++ b/wrolpi/files/test/test_api.py @@ -717,8 +717,7 @@ async def test_get_file(test_session, async_client, test_directory, make_files_s @pytest.mark.asyncio -async def test_ignore_directory(test_session, async_client, test_directory, make_files_structure, test_config, - skip_config_backups): +async def test_ignore_directory(test_session, async_client, test_directory, make_files_structure, test_wrolpi_config): """A maintainer can ignore/un-ignore directories. The files in the directory should not be refreshed.""" # Remove any default ignored directories. get_wrolpi_config().ignored_directories = [] diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py index 51621dca..b383a2a8 100644 --- a/wrolpi/root_api.py +++ b/wrolpi/root_api.py @@ -139,33 +139,33 @@ async def echo(request: Request): @openapi.description('Get WROLPi settings') @openapi.response(HTTPStatus.OK, schema.SettingsResponse) def get_settings(_: Request): - config = get_wrolpi_config() + wrolpi_config = get_wrolpi_config() - ignored_directories = [get_relative_to_media_directory(i) for i in config.ignored_directories] + ignored_directories = [get_relative_to_media_directory(i) for i in wrolpi_config.ignored_directories] settings = { - 'archive_destination': config.archive_destination, + 'archive_destination': wrolpi_config.archive_destination, 'download_manager_disabled': download_manager.is_disabled, 'download_manager_stopped': download_manager.is_stopped, - 'download_on_startup': config.download_on_startup, - 'download_timeout': config.download_timeout, - 'hotspot_device': config.hotspot_device, - 'hotspot_on_startup': config.hotspot_on_startup, - 'hotspot_password': config.hotspot_password, - 'hotspot_ssid': config.hotspot_ssid, + 'download_on_startup': wrolpi_config.download_on_startup, + 'download_timeout': wrolpi_config.download_timeout, + 'hotspot_device': wrolpi_config.hotspot_device, + 'hotspot_on_startup': wrolpi_config.hotspot_on_startup, + 'hotspot_password': wrolpi_config.hotspot_password, + 'hotspot_ssid': wrolpi_config.hotspot_ssid, 'hotspot_status': admin.hotspot_status().name, - 'ignore_outdated_zims': config.ignore_outdated_zims, + 'ignore_outdated_zims': wrolpi_config.ignore_outdated_zims, 'ignored_directories': ignored_directories, 'log_level': api_app.shared_ctx.log_level.value, - 'map_destination': config.map_destination, - 'nav_color': config.nav_color, + 'map_destination': wrolpi_config.map_destination, + 'nav_color': wrolpi_config.nav_color, 'media_directory': str(get_media_directory()), # Convert to string to avoid conversion to relative. - 'throttle_on_startup': config.throttle_on_startup, + 'throttle_on_startup': wrolpi_config.throttle_on_startup, 'throttle_status': admin.throttle_status().name, 'version': __version__, - 'videos_destination': config.videos_destination, - 'wrol_mode': config.wrol_mode, - 'zims_destination': config.zims_destination, + 'videos_destination': wrolpi_config.videos_destination, + 'wrol_mode': wrolpi_config.wrol_mode, + 'zims_destination': wrolpi_config.zims_destination, } return json_response(settings) @@ -191,41 +191,41 @@ async def update_settings(_: Request, body: schema.SettingsRequest): raise HotspotPasswordTooShort() # Remove any keys with None values, then save the config. - config = {k: v for k, v in body.__dict__.items() if v is not None} + new_config = {k: v for k, v in body.__dict__.items() if v is not None} wrolpi_config = get_wrolpi_config() - if not config: + if not new_config: raise InvalidConfig() if body.archive_destination and pathlib.Path(body.archive_destination).is_absolute(): raise InvalidConfig('Archive directory must be relative to media directory') elif not body.archive_destination: - config['archive_destination'] = wrolpi_config.default_config['archive_destination'] + new_config['archive_destination'] = wrolpi_config.default_config['archive_destination'] if body.videos_destination and pathlib.Path(body.videos_destination).is_absolute(): raise InvalidConfig('Videos directory must be relative to media directory') elif not body.videos_destination: - config['videos_destination'] = wrolpi_config.default_config['videos_destination'] + new_config['videos_destination'] = wrolpi_config.default_config['videos_destination'] if body.map_destination and pathlib.Path(body.map_destination).is_absolute(): raise InvalidConfig('Map directory must be relative to media directory') elif not body.map_destination: - config['map_destination'] = wrolpi_config.default_config['map_destination'] + new_config['map_destination'] = wrolpi_config.default_config['map_destination'] if body.zims_destination and pathlib.Path(body.zims_destination).is_absolute(): raise InvalidConfig('Zims directory must be relative to media directory') elif not body.zims_destination: - config['zims_destination'] = wrolpi_config.default_config['zims_destination'] + new_config['zims_destination'] = wrolpi_config.default_config['zims_destination'] - log_level = config.pop('log_level', None) + log_level = new_config.pop('log_level', None) if isinstance(log_level, int): set_global_log_level(log_level) old_password = wrolpi_config.hotspot_password - wrolpi_config.update(config) + wrolpi_config.update(new_config) # If the password was changed, we need to restart the hotspot. - password_changed = (new_password := config.get('hotspot_password')) and old_password != new_password + password_changed = (new_password := new_config.get('hotspot_password')) and old_password != new_password if body.hotspot_status is True or (password_changed and admin.hotspot_status() == HotspotStatus.connected): # Turn on Hotspot diff --git a/wrolpi/tags.py b/wrolpi/tags.py index 4416f70b..e83f9cfe 100644 --- a/wrolpi/tags.py +++ b/wrolpi/tags.py @@ -226,6 +226,7 @@ class TagsConfig(ConfigFile): tag_files=list(), tag_zims=list(), tags=dict(), + version=0, ) @property @@ -254,62 +255,211 @@ class TagsConfig(ConfigFile): def tags(self, value: dict): self.update({'tags': value}) - def save_tags(self, session: Session): + def dump_config(self, file: pathlib.Path = None): media_directory = get_media_directory() - tags = dict() - tag_rows = session.query(Tag) - for tag in tag_rows: - tags[tag.name] = dict(color=tag.color) + with get_db_session() as session: + tags = dict() + tag_rows = session.query(Tag) + for tag in tag_rows: + tags[tag.name] = dict(color=tag.color) - from wrolpi.files.models import FileGroup - results = session.query(Tag, TagFile, FileGroup) \ - .filter(TagFile.tag_id == Tag.id, TagFile.file_group_id == FileGroup.id) \ - .order_by(FileGroup.primary_path) + from wrolpi.files.models import FileGroup + results = session.query(Tag, TagFile, FileGroup) \ + .filter(TagFile.tag_id == Tag.id, TagFile.file_group_id == FileGroup.id) \ + .order_by(FileGroup.primary_path) - tag_files = [] - for tag, tag_file, file_group in results: - value = [ - tag.name, - str(file_group.primary_path.relative_to(media_directory)), - # Fallback to current time if not set. - tag_file.created_at.isoformat() if tag_file.created_at else dates.now().isoformat(), - ] - tag_files.append(value) - logger.debug(f'Got {len(tag_files)} tag files for config.') + tag_files = [] + for tag, tag_file, file_group in results: + value = [ + tag.name, + str(file_group.primary_path.relative_to(media_directory)), + # Fallback to current time if not set. + tag_file.created_at.isoformat() if tag_file.created_at else dates.now().isoformat(), + ] + tag_files.append(value) + logger.debug(f'Got {len(tag_files)} tag files for config.') + from modules.zim.models import Zim, TagZimEntry + results = session.query(Tag, Zim, TagZimEntry) \ + .filter(Tag.id == TagZimEntry.tag_id, Zim.id == TagZimEntry.zim_id) \ + .order_by(TagZimEntry.zim_id, TagZimEntry.zim_entry) + + tag_zims = [] + for tag, zim, tag_zim_entry in results: + zim: Zim + tag_zim_entry: TagZimEntry + value = [ + tag.name, + str(get_relative_to_media_directory(zim.path)), + tag_zim_entry.zim_entry, + # Fallback to current time if not set. + tag_zim_entry.created_at.isoformat() if tag_zim_entry.created_at else dates.now().isoformat(), + ] + tag_zims.append(value) + logger.debug(f'Got {len(tag_zims)} tag zims for config.') + + # Write to the config. + self.update({ + 'tag_files': tag_files, + 'tag_zims': tag_zims, + 'tags': tags, + }) + + def import_config(self, file: pathlib.Path = None): + from modules.zim import lib as zim_lib from modules.zim.models import Zim, TagZimEntry - results = session.query(Tag, Zim, TagZimEntry) \ - .filter(Tag.id == TagZimEntry.tag_id, Zim.id == TagZimEntry.zim_id) \ - .order_by(TagZimEntry.zim_id, TagZimEntry.zim_entry) + from wrolpi.files.lib import glob_shared_stem - tag_zims = [] - for tag, zim, tag_zim_entry in results: - zim: Zim - tag_zim_entry: TagZimEntry - value = [ - tag.name, - str(get_relative_to_media_directory(zim.path)), - tag_zim_entry.zim_entry, - # Fallback to current time if not set. - tag_zim_entry.created_at.isoformat() if tag_zim_entry.created_at else dates.now().isoformat(), - ] - tag_zims.append(value) - logger.debug(f'Got {len(tag_zims)} tag zims for config.') + if PYTEST and not TEST_TAGS_CONFIG: + logger.warning('Refusing to import tags without test tags config. ' + 'Use `test_tags_config` fixture if you would like to call this.') + return - # Write to the config. - self.update({ - 'tag_files': tag_files, - 'tag_zims': tag_zims, - 'tags': tags, - }) + config = get_tags_config() + if not (path := config.get_file()).is_file(): + logger.warning(f'Refusing to import tags config because it does not exist: {path}') + return + + logger.info('Importing tags config') + super().import_config(file) + + try: + with get_db_session() as session: + if config.tags: + # Tags have been saved to config, import them + tags_by_name: Dict[str, Tag] = {i.name: i for i in session.query(Tag)} + new_tags = list() + for name, attrs in config.tags.items(): + tag = tags_by_name.get(name) + if not tag: + # Maintainer added a Tag to the config manually, or DB was wiped. + tag = Tag(name=name, color=attrs['color']) + new_tags.append(tag) + logger.info(f'Creating new {tag}') + tag.color = attrs['color'] + + if new_tags: + session.add_all(new_tags) + + media_directory = get_media_directory() + + need_commit = False + + # Get all Tags again because new ones may exist. + tags_by_name: Dict[str, Tag] = {i.name: i for i in session.query(Tag)} + + # Tag all FileGroups. + if config.tag_files: + from wrolpi.files.models import FileGroup + + primary_paths = [str(media_directory / i[1]) for i in config.tag_files] + file_groups = session.query(FileGroup).filter(FileGroup.primary_path.in_(primary_paths)) + file_groups_by_primary_path = {i.primary_path: i for i in file_groups} + # Get all TagFiles so we can create new ones. + tag_files = {(i.tag_id, i.file_group_id): i for i in session.query(TagFile)} + + for tag_name, primary_path, created_at in config.tag_files: + tag: Tag = tags_by_name.get(tag_name) + # Paths are absolute in the DB, relative in config. + absolute_path = media_directory / primary_path + file_group: FileGroup = file_groups_by_primary_path.get(absolute_path) + if not file_group and absolute_path.is_file(): + # File exists, but is not yet in DB. + files = glob_shared_stem(absolute_path) + try: + file_group = FileGroup.from_paths(session, *files) + session.add(file_group) + session.flush([file_group, ]) + except NoPrimaryFile: + logger.error(f'Failed to tag {absolute_path}') + continue + + if tag and file_group: + tag_file: TagFile = tag_files.get((tag.id, file_group.id)) + if not tag_file: + # This FileGroup has not been tagged with the Tag, add it. + logger.debug(f'Creating TagFile for tag_id={tag.id} file_group_id={file_group.id}') + tag_file = TagFile(file_group_id=file_group.id, tag_id=tag.id, tag=tag, + file_group=file_group) + session.add(tag_file) + tag_file.flush() + tag_file.created_at = dates.strptime_ms(created_at) if created_at else dates.now() + need_commit = True + elif not file_group: + logger.warning(f'Cannot find FileGroup for {repr(str(primary_path))}') + elif not tag: + logger.warning(f'Cannot find Tag for {repr(str(primary_path))}') + + # Tag all Zim entries. + if config.tag_zims: + # { pathlib.Path('/media/wrolpi/...'): , ... } + zims_by_path = {i.path: i for i in session.query(Zim)} + + # { (pathlib.Path('relative/path'), 'entry path'): , ... } + tag_zim_entries = {(get_relative_to_media_directory(i.zim.path), i.zim_entry): i for i in + session.query(TagZimEntry)} + + for tag_name, zim_path, zim_entry, created_at in config.tag_zims: + zim_path = pathlib.Path(zim_path) + tag: Tag = tags_by_name.get(tag_name) + absolute_path = media_directory / zim_path + zim: Zim = zims_by_path.get(absolute_path) + if not zim: + # No Zim matches the path. It's likely that the old Zim file was deleted. Attempt to migrate + # the entry. + name, date = zim_lib.parse_name(absolute_path) + # Find any Zims that match the old Zim's name (wikipedia_en_all_maxi_*) + possible_zims = {i: j for i, j in zims_by_path.items() if i.name.startswith(name)} + if not possible_zims: + logger.warning(f'Cannot find Zim for {repr(str(zim_path))}') + continue + zim = zims_by_path[sorted(possible_zims.keys())[-1]] + new_zim_path = get_relative_to_media_directory(media_directory / zim.path) + logger.warning( + f'Migrating Zim entry tag {repr(str(tag_name))} from {zim_path} to {new_zim_path}') + zim_path = new_zim_path + + if tag: + tag_zim_entry: TagZimEntry = tag_zim_entries.get((zim_path, zim_entry)) + if not tag_zim_entry: + tag_zim_entry = TagZimEntry(tag=tag, zim=zim, zim_entry=zim_entry) + session.add(tag_zim_entry) + # Track this new TagZimEntry because migration may cause duplicates. + tag_zim_entries[(zim_path, zim_entry)] = tag_zim_entry + logger.info(f'Created TagZimEntry: {tag_zim_entry}') + tag_zim_entry.created_at = datetime.fromisoformat(created_at) if created_at else dates.now() + need_commit = True + elif not tag: + logger.warning(f'Cannot find Tag for {repr(str(zim_path))}') + + # Delete missing Tags last in case they are used above. + if config.tags: + config_tag_names = set(config.tags.keys()) + for tag in session.query(Tag): + if tag.name not in config_tag_names: + if tag.has_relations(): + logger.warning(f'Refusing to delete {tag} because it is used.') + else: + logger.warning(f'Deleting {tag} because it is not in the config.') + session.delete(tag) + need_commit = True + + if need_commit: + session.commit() + + self.successful_import = True + logger.info('Importing tags config complete') + except Exception as e: + logger.error(f'Failed to import tags config', exc_info=e) + raise TAGS_CONFIG: TagsConfig = TagsConfig() -TEST_TAGS_CONFIG: TAGS_CONFIG = None +TEST_TAGS_CONFIG: TagsConfig = None # noqa -def get_tags_config(): +def get_tags_config() -> TagsConfig: global TEST_TAGS_CONFIG if isinstance(TEST_TAGS_CONFIG, ConfigFile): return TEST_TAGS_CONFIG @@ -329,11 +479,16 @@ def test_tags_config(): @register_switch_handler('save_tags_config') def save_tags_config(): """Schedule a background task to save all TagFiles to the config file. If testing, save synchronously.""" - with get_db_session() as session: - get_tags_config().save_tags(session) + get_tags_config().dump_config() logger.info('save_tags_config complete') +def import_tags_config(): + """Reads the Tags and TagFiles from the config file, upserts them in the DB.""" + get_tags_config().import_config() + sync_tags_directory.activate_switch() + + save_tags_config: ActivateSwitchMethod @@ -464,157 +619,6 @@ async def upsert_tag(name: str, color: str, tag_id: int = None, session: Session return tag -@optional_session -def import_tags_config(session: Session = None): - """Reads the Tags and TagFiles from the config file, upserts them in the DB.""" - from modules.zim import lib as zim_lib - from modules.zim.models import Zim, TagZimEntry - from wrolpi.files.lib import glob_shared_stem - - if PYTEST and not TEST_TAGS_CONFIG: - logger.warning('Refusing to import tags without test tags config. ' - 'Use `test_tags_config` fixture if you would like to call this.') - return - - config = get_tags_config() - if not (path := config.get_file()).is_file(): - logger.warning(f'Refusing to import tags config because it does not exist: {path}') - return - - logger.info('Importing tags config') - - try: - if config.tags: - # Tags have been saved to config, import them - tags_by_name: Dict[str, Tag] = {i.name: i for i in session.query(Tag)} - new_tags = list() - for name, attrs in config.tags.items(): - tag = tags_by_name.get(name) - if not tag: - # Maintainer added a Tag to the config manually, or DB was wiped. - tag = Tag(name=name, color=attrs['color']) - new_tags.append(tag) - logger.info(f'Creating new {tag}') - tag.color = attrs['color'] - - if new_tags: - session.add_all(new_tags) - - session.commit() - - media_directory = get_media_directory() - - need_commit = False - - # Get all Tags again because new ones may exist. - tags_by_name: Dict[str, Tag] = {i.name: i for i in session.query(Tag)} - - # Tag all FileGroups. - if config.tag_files: - from wrolpi.files.models import FileGroup - - primary_paths = [str(media_directory / i[1]) for i in config.tag_files] - file_groups = session.query(FileGroup).filter(FileGroup.primary_path.in_(primary_paths)) - file_groups_by_primary_path = {i.primary_path: i for i in file_groups} - # Get all TagFiles so we can create new ones. - tag_files = {(i.tag_id, i.file_group_id): i for i in session.query(TagFile)} - - for tag_name, primary_path, created_at in config.tag_files: - tag: Tag = tags_by_name.get(tag_name) - # Paths are absolute in the DB, relative in config. - absolute_path = media_directory / primary_path - file_group: FileGroup = file_groups_by_primary_path.get(absolute_path) - if not file_group and absolute_path.is_file(): - # File exists, but is not yet in DB. - files = glob_shared_stem(absolute_path) - try: - file_group = FileGroup.from_paths(session, *files) - session.add(file_group) - session.flush([file_group, ]) - except NoPrimaryFile: - logger.error(f'Failed to tag {absolute_path}') - continue - - if tag and file_group: - tag_file: TagFile = tag_files.get((tag.id, file_group.id)) - if not tag_file: - # This FileGroup has not been tagged with the Tag, add it. - logger.debug(f'Creating TagFile for tag_id={tag.id} file_group_id={file_group.id}') - tag_file = TagFile(file_group_id=file_group.id, tag_id=tag.id, tag=tag, file_group=file_group) - session.add(tag_file) - tag_file.flush() - tag_file.created_at = dates.strptime_ms(created_at) if created_at else dates.now() - need_commit = True - elif not file_group: - logger.warning(f'Cannot find FileGroup for {repr(str(primary_path))}') - elif not tag: - logger.warning(f'Cannot find Tag for {repr(str(primary_path))}') - - # Tag all Zim entries. - if config.tag_zims: - # { pathlib.Path('/media/wrolpi/...'): , ... } - zims_by_path = {i.path: i for i in session.query(Zim)} - - # { (pathlib.Path('relative/path'), 'entry path'): , ... } - tag_zim_entries = {(get_relative_to_media_directory(i.zim.path), i.zim_entry): i for i in - session.query(TagZimEntry)} - - for tag_name, zim_path, zim_entry, created_at in config.tag_zims: - zim_path = pathlib.Path(zim_path) - tag: Tag = tags_by_name.get(tag_name) - absolute_path = media_directory / zim_path - zim: Zim = zims_by_path.get(absolute_path) - if not zim: - # No Zim matches the path. It's likely that the old Zim file was deleted. Attempt to migrate - # the entry. - name, date = zim_lib.parse_name(absolute_path) - # Find any Zims that match the old Zim's name (wikipedia_en_all_maxi_*) - possible_zims = {i: j for i, j in zims_by_path.items() if i.name.startswith(name)} - if not possible_zims: - logger.warning(f'Cannot find Zim for {repr(str(zim_path))}') - continue - zim = zims_by_path[sorted(possible_zims.keys())[-1]] - new_zim_path = get_relative_to_media_directory(media_directory / zim.path) - logger.warning(f'Migrating Zim entry tag {repr(str(tag_name))} from {zim_path} to {new_zim_path}') - zim_path = new_zim_path - - if tag: - tag_zim_entry: TagZimEntry = tag_zim_entries.get((zim_path, zim_entry)) - if not tag_zim_entry: - tag_zim_entry = TagZimEntry(tag=tag, zim=zim, zim_entry=zim_entry) - session.add(tag_zim_entry) - # Track this new TagZimEntry because migration may cause duplicates. - tag_zim_entries[(zim_path, zim_entry)] = tag_zim_entry - logger.info(f'Created TagZimEntry: {tag_zim_entry}') - tag_zim_entry.created_at = datetime.fromisoformat(created_at) if created_at else dates.now() - need_commit = True - elif not tag: - logger.warning(f'Cannot find Tag for {repr(str(zim_path))}') - - # Delete missing Tags last in case they are used above. - if config.tags: - config_tag_names = set(config.tags.keys()) - for tag in session.query(Tag): - if tag.name not in config_tag_names: - if tag.has_relations(): - logger.warning(f'Refusing to delete {tag} because it is used.') - else: - logger.warning(f'Deleting {tag} because it is not in the config.') - session.delete(tag) - need_commit = True - - if need_commit: - session.commit() - - logger.info('Importing tags config complete') - except Exception as e: - logger.error(f'Failed to import tags config', exc_info=e) - if PYTEST: - raise - - sync_tags_directory.activate_switch() - - def tag_names_to_file_group_sub_select(tag_names: List[str], params: dict) -> Tuple[str, dict]: """Create the SQL necessary to filter FileGroup by the provided Tag names.""" if not tag_names: diff --git a/wrolpi/test/test_admin.py b/wrolpi/test/test_admin.py index c78b2f26..92faed71 100644 --- a/wrolpi/test/test_admin.py +++ b/wrolpi/test/test_admin.py @@ -69,7 +69,7 @@ def test_enable_hotspot_connected(): ) -def test_change_hotspot(test_config, async_client): +def test_change_hotspot(test_wrolpi_config, async_client): """The hotspot can be configured.""" with mock.patch('wrolpi.admin.hotspot_status') as mock_hotspot_status, \ mock.patch('wrolpi.admin.subprocess') as mock_subprocess, \ diff --git a/wrolpi/test/test_common.py b/wrolpi/test/test_common.py index 6e59f048..074f9206 100644 --- a/wrolpi/test/test_common.py +++ b/wrolpi/test/test_common.py @@ -18,7 +18,8 @@ import pytz import wrolpi.vars from wrolpi import common -from wrolpi.common import cum_timer, TIMERS, print_timer, limit_concurrent, run_after +from wrolpi.common import cum_timer, TIMERS, print_timer, limit_concurrent, run_after, get_wrolpi_config +from wrolpi.switches import await_switches from wrolpi.test.common import build_test_directories, skip_circleci @@ -814,18 +815,18 @@ def test_find_file(test_directory, make_files_structure): assert common.find_file(test_directory, 'does not exist', 100) is None -def test_config_backup(async_client, test_config, test_directory): +def test_config_backup(async_client, test_wrolpi_config, test_directory): """Configs have a backup each day.""" config = common.get_wrolpi_config() # No backups yet. - config.save() + config.dump_config() assert (test_directory / 'config').is_dir() assert not (test_directory / 'config/backup').is_dir() assert (test_directory / 'config/wrolpi.yaml').is_file() # Backups directory is created. New backup config is saved. - config.save() + config.dump_config() assert (test_directory / 'config').is_dir() assert (test_directory / 'config/backup').is_dir() assert (test_directory / 'config/wrolpi.yaml').is_file() @@ -860,7 +861,7 @@ def test_can_connect_to_server(simple_web_server): @pytest.mark.asyncio -async def test_log_level(async_client, test_config): +async def test_log_level(async_client, test_wrolpi_config): """User can change API log level.""" from wrolpi.api_utils import api_app try: @@ -916,3 +917,67 @@ def test_is_valid_hex_color(color, expected): ]) def test_unique_by_predicate(iterable, predicate, expected): assert common.unique_by_predicate(iterable, predicate) == expected + + +@pytest.mark.asyncio +async def test_config_lifecycle(async_client, test_wrolpi_config): + """Test importing, dumping, updating, saving a config.""" + config = get_wrolpi_config() + # Config is not imported, default values are used. + assert config.successful_import is False + assert config.wrol_mode is False + assert config.version == 0 + + # Bad config cannot be imported. + test_wrolpi_config.parent.mkdir(exist_ok=True) + test_wrolpi_config.write_text('bad config\ndata') + with pytest.raises(RuntimeError) as e: + config.import_config() + assert config.successful_import is False + assert config.version == 0 + assert 'invalid' in str(e) + + # Cannot dump config because import was not successful. + with pytest.raises(RuntimeError) as e: + config.dump_config() + assert 'imported' in str(e) + assert config.version == 0 + + # Incomplete config can still be imported. + test_wrolpi_config.write_text('wrol_mode: true') + config.import_config() + assert config.successful_import is True + assert config.wrol_mode is True + assert config.version == 0 + + # Items from the default config are written to the file. + config.dump_config() + assert 'version: ' in test_wrolpi_config.read_text() + assert config.wrol_mode is True + assert config.version == 1 + + # Other data is ignored. + test_wrolpi_config.write_text('wrol_mode: false\nother_data: false') + config.import_config() + assert 'other_data' not in config._config, 'Extra data in config should be ignored' + assert config.wrol_mode is False + + # Changing value changes both file and config data. + config.wrol_mode = True + assert config._config['wrol_mode'] is True + await await_switches() + assert 'wrol_mode: true' in test_wrolpi_config.read_text() + assert 'other_data' not in test_wrolpi_config.read_text(), 'Other data should be removed on save.' + assert config.version == 2 + + # Cannot overwrite newer config. + config_data = config.read_config_file() + config_data['version'] = 5 + config.write_config_data(config_data, test_wrolpi_config) + with pytest.raises(RuntimeError) as e: + config.dump_config() + assert 'newer config' in str(e) + + # Can import, then config can be saved. + config.import_config() + config.dump_config() diff --git a/wrolpi/test/test_root_api.py b/wrolpi/test/test_root_api.py index 03fb1c64..c93fe31a 100644 --- a/wrolpi/test/test_root_api.py +++ b/wrolpi/test/test_root_api.py @@ -206,7 +206,7 @@ async def test_echo(async_client): assert response.json['args'] == {} -def test_hotspot_settings(test_session, test_client, test_config): +def test_hotspot_settings(test_session, test_client, test_wrolpi_config): """ The User can toggle the Hotspot via /settings. The Hotspot can be automatically started on startup. """ @@ -268,7 +268,7 @@ def test_hotspot_settings(test_session, test_client, test_config): @skip_circleci -def test_throttle_toggle(test_session, test_client, test_config): +def test_throttle_toggle(test_session, test_client, test_wrolpi_config): get_wrolpi_config().ignored_directories = list() with mock.patch('wrolpi.admin.subprocess') as mock_subprocess, \ @@ -286,7 +286,7 @@ def test_throttle_toggle(test_session, test_client, test_config): @pytest.mark.asyncio -async def test_clear_downloads(test_session, async_client, test_config, test_download_manager_config): +async def test_clear_downloads(test_session, async_client, test_wrolpi_config, test_download_manager_config): d1 = Download(url='https://example.com/1', status='complete') d2 = Download(url='https://example.com/2', status='pending') d3 = Download(url='https://example.com/3', status='deferred') @@ -706,7 +706,7 @@ def test_recursive_errors(): @pytest.mark.asyncio -async def test_settings_special_directories(async_client, test_config): +async def test_settings_special_directories(async_client, test_wrolpi_config): """Maintainer can change special directories.""" request, response = await async_client.get('/api/settings') assert response.status_code == HTTPStatus.OK diff --git a/wrolpi/test/test_tags.py b/wrolpi/test/test_tags.py index 2aa49583..4ebc923a 100644 --- a/wrolpi/test/test_tags.py +++ b/wrolpi/test/test_tags.py @@ -99,9 +99,10 @@ async def test_tags_config_file(async_client, test_session, test_directory, tag_ tag1 = await tag_factory() tag2 = await tag_factory() test_session.commit() - - tags.save_tags_config.activate_switch() await await_switches() + # tags.get_tags_config().successful_import = True + + tags.save_tags_config() assert tag1.name in test_tags_config.read_text() assert tag2.name in test_tags_config.read_text() @@ -251,7 +252,7 @@ async def test_import_tags_config(async_client, test_session, test_directory, te FileGroup.from_paths(test_session, example_singlefile) test_session.commit() - tags.import_tags_config(test_session) + tags.import_tags_config() # '🔫' Tag was created. assert test_session.query(tags.Tag).count() == 1 @@ -277,7 +278,7 @@ async def test_import_tags_config_missing_file(test_session, test_directory, tes # Re-initialize config with the data we just saved. tags.get_tags_config().initialize() - tags.import_tags_config(test_session) + tags.import_tags_config() file_group: FileGroup = test_session.query(FileGroup).one() assert file_group.tag_files, 'File was not tagged during import.'