mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-29 11:26:25 -05:00
Configs are displayed in new ConfigsPage under Admin.
- Configs can be imported and saved. - Configs are validated before imported. - API will refuse to save a config if it was not imported successfully.
This commit is contained in:
parent
d34301a085
commit
acf3dee179
22 changed files with 767 additions and 157 deletions
|
|
@ -1,4 +1,5 @@
|
|||
import pathlib
|
||||
from dataclasses import field, dataclass
|
||||
from decimal import Decimal
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
|
|
@ -8,6 +9,7 @@ from pint import Quantity
|
|||
|
||||
from wrolpi.common import logger, Base, ConfigFile
|
||||
from wrolpi.db import get_db_session
|
||||
from wrolpi.events import Events
|
||||
from .errors import NoInventories
|
||||
from .inventory import get_items, get_inventories, get_unit_registry
|
||||
from .models import Inventory, Item
|
||||
|
|
@ -116,12 +118,19 @@ def cleanup_quantity(quantity: Quantity) -> Quantity:
|
|||
return Decimal(num) * unit
|
||||
|
||||
|
||||
@dataclass
|
||||
class InventoriesConfigValidator:
|
||||
version: int = None
|
||||
inventories: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
class InventoriesConfig(ConfigFile):
|
||||
file_name = 'inventories.yaml'
|
||||
default_config = dict(
|
||||
inventories=[],
|
||||
version=0,
|
||||
)
|
||||
validator = InventoriesConfigValidator
|
||||
|
||||
@property
|
||||
def inventories(self) -> dict:
|
||||
|
|
@ -131,7 +140,7 @@ class InventoriesConfig(ConfigFile):
|
|||
def inventories(self, value: dict):
|
||||
self.update({'inventories': value})
|
||||
|
||||
def dump_config(self, file: pathlib.Path = None):
|
||||
def dump_config(self, file: pathlib.Path = None, send_events=False, overwrite=False):
|
||||
inventories = []
|
||||
for inventory in get_inventories():
|
||||
inventories.append(inventory.dict())
|
||||
|
|
@ -140,46 +149,51 @@ class InventoriesConfig(ConfigFile):
|
|||
raise NoInventories('No Inventories are in the database!')
|
||||
|
||||
self._config['inventories'] = inventories
|
||||
super().dump_config(file)
|
||||
super().dump_config(file, send_events, overwrite)
|
||||
|
||||
def import_config(self, file: pathlib.Path = None):
|
||||
def import_config(self, file: pathlib.Path = None, send_events=False):
|
||||
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
|
||||
db_inventories = session.query(Inventory).all()
|
||||
db_inventories_by_name = {i.name: i for i in db_inventories}
|
||||
config_inventories = [i['name'] for i in self.inventories]
|
||||
for inventory_dict in self.inventories:
|
||||
if inventory_dict['name'] not in db_inventories_by_name:
|
||||
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()
|
||||
db_inventories_by_name[inventory.name] = inventory
|
||||
|
||||
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()
|
||||
# Delete any inventories no longer in the config.
|
||||
for name, inventory in db_inventories_by_name.items():
|
||||
if name not in config_inventories:
|
||||
session.delete(inventory)
|
||||
|
||||
for inventory_dict in self.inventories:
|
||||
# Items are complex and do not have useful primary keys. Delete all items, create new items.
|
||||
session.query(Item).filter(Item.inventory_id == inventory_dict['id']).delete()
|
||||
inventory = db_inventories_by_name[inventory_dict['name']]
|
||||
for item in inventory_dict['items']:
|
||||
del item['inventory_id']
|
||||
item = Item(inventory_id=inventory.id, **item)
|
||||
item.inventory_id = inventory.id
|
||||
del item['id']
|
||||
item = Item(inventory=inventory, inventory_id=inventory.id, **item)
|
||||
session.add(item)
|
||||
item.flush()
|
||||
|
||||
self.successful_import = True
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to import {self.file_name}', exc_info=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
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
from sqlalchemy import Column, Integer, String, Date, ForeignKey, DECIMAL
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.orm import relationship, Session
|
||||
from sqlalchemy.orm.collections import InstrumentedList
|
||||
|
||||
from wrolpi.common import Base, ModelHelper
|
||||
|
|
@ -56,6 +56,10 @@ class Inventory(Base, ModelHelper):
|
|||
"""
|
||||
self.deleted_at = now()
|
||||
|
||||
@staticmethod
|
||||
def find_by_name(session: Session, name: str) -> 'Inventory':
|
||||
return session.query(Inventory).filter_by(name=name).one()
|
||||
|
||||
|
||||
class InventoriesVersion(Base, ModelHelper):
|
||||
__tablename__ = 'inventories_version'
|
||||
|
|
|
|||
|
|
@ -303,3 +303,16 @@ async def test_inventories_config(async_client, test_session, test_directory, in
|
|||
test_items = {(i['name'], i['brand'], i['count']) for i in TEST_ITEMS[:-1]}
|
||||
db_items = {(i.name, i.brand, i.count) for i in non_deleted_items}
|
||||
assert test_items == db_items
|
||||
|
||||
# An extra Inventory with items should be deleted from the DB.
|
||||
inventory = Inventory(name='delete me')
|
||||
test_session.add(inventory)
|
||||
inventory.flush()
|
||||
test_session.add(Item(inventory_id=inventory.id))
|
||||
test_session.commit()
|
||||
assert test_session.query(Inventory).count() == 2
|
||||
assert {i for i, in test_session.query(Inventory.name)} == {'Food Storage', 'delete me'}
|
||||
|
||||
import_inventories_config()
|
||||
assert test_session.query(Inventory).count() == 1
|
||||
assert test_session.query(Inventory).one().name == 'Food Storage'
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import dataclasses
|
|||
import html
|
||||
import pathlib
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Generator, Type
|
||||
from typing import Tuple, Optional
|
||||
|
|
@ -20,6 +21,7 @@ from wrolpi.dates import Seconds, from_timestamp
|
|||
from wrolpi.db import get_db_curs, get_db_session
|
||||
from wrolpi.downloader import Download
|
||||
from wrolpi.errors import UnknownDirectory
|
||||
from wrolpi.events import Events
|
||||
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
|
||||
|
|
@ -207,6 +209,20 @@ def convert_or_generate_poster(video: Video) -> Tuple[Optional[pathlib.Path], Op
|
|||
return None, None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChannelDictValidator:
|
||||
name: str
|
||||
directory: str
|
||||
download_frequency: int
|
||||
url: str = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChannelsConfigValidator:
|
||||
version: int = None
|
||||
channels: list[ChannelDictValidator] = dataclasses.field(default_factory=list)
|
||||
|
||||
|
||||
class ChannelsConfig(ConfigFile):
|
||||
file_name = 'channels.yaml'
|
||||
default_config = dict(
|
||||
|
|
@ -218,6 +234,7 @@ class ChannelsConfig(ConfigFile):
|
|||
)],
|
||||
version=0,
|
||||
)
|
||||
validator = ChannelsConfigValidator
|
||||
|
||||
@property
|
||||
def channels(self) -> dict:
|
||||
|
|
@ -227,7 +244,7 @@ class ChannelsConfig(ConfigFile):
|
|||
def channels(self, value: dict):
|
||||
self.update({'channels': value})
|
||||
|
||||
def import_config(self, file: pathlib.Path = None):
|
||||
def import_config(self, file: pathlib.Path = None, send_events=False):
|
||||
from modules.videos.channel.lib import get_channel
|
||||
super().import_config()
|
||||
try:
|
||||
|
|
@ -296,10 +313,12 @@ class ChannelsConfig(ConfigFile):
|
|||
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
|
||||
self.successful_import = False
|
||||
message = f'Failed to import {self.get_relative_file()} config!'
|
||||
if send_events:
|
||||
channel_import_logger.warning(message, exc_info=e)
|
||||
Events.send_config_import_failed(message)
|
||||
raise
|
||||
|
||||
|
||||
CHANNELS_CONFIG: ChannelsConfig = ChannelsConfig()
|
||||
|
|
@ -328,6 +347,21 @@ def set_test_channels_config():
|
|||
TEST_CHANNELS_CONFIG = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class VideoDownloaderConfigValidator:
|
||||
continue_dl: bool
|
||||
dateafter: str
|
||||
file_name_format: str
|
||||
nooverwrites: bool
|
||||
quiet: bool
|
||||
writeautomaticsub: bool
|
||||
writeinfojson: bool
|
||||
writesubtitles: bool
|
||||
writethumbnail: bool
|
||||
youtube_include_dash_manifest: bool
|
||||
version: int = None
|
||||
|
||||
|
||||
class VideoDownloaderConfig(ConfigFile):
|
||||
file_name = 'videos_downloader.yaml'
|
||||
default_config = dict(
|
||||
|
|
@ -343,6 +377,7 @@ class VideoDownloaderConfig(ConfigFile):
|
|||
writethumbnail=True,
|
||||
youtube_include_dash_manifest=False,
|
||||
)
|
||||
validator = VideoDownloaderConfigValidator
|
||||
|
||||
@property
|
||||
def continue_dl(self) -> bool:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue