Files
notify-bridge/packages/server/src/notify_bridge_server/database/seeds.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

403 lines
14 KiB
Python

"""Database seed functions — create/update system-owned defaults on startup."""
import json
import logging
from datetime import datetime, timezone
from sqlalchemy import text
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from .engine import get_engine
from .models import (
CommandConfig,
CommandTemplateConfig,
CommandTemplateSlot,
TemplateConfig,
TemplateSlot,
TrackingConfig,
)
_LOGGER = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
async def _seed_provider_template(
session: AsyncSession,
provider_type: str,
label: str,
) -> None:
"""Seed templates for a single provider type across all locales.
Creates a single TemplateConfig per provider with locale-aware slots
(each slot has an EN and RU version stored as separate rows).
"""
from notify_bridge_core.templates.defaults import load_default_templates
result = await session.exec(
select(TemplateConfig).where(
TemplateConfig.user_id == 0,
TemplateConfig.provider_type == provider_type,
)
)
configs = result.all()
if not configs:
config = TemplateConfig(
user_id=0,
provider_type=provider_type,
name=f"Default {label}",
description=f"Default {label} templates",
)
session.add(config)
await session.flush()
else:
config = configs[0]
for locale in ("en", "ru"):
slots = load_default_templates(locale, provider_type=provider_type)
if not slots:
continue
for slot_name, template_text in slots.items():
slot_result = await session.exec(
select(TemplateSlot).where(
TemplateSlot.config_id == config.id,
TemplateSlot.slot_name == slot_name,
TemplateSlot.locale == locale,
)
)
existing = slot_result.first()
if existing:
existing.template = template_text
session.add(existing)
else:
session.add(TemplateSlot(
config_id=config.id,
slot_name=slot_name,
locale=locale,
template=template_text,
))
async def _seed_provider_command_template(
session: AsyncSession,
provider_type: str,
name: str,
description: str,
) -> None:
"""Seed command templates for a single provider type across all locales."""
from notify_bridge_core.templates.command_defaults import load_default_command_templates
result = await session.exec(
select(CommandTemplateConfig).where(
CommandTemplateConfig.user_id == 0,
CommandTemplateConfig.provider_type == provider_type,
)
)
configs = result.all()
if not configs:
config = CommandTemplateConfig(
user_id=0,
provider_type=provider_type,
name=name,
description=description,
)
session.add(config)
await session.flush()
else:
config = configs[0]
if config.name != name or config.description != description:
config.name = name
config.description = description
session.add(config)
for locale in ("en", "ru"):
slots = load_default_command_templates(locale, provider_type=provider_type)
if not slots:
continue
for slot_name, template_text in slots.items():
slot_result = await session.exec(
select(CommandTemplateSlot).where(
CommandTemplateSlot.config_id == config.id,
CommandTemplateSlot.slot_name == slot_name,
CommandTemplateSlot.locale == locale,
)
)
existing = slot_result.first()
if existing:
existing.template = template_text
session.add(existing)
else:
session.add(CommandTemplateSlot(
config_id=config.id,
slot_name=slot_name,
locale=locale,
template=template_text,
))
# ---------------------------------------------------------------------------
# Top-level seed functions
# ---------------------------------------------------------------------------
async def _seed_default_templates() -> None:
"""Seed or update default (system-owned) templates on startup.
Uses TemplateSlot child rows for template content.
"""
engine = get_engine()
async with AsyncSession(engine) as session:
await _seed_provider_template(session, "immich", "Immich")
await _seed_provider_template(session, "gitea", "Gitea")
await _seed_provider_template(session, "planka", "Planka")
await _seed_provider_template(session, "scheduler", "Scheduler")
await _seed_provider_template(session, "nut", "NUT")
await _seed_provider_template(session, "google_photos", "Google Photos")
await _seed_provider_template(session, "webhook", "Generic Webhook")
await session.commit()
async def _seed_default_command_templates() -> None:
"""Seed or update default command response templates on startup.
Creates a single config per provider with locale-aware slots
(each slot has an EN and RU version stored as separate rows).
"""
engine = get_engine()
async with AsyncSession(engine) as session:
await _seed_provider_command_template(
session, "immich", "Default Immich Commands", "Default Immich command templates",
)
await _seed_provider_command_template(
session, "gitea", "Default Gitea Commands", "Default Gitea command templates",
)
await _seed_provider_command_template(
session, "planka", "Default Planka Commands", "Default Planka command templates",
)
await _seed_provider_command_template(
session, "nut", "Default NUT Commands", "Default NUT command templates",
)
await _seed_provider_command_template(
session, "google_photos", "Default Google Photos Commands", "Default Google Photos command templates",
)
await _seed_provider_command_template(
session, "webhook", "Default Webhook Commands", "Default Generic Webhook command templates",
)
await session.commit()
async def _seed_default_tracking_configs() -> None:
"""Seed system-owned default tracking configs for each provider type."""
engine = get_engine()
async with AsyncSession(engine) as session:
result = await session.exec(
select(TrackingConfig).where(TrackingConfig.user_id == 0)
)
existing = {c.provider_type: c for c in result.all()}
defaults = [
{
"provider_type": "gitea",
"name": "Default Gitea",
"track_push": True,
"track_issue_opened": True,
"track_issue_closed": True,
"track_issue_commented": False,
"track_pr_opened": True,
"track_pr_closed": True,
"track_pr_merged": True,
"track_pr_commented": False,
"track_release_published": True,
},
{
"provider_type": "planka",
"name": "Default Planka",
"track_card_created": True,
"track_card_updated": False,
"track_card_moved": True,
"track_card_deleted": False,
"track_card_commented": True,
"track_comment_updated": False,
"track_board_created": True,
"track_board_updated": False,
"track_board_deleted": True,
"track_list_created": False,
"track_list_updated": False,
"track_list_deleted": False,
"track_attachment_created": True,
"track_card_label_added": False,
"track_task_completed": True,
},
{
"provider_type": "scheduler",
"name": "Default Scheduler",
"track_scheduled_message": True,
},
{
"provider_type": "webhook",
"name": "Default Webhook",
"track_webhook_received": True,
},
{
"provider_type": "immich",
"name": "Default Immich",
"track_assets_added": True,
"track_assets_removed": False,
"track_collection_renamed": True,
"track_collection_deleted": True,
"track_sharing_changed": False,
},
{
"provider_type": "google_photos",
"name": "Default Google Photos",
"track_assets_added": True,
"track_assets_removed": False,
"track_collection_renamed": True,
"track_collection_deleted": True,
"track_sharing_changed": False,
},
{
"provider_type": "nut",
"name": "Default NUT",
"track_ups_online": True,
"track_ups_on_battery": True,
"track_ups_low_battery": True,
"track_ups_battery_restored": True,
"track_ups_comms_lost": True,
"track_ups_comms_restored": True,
"track_ups_replace_battery": True,
"track_ups_overload": True,
},
]
for cfg in defaults:
ptype = cfg["provider_type"]
if ptype in existing:
continue
session.add(TrackingConfig(user_id=0, **cfg))
await session.commit()
async def _seed_default_command_configs() -> None:
"""Seed system-owned default command configs for each provider type."""
engine = get_engine()
async with AsyncSession(engine) as session:
result = await session.exec(
select(CommandConfig).where(CommandConfig.user_id == 0)
)
existing = {c.provider_type: c for c in result.all()}
# Find system command template configs to link
tmpl_result = await session.exec(
select(CommandTemplateConfig).where(CommandTemplateConfig.user_id == 0)
)
tmpl_by_type = {t.provider_type: t.id for t in tmpl_result.all()}
defaults = [
{
"provider_type": "immich",
"name": "Default Immich",
"enabled_commands": [
"help", "status", "albums", "events", "latest",
"random", "favorites", "summary", "memory",
],
"response_mode": "media",
"default_count": 5,
"rate_limits": {"search": 30, "default": 10},
},
{
"provider_type": "gitea",
"name": "Default Gitea",
"enabled_commands": [
"help", "status", "repos", "issues", "prs", "commits",
],
"response_mode": "text",
"default_count": 10,
"rate_limits": {"api": 15, "default": 10},
},
{
"provider_type": "planka",
"name": "Default Planka",
"enabled_commands": [
"help", "status", "boards", "cards", "lists",
],
"response_mode": "text",
"default_count": 10,
"rate_limits": {"api": 15, "default": 10},
},
{
"provider_type": "nut",
"name": "Default NUT",
"enabled_commands": [
"help", "status", "devices", "battery",
],
"response_mode": "text",
"default_count": 5,
"rate_limits": {"api": 15, "default": 10},
},
{
"provider_type": "webhook",
"name": "Default Webhook",
"enabled_commands": ["help", "status"],
"response_mode": "text",
"default_count": 5,
"rate_limits": {"default": 10},
},
{
"provider_type": "google_photos",
"name": "Default Google Photos",
"enabled_commands": [
"help", "status", "albums", "latest", "search", "random",
],
"response_mode": "media",
"default_count": 5,
"rate_limits": {"search": 30, "default": 10},
},
]
for cfg in defaults:
ptype = cfg["provider_type"]
if ptype in existing:
continue
cmd_tmpl_id = tmpl_by_type.get(ptype)
await session.execute(
text(
"INSERT INTO command_config "
"(user_id, provider_type, name, icon, enabled_commands, locale, "
"response_mode, default_count, rate_limits, command_template_config_id, created_at) "
"VALUES (:uid, :pt, :name, :icon, :cmds, :locale, :rm, :dc, :rl, :ctid, :ca)"
),
{
"uid": 0,
"pt": ptype,
"name": cfg["name"],
"icon": "",
"cmds": json.dumps(cfg["enabled_commands"]),
"locale": "en",
"rm": cfg["response_mode"],
"dc": cfg["default_count"],
"rl": json.dumps(cfg["rate_limits"]),
"ctid": cmd_tmpl_id,
"ca": datetime.now(timezone.utc).isoformat(),
},
)
await session.commit()
# ---------------------------------------------------------------------------
# Public entry point
# ---------------------------------------------------------------------------
async def seed_all() -> None:
"""Run all seed functions in order."""
await _seed_default_templates()
await _seed_default_command_templates()
await _seed_default_tracking_configs()
await _seed_default_command_configs()