This commit is contained in:
2026-01-22 02:45:08 -08:00
parent 3d571b007b
commit ba23c0606f
18 changed files with 75 additions and 5355 deletions

View File

@@ -188,19 +188,6 @@ def _apply_conf_block(
tool[tool_name] = dict(block)
return
if kind_l == "networking":
net_name = str(subtype).strip().lower()
if not net_name:
return
net = config.setdefault("networking", {})
if not isinstance(net, dict):
config["networking"] = {}
net = config["networking"]
existing = net.get(net_name)
if isinstance(existing, dict):
_merge_dict_inplace(existing, block)
else:
net[net_name] = dict(block)
return
@@ -366,24 +353,6 @@ def _serialize_conf(config: Dict[str, Any]) -> str:
seen_keys.add(k_upper)
lines.append(f"{k}={_format_conf_value(block.get(k))}")
# Networking blocks
networking = config.get("networking")
if isinstance(networking, dict):
for name in sorted(networking.keys()):
block = networking.get(name)
if not isinstance(block, dict):
continue
lines.append("")
lines.append(f"[networking={name}]")
seen_keys = set()
for k in sorted(block.keys()):
k_upper = k.upper()
if k_upper in seen_keys:
continue
seen_keys.add(k_upper)
lines.append(f"{k}={_format_conf_value(block.get(k))}")
return "\n".join(lines).rstrip() + "\n"
@@ -674,34 +643,6 @@ def resolve_debug_log(config: Dict[str, Any]) -> Optional[Path]:
return path
def migrate_conf_to_db(config: Dict[str, Any]) -> None:
"""Migrate the configuration dictionary to the database."""
log("Migrating configuration from .conf to database...")
for key, value in config.items():
if key in ("store", "provider", "tool", "networking"):
cat = key
sub_dict = value
if isinstance(sub_dict, dict):
for subtype, subtype_items in sub_dict.items():
if isinstance(subtype_items, dict):
# For provider/tool/networking, subtype is the name (e.g. alldebrid)
# but for store, it's the type (e.g. hydrusnetwork)
if cat == "store" and str(subtype).strip().lower() == "folder":
continue
if cat != "store":
for k, v in subtype_items.items():
save_config_value(cat, subtype, "", k, v)
else:
for name, items in subtype_items.items():
if isinstance(items, dict):
for k, v in items.items():
save_config_value(cat, subtype, name, k, v)
else:
# Global setting
save_config_value("global", "", "", key, value)
log("Configuration migration complete!")
def load_config(
config_dir: Optional[Path] = None, filename: str = DEFAULT_CONFIG_FILENAME
) -> Dict[str, Any]:
@@ -712,37 +653,12 @@ def load_config(
if cache_key in _CONFIG_CACHE:
return _CONFIG_CACHE[cache_key]
# 1. Try loading from database first
# Load from database
db_config = get_config_all()
if db_config:
_CONFIG_CACHE[cache_key] = db_config
return db_config
# 2. If DB is empty, try loading from legacy config.conf
if config_path.exists():
if config_path.suffix.lower() != ".conf":
log(f"Unsupported config format: {config_path.name} (only .conf is supported)")
return {}
try:
config = _load_conf_config(base_dir, config_path)
# Migrate to database
migrate_conf_to_db(config)
# Optional: Rename old config file to mark as migrated
try:
migrated_path = config_path.with_name(config_path.name + ".migrated")
config_path.rename(migrated_path)
log(f"Legacy config file renamed to {migrated_path.name}")
except Exception as e:
log(f"Could not rename legacy config file: {e}")
_CONFIG_CACHE[cache_key] = config
return config
except Exception as e:
log(f"Failed to load legacy config at {config_path}: {e}")
return {}
return {}
@@ -771,18 +687,43 @@ def save_config(
base_dir = config_dir or SCRIPT_DIR
config_path = base_dir / filename
if config_path.suffix.lower() != ".conf":
raise RuntimeError(
f"Unsupported config format: {config_path.name} (only .conf is supported)"
)
# Safety Check: placeholder (folder store validation removed)
_validate_config_safety(config)
# 1. Save to Database
try:
config_path.write_text(_serialize_conf(config), encoding="utf-8")
except OSError as exc:
raise RuntimeError(f"Failed to write config to {config_path}: {exc}") from exc
from SYS.database import db, save_config_value
# We want to clear and re-save or just update?
# For simplicity, we'll iterate and update.
for key, value in config.items():
if key in ('store', 'provider', 'tool'):
if isinstance(value, dict):
for subtype, instances in value.items():
if isinstance(instances, dict):
# provider/tool are usually config[cat][subtype][key]
# but store is config['store'][subtype][name][key]
if key == 'store':
for name, settings in instances.items():
if isinstance(settings, dict):
for k, v in settings.items():
save_config_value(key, subtype, name, k, v)
else:
for k, v in instances.items():
save_config_value(key, subtype, "default", k, v)
else:
# global settings
if not key.startswith("_"):
save_config_value("global", "none", "none", key, value)
except Exception as e:
log(f"Failed to save config to database: {e}")
# 2. Legacy fallback: write to .conf for now (optional, but keep for backward compat for a bit)
if config_path.suffix.lower() == ".conf":
# Safety Check: placeholder (folder store validation removed)
_validate_config_safety(config)
try:
config_path.write_text(_serialize_conf(config), encoding="utf-8")
except OSError as exc:
log(f"Failed to write legacy config to {config_path}: {exc}")
cache_key = _make_cache_key(config_dir, filename, config_path)
_CONFIG_CACHE[cache_key] = config