175 lines
6.8 KiB
Python
175 lines
6.8 KiB
Python
"""Revision-checked image settings; new bundled assets never replace user edits."""
|
|
|
|
from uuid import uuid4
|
|
|
|
from fastapi import HTTPException
|
|
from sqlalchemy import select
|
|
from sqlalchemy.dialects.postgresql import insert
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.request_context import get_request_id
|
|
from app.models.system_log import AuditLog
|
|
from app.models.system_setting import SystemSetting
|
|
from app.models.user import User
|
|
from app.schemas.card_images import CardImageConfiguration
|
|
from app.services.card_image_defaults import (
|
|
bundled_configuration,
|
|
previous_bundled_assets,
|
|
previous_bundled_rules,
|
|
)
|
|
|
|
CATEGORY = "earth_card_images"
|
|
|
|
|
|
def effective_envelope(payload: dict | None) -> dict:
|
|
defaults, version = bundled_configuration()
|
|
config = (
|
|
CardImageConfiguration.model_validate(payload["config"])
|
|
if payload
|
|
else defaults.model_copy(deep=True)
|
|
)
|
|
if payload:
|
|
previous = previous_bundled_assets()
|
|
latest = {asset.id: asset for asset in defaults.assets}
|
|
for index, asset in enumerate(config.assets):
|
|
old = next((item for item in previous.get(asset.id, []) if item.url == asset.url), None)
|
|
# Replace the old bundled source while preserving fields the user
|
|
# changed (crop, title, enabled state, etc.). Custom URLs are untouched.
|
|
if old is not None and asset.url == old.url and asset.id in latest:
|
|
overrides = {
|
|
key: value
|
|
for key, value in asset.model_dump().items()
|
|
if value != getattr(old, key)
|
|
}
|
|
config.assets[index] = latest[asset.id].model_copy(update=overrides, deep=True)
|
|
known_assets = set(payload.get("known_assets", []))
|
|
asset_ids = {asset.id for asset in config.assets}
|
|
config.assets.extend(
|
|
asset.model_copy(deep=True)
|
|
for asset in defaults.assets
|
|
if asset.id not in known_assets and asset.id not in asset_ids
|
|
)
|
|
prior_rules = previous_bundled_rules()
|
|
latest_rules = {rule.id: rule for rule in defaults.rules}
|
|
for index, rule in enumerate(config.rules):
|
|
old_rule = prior_rules.get(rule.id)
|
|
if (
|
|
old_rule
|
|
and rule.id in latest_rules
|
|
and rule.target() == old_rule.target()
|
|
and rule.asset_id == old_rule.asset_id
|
|
):
|
|
overrides = {
|
|
key: value
|
|
for key, value in rule.model_dump().items()
|
|
if value != getattr(old_rule, key)
|
|
}
|
|
config.rules[index] = latest_rules[rule.id].model_copy(update=overrides, deep=True)
|
|
known_rules = set(payload.get("known_rules", []))
|
|
rule_ids = {rule.id for rule in config.rules}
|
|
targets = {rule.target() for rule in config.rules}
|
|
available = {asset.id for asset in config.assets}
|
|
config.rules.extend(
|
|
rule.model_copy(deep=True)
|
|
for rule in defaults.rules
|
|
if rule.id not in known_rules
|
|
and rule.id not in rule_ids
|
|
and rule.target() not in targets
|
|
and rule.asset_id in available
|
|
)
|
|
return {
|
|
"config": config.model_dump(mode="json"),
|
|
"revision": f"{version}:{payload['revision'] if payload else 'default'}",
|
|
"is_default": payload is None,
|
|
}
|
|
|
|
|
|
async def read_configuration(db: AsyncSession) -> dict:
|
|
record = (
|
|
await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY))
|
|
).scalar_one_or_none()
|
|
return effective_envelope(record.payload if record else None)
|
|
|
|
|
|
async def publish_configuration(
|
|
db: AsyncSession, revision: str, config: CardImageConfiguration, actor: User
|
|
) -> dict:
|
|
defaults, _ = bundled_configuration()
|
|
pending = {asset.id for asset in defaults.assets if asset.rights_status == "permission_pending"}
|
|
if any(
|
|
asset.id in pending and asset.rights_status != "permission_pending"
|
|
for asset in config.assets
|
|
):
|
|
raise HTTPException(422, "Bundled image permission is still unverified")
|
|
initial = {
|
|
"config": defaults.model_dump(mode="json"),
|
|
"revision": "default",
|
|
"known_assets": [],
|
|
"known_rules": [],
|
|
}
|
|
await db.execute(
|
|
insert(SystemSetting)
|
|
.values(category=CATEGORY, payload=initial)
|
|
.on_conflict_do_nothing(index_elements=[SystemSetting.category])
|
|
)
|
|
record = (
|
|
await db.execute(
|
|
select(SystemSetting).where(SystemSetting.category == CATEGORY).with_for_update()
|
|
)
|
|
).scalar_one()
|
|
if effective_envelope(record.payload)["revision"] != revision:
|
|
await db.rollback()
|
|
raise HTTPException(409, "Configuration changed. Reload before saving your edits.")
|
|
before = record.payload
|
|
record.payload = {
|
|
"config": config.model_dump(mode="json"),
|
|
"revision": uuid4().hex,
|
|
"known_assets": [asset.id for asset in defaults.assets],
|
|
"known_rules": [rule.id for rule in defaults.rules],
|
|
}
|
|
db.add(
|
|
AuditLog(
|
|
actor_id=actor.id,
|
|
actor_name=actor.username,
|
|
action="card_images.update",
|
|
target_type="system_setting",
|
|
target_id=CATEGORY,
|
|
result="success",
|
|
request_id=get_request_id(),
|
|
details={"before": before, "after": record.payload},
|
|
)
|
|
)
|
|
await db.commit()
|
|
return effective_envelope(record.payload)
|
|
|
|
|
|
def resolve_image(config: CardImageConfiguration, context: dict[str, str]) -> dict:
|
|
assets = {asset.id: asset for asset in config.assets}
|
|
for scope in ("object", "model", "group", "category"):
|
|
value = context.get("entity_id" if scope == "object" else scope)
|
|
values = [value] if value else []
|
|
if scope == "category" and value != "*":
|
|
values.append("*")
|
|
for value in values:
|
|
value = value if scope == "object" else value.casefold()
|
|
rule = next(
|
|
(
|
|
rule
|
|
for rule in config.rules
|
|
if rule.enabled
|
|
and rule.entity_type == context["entity_type"]
|
|
and rule.scope == scope
|
|
and rule.value == value
|
|
),
|
|
None,
|
|
)
|
|
if not rule:
|
|
continue
|
|
match = {"scope": scope, "value": value, "rule_id": rule.id}
|
|
if rule.suppress:
|
|
return {"image": None, "match": match, "suppressed": True}
|
|
asset = assets.get(rule.asset_id)
|
|
if asset and asset.enabled:
|
|
return {"image": asset.model_dump(mode="json"), "match": match, "suppressed": False}
|
|
return {"image": None, "match": None, "suppressed": False}
|