Files
notify-bridge/packages/server/src/notify_bridge_server/api/delete_protection.py
T
alexei.dolgolyov a7a2b4efa4 feat: large polish pass — UX fixes, per-chat scope, restore/backup, action events
Backend
- Per-chat album scope for Immich commands (search/latest/memory/...): new
  allowed_album_ids on CommandTrackerListener, threaded listener/page kwargs
  through ProviderCommandHandler.handle; PATCH listener-scope endpoint.
- /search and /find accept a trailing page number; Immich client search_smart
  / search_metadata take a page param.
- Immich person-asset lookup switched from removed GET /api/people/{id}/assets
  to POST /api/search/metadata with personIds (fixes /person command and
  auto_organize rules silently returning zero candidates on Immich 1.106+).
- Auto_organize rule now sets the target album's thumbnail to the first added
  image when missing (falls back to any asset type); failures do not fail the
  rule. add_assets_to_album surfaces the Immich error body on non-2xx.
- EventLog.user_id / action_id / action_name columns with defensive migration
  + backfill. Status query filters by user_id directly; Immich/webhook paths
  emit user_id explicitly. action_runner writes an action_success/partial/
  failed event on each non-dry-run.
- Dashboard DELETE /api/status/events (scoped to user_id) + rendering live
  tracker/provider/action names via FK join with snapshot fallback.
- PATCH /api/users/{id} for username/role change with last-admin guard.
- Deletion protection returns structured {message, entity, blocked_by}
  (ApiError carries .blockedBy; frontend opens BlockedByModal).
- Backup prepare-restore → AppSetting markers + atomic write of
  pending_restore.json; lifespan hook applies on next startup and archives
  under data/applied_restores/. apply-restart sends SIGTERM so the lifespan
  shutdown runs; NOTIFY_BRIDGE_SUPERVISED env override gates the button.
  Manual POST /api/backup/files (same format as scheduled).
- New periodic-summary test path reuses shared collect_scheduled_assets
  (limit=0) so test and future production code go through one primitive.
- Per-receiver locale for Telegram test messages (resolves
  TelegramChat.language_override per chat instead of applying the first
  receiver's locale to everyone).
- Bounded concurrency (semaphores) in NotificationDispatcher._preload_asset_data
  and _refresh_telegram_chat_titles; chat title sweep extended to 24h since
  save_chat_from_webhook covers active chats opportunistically.
- Telegram poller detects the \"webhook is active\" 409 and auto-calls
  deleteWebhook for bots whose DB update_mode is polling (throttled per bot).
- TelegramClient.get_chat added (CLAUDE.md rule 6); set_album_thumbnail added.
- Seeds: rename \"Default Commands\" → \"Default Immich Commands\";
  track_assets_removed default False.

Frontend
- Global provider selector visible when there is only one provider.
- Clear-events button + i18n + ConfirmModal on the dashboard; new icons/
  labels/filters/colors for action_success / action_partial / action_failed.
- Auto-select first available tracking/template/command/config + bot on
  create forms (trackers, command-trackers, targets, template/command
  configs).
- Telegram target disable_url_preview defaults to true.
- BlockedByModal wired into 8 deletion flows; fetchAuth helper for
  multipart/binary calls (reuses api()'s refresh + ApiError mapping).
- Immich tracker 'Checking links' parallelised (concurrency cap 6).
- Backup page: pending-restore banner + Apply-now / Apply-later modal,
  restarting overlay polling /api/health, manual 'Create backup' button.
- Command-trackers listener row gets an 'Edit album scope' modal with
  inherit/explicit multiselect.
- Users page: Edit user modal (username + role).
- parseDate helper for consistent UTC date rendering.

Migrations / schema
- event_log: + user_id, action_id, action_name (+ backfill user_id from
  notification_tracker).
- command_tracker_listener: + allowed_album_ids.
2026-04-22 01:13:11 +03:00

177 lines
6.4 KiB
Python

"""Delete protection — prevents deletion of entities that are in use.
Each check function returns a list of consumer descriptions. If non-empty,
the entity cannot be deleted.
"""
from fastapi import HTTPException, status
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from ..database.models import (
CommandConfig,
CommandTracker,
CommandTrackerListener,
NotificationTarget,
NotificationTracker,
NotificationTrackerTarget,
)
def raise_if_used(consumers: list[str], entity_name: str) -> None:
"""Raise 409 Conflict if the entity has consumers.
Produces a human-readable summary string (kept as the primary ``detail``)
plus a structured ``blocked_by`` list so the frontend can render a
clickable warning modal.
"""
if consumers:
summary = f"Cannot delete {entity_name}: used by {len(consumers)} consumer(s)."
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail={
"message": summary,
"entity": entity_name,
"blocked_by": consumers,
},
)
async def check_service_provider(session: AsyncSession, provider_id: int) -> list[str]:
"""Check if a ServiceProvider is used by any trackers."""
consumers = []
result = await session.exec(
select(NotificationTracker).where(NotificationTracker.provider_id == provider_id)
)
for t in result.all():
consumers.append(f"Notification Tracker: {t.name}")
result = await session.exec(
select(CommandTracker).where(CommandTracker.provider_id == provider_id)
)
for t in result.all():
consumers.append(f"Command Tracker: {t.name}")
return consumers
async def check_telegram_bot(session: AsyncSession, bot_id: int) -> list[str]:
"""Check if a TelegramBot is used by any targets or command listeners."""
consumers = []
# Check notification targets with this bot in config
result = await session.exec(
select(NotificationTarget).where(NotificationTarget.type == "telegram")
)
for t in result.all():
if t.config.get("bot_id") == bot_id:
consumers.append(f"Target: {t.name}")
# Check command tracker listeners
result = await session.exec(
select(CommandTrackerListener).where(
CommandTrackerListener.listener_type == "telegram_bot",
CommandTrackerListener.listener_id == bot_id,
)
)
for listener in result.all():
tracker = await session.get(CommandTracker, listener.command_tracker_id)
name = tracker.name if tracker else f"#{listener.command_tracker_id}"
consumers.append(f"Command Tracker Listener: {name}")
return consumers
async def check_email_bot(session: AsyncSession, bot_id: int) -> list[str]:
"""Check if an EmailBot is used by any targets."""
consumers = []
result = await session.exec(
select(NotificationTarget).where(NotificationTarget.type == "email")
)
for t in result.all():
if t.config.get("email_bot_id") == bot_id:
consumers.append(f"Target: {t.name}")
return consumers
async def check_matrix_bot(session: AsyncSession, bot_id: int) -> list[str]:
"""Check if a MatrixBot is used by any targets."""
consumers = []
result = await session.exec(
select(NotificationTarget).where(NotificationTarget.type == "matrix")
)
for t in result.all():
if t.config.get("matrix_bot_id") == bot_id:
consumers.append(f"Target: {t.name}")
return consumers
async def check_tracking_config(session: AsyncSession, config_id: int) -> list[str]:
"""Check if a TrackingConfig is used by any tracker-target links."""
consumers = []
result = await session.exec(
select(NotificationTrackerTarget).where(
NotificationTrackerTarget.tracking_config_id == config_id
)
)
for tt in result.all():
tracker = await session.get(NotificationTracker, tt.tracker_id)
target = await session.get(NotificationTarget, tt.target_id)
tracker_name = tracker.name if tracker else f"#{tt.tracker_id}"
target_name = target.name if target else f"#{tt.target_id}"
consumers.append(f"Tracker Link: {tracker_name}{target_name}")
return consumers
async def check_template_config(session: AsyncSession, config_id: int) -> list[str]:
"""Check if a TemplateConfig is used by any tracker-target links."""
consumers = []
result = await session.exec(
select(NotificationTrackerTarget).where(
NotificationTrackerTarget.template_config_id == config_id
)
)
for tt in result.all():
tracker = await session.get(NotificationTracker, tt.tracker_id)
target = await session.get(NotificationTarget, tt.target_id)
tracker_name = tracker.name if tracker else f"#{tt.tracker_id}"
target_name = target.name if target else f"#{tt.target_id}"
consumers.append(f"Tracker Link: {tracker_name}{target_name}")
return consumers
async def check_command_template_config(session: AsyncSession, config_id: int) -> list[str]:
"""Check if a CommandTemplateConfig is used by any command configs."""
consumers = []
result = await session.exec(
select(CommandConfig).where(
CommandConfig.command_template_config_id == config_id
)
)
for c in result.all():
consumers.append(f"Command Config: {c.name}")
return consumers
async def check_command_config(session: AsyncSession, config_id: int) -> list[str]:
"""Check if a CommandConfig is used by any command trackers."""
consumers = []
result = await session.exec(
select(CommandTracker).where(CommandTracker.command_config_id == config_id)
)
for t in result.all():
consumers.append(f"Command Tracker: {t.name}")
return consumers
async def check_notification_target(session: AsyncSession, target_id: int) -> list[str]:
"""Check if a NotificationTarget is used by any tracker-target links."""
consumers = []
result = await session.exec(
select(NotificationTrackerTarget).where(
NotificationTrackerTarget.target_id == target_id
)
)
for tt in result.all():
tracker = await session.get(NotificationTracker, tt.tracker_id)
name = tracker.name if tracker else f"#{tt.tracker_id}"
consumers.append(f"Notification Tracker: {name}")
return consumers