feat: Discord/Slack/ntfy/Matrix targets, command templates, delete protection, email/matrix bots

- Discord, Slack, ntfy, Matrix notification target types with clients and dispatch
- MatrixBot model + API + frontend in Bots tab
- Command template system fully wired into all handler commands
- Default command templates seeded (EN/RU, 14 slots each)
- Command template editor with variables reference including child fields
- Delete protection on all 10 entity types (409 with consumer details)
- Provider type selector on template config forms
- Target type selector as dropdown with all 7 types
- Response template selector on command config form
- CLAUDE.md: mandatory server restart rule, child properties rule
This commit is contained in:
2026-03-21 20:36:12 +03:00
parent 846d480d38
commit 3e3a6f0777
64 changed files with 1861 additions and 180 deletions
@@ -107,18 +107,9 @@ async def delete_command_config(
session: AsyncSession = Depends(get_session),
):
"""Delete a command config. Fails if in use by any command tracker."""
from .delete_protection import check_command_config, raise_if_used
config = await _get_user_config(session, config_id, user.id)
# Check if any command tracker references this config
result = await session.exec(
select(CommandTracker).where(CommandTracker.command_config_id == config_id)
)
if result.first():
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Cannot delete: command config is in use by a command tracker",
)
raise_if_used(await check_command_config(session, config.id), config.name)
await session.delete(config)
await session.commit()
@@ -95,6 +95,103 @@ async def _get(session: AsyncSession, config_id: int, user_id: int) -> CommandTe
# Routes
# ---------------------------------------------------------------------------
@router.get("/variables")
async def get_command_variables():
"""Get variable reference for each command template slot."""
common_vars = {
"locale": "Current locale (en/ru)",
}
asset_fields = {
"id": "Asset ID (UUID)",
"originalFileName": "Original filename",
"type": "IMAGE or VIDEO",
"createdAt": "Creation date/time (ISO 8601)",
"year": "Year of the memory (memory command only)",
}
album_fields = {
"name": "Album name",
"asset_count": "Number of assets in the album",
"id": "Album ID (UUID)",
}
command_fields = {
"name": "Command name (e.g. status, albums)",
"description": "Command description text",
}
event_fields = {
"type": "Event type (assets_added, assets_removed, etc.)",
"album": "Album/collection name",
"count": "Number of affected assets",
"date": "Event date/time string (MM/DD HH:MM)",
}
assets_slot = lambda desc: {
"description": desc,
"variables": {**common_vars, "assets": "List of asset dicts (use {% for asset in assets %})", "count": "Number of results"},
"asset_fields": asset_fields,
}
return {
"start": {
"description": "/start greeting message",
"variables": {**common_vars, "bot_name": "Bot display name"},
},
"help": {
"description": "/help command listing",
"variables": {**common_vars, "commands": "List of command dicts (use {% for cmd in commands %})"},
"command_fields": command_fields,
},
"status": {
"description": "/status tracker summary",
"variables": {
**common_vars,
"trackers_active": "Number of active trackers",
"trackers_total": "Total tracker count",
"total_albums": "Total tracked albums",
"last_event": "Last event timestamp string",
},
},
"albums": {
"description": "/albums tracked albums list",
"variables": {**common_vars, "albums": "List of album dicts (use {% for album in albums %})"},
"album_fields": album_fields,
},
"events": {
"description": "/events recent events",
"variables": {**common_vars, "events": "List of event dicts (use {% for event in events %})"},
"event_fields": event_fields,
},
"people": {
"description": "/people detected people",
"variables": {**common_vars, "people": "List of name strings (use {% for name in people %})"},
},
"search": {
**assets_slot("/search, /find, /person, /place results"),
"variables": {**common_vars, "assets": "List of asset dicts (use {% for asset in assets %})", "query": "Search query", "command": "Actual command name (search/find/person/place)", "count": "Number of results"},
},
"latest": assets_slot("/latest recent photos"),
"favorites": assets_slot("/favorites starred items"),
"random": assets_slot("/random random photos"),
"summary": {
"description": "/summary album summary",
"variables": {**common_vars, "albums": "List of album dicts (use {% for album in albums %})"},
"album_fields": album_fields,
},
"memory": {
"description": "/memory On This Day photos",
"variables": {**common_vars, "assets": "List of asset dicts with year field (use {% for asset in assets %})", "count": "Number of results"},
"asset_fields": asset_fields,
},
"rate_limited": {
"description": "Rate limit warning message",
"variables": {**common_vars, "wait": "Seconds to wait before retry"},
},
"no_results": {
"description": "Empty results fallback",
"variables": {**common_vars, "command": "Command name", "query": "Search query (empty for non-search commands)"},
},
}
@router.get("")
async def list_configs(
provider_type: str | None = None,
@@ -168,7 +265,9 @@ async def delete_config(
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
from .delete_protection import check_command_template_config, raise_if_used
config = await _get(session, config_id, user.id)
raise_if_used(await check_command_template_config(session, config.id), config.name)
slot_result = await session.exec(
select(CommandTemplateSlot).where(CommandTemplateSlot.config_id == config.id)
)
@@ -189,28 +288,42 @@ async def preview_raw(
):
"""Render arbitrary Jinja2 template text with sample command context."""
sample_ctx = {
# /start
"bot_name": "NotifyBridgeBot",
"locale": "en",
# /status
"trackers_active": 2,
"trackers_total": 3,
"total_albums": 5,
"last_event": "2026-03-19 14:30",
# /help
"commands": [
{"name": "status", "description": "Show tracker status"},
{"name": "albums", "description": "List tracked albums"},
{"name": "latest", "description": "Show latest photos"},
],
# /albums, /summary
"albums": [
{"name": "Family Photos", "asset_count": 142, "url": "https://example.com/albums/1"},
{"name": "Vacation 2025", "asset_count": 87, "url": "https://example.com/albums/2"},
{"name": "Family Photos", "asset_count": 142, "id": "abc-123"},
{"name": "Vacation 2025", "asset_count": 87, "id": "def-456"},
],
# /events
"events": [
{"type": "assets_added", "album": "Family Photos", "count": 3, "date": "2026-03-19 14:30"},
{"type": "assets_removed", "album": "Vacation 2025", "count": 1, "date": "2026-03-19 12:00"},
{"type": "assets_added", "album": "Family Photos", "count": 3, "date": "03/19 14:30"},
{"type": "assets_removed", "album": "Vacation 2025", "count": 1, "date": "03/19 12:00"},
],
# /people
"people": ["Alice", "Bob", "Charlie"],
# /search, /find, /person, /place, /latest, /favorites, /random, /memory
"assets": [
{"filename": "IMG_001.jpg", "type": "IMAGE", "created_at": "2026-03-19T14:30:00"},
{"filename": "VID_002.mp4", "type": "VIDEO", "created_at": "2026-03-19T15:00:00"},
{"id": "a1", "originalFileName": "IMG_001.jpg", "type": "IMAGE", "createdAt": "2026-03-19T14:30:00", "year": 2024},
{"id": "a2", "originalFileName": "VID_002.mp4", "type": "VIDEO", "createdAt": "2026-03-19T15:00:00", "year": 2023},
],
"search_query": "sunset",
"search_results_count": 5,
"command": "status",
"bot_name": "NotifyBridgeBot",
"locale": "en",
"query": "sunset",
"command": "search",
"count": 2,
# /rate_limited
"wait": 15,
}
try:
@@ -0,0 +1,179 @@
"""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,
TargetReceiver,
TelegramChat,
)
def raise_if_used(consumers: list[str], entity_name: str) -> None:
"""Raise 409 Conflict if the entity has consumers."""
if consumers:
detail = f"Cannot delete {entity_name}: used by {len(consumers)} consumer(s). " + "; ".join(consumers)
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=detail)
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))
for t in result.all():
if t.config.get("bot_id") == bot_id or t.config.get("bot_token"):
# Need to verify it's actually this bot
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
async def check_notification_tracker(session: AsyncSession, tracker_id: int) -> list[str]:
"""Check if a NotificationTracker has any linked targets."""
consumers = []
result = await session.exec(
select(NotificationTrackerTarget).where(
NotificationTrackerTarget.tracker_id == tracker_id
)
)
for tt in result.all():
target = await session.get(NotificationTarget, tt.target_id)
name = target.name if target else f"#{tt.target_id}"
consumers.append(f"Linked Target: {name}")
return consumers
@@ -94,7 +94,9 @@ async def delete_email_bot(
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
from .delete_protection import check_email_bot, raise_if_used
bot = await _get_user_bot(session, bot_id, user.id)
raise_if_used(await check_email_bot(session, bot.id), bot.name)
await session.delete(bot)
await session.commit()
@@ -0,0 +1,156 @@
"""Matrix bot management API routes."""
import logging
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from ..auth.dependencies import get_current_user
from ..database.engine import get_session
from ..database.models import MatrixBot, User
_LOGGER = logging.getLogger(__name__)
router = APIRouter(prefix="/api/matrix-bots", tags=["matrix-bots"])
class MatrixBotCreate(BaseModel):
name: str
icon: str = ""
homeserver_url: str
access_token: str
display_name: str = ""
class MatrixBotUpdate(BaseModel):
name: str | None = None
icon: str | None = None
homeserver_url: str | None = None
access_token: str | None = None
display_name: str | None = None
@router.get("")
async def list_matrix_bots(
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
result = await session.exec(
select(MatrixBot).where(MatrixBot.user_id == user.id)
)
return [_response(b) for b in result.all()]
@router.post("", status_code=status.HTTP_201_CREATED)
async def create_matrix_bot(
body: MatrixBotCreate,
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
bot = MatrixBot(user_id=user.id, **body.model_dump())
session.add(bot)
await session.commit()
await session.refresh(bot)
return _response(bot)
@router.get("/{bot_id}")
async def get_matrix_bot(
bot_id: int,
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
return _response(await _get_user_bot(session, bot_id, user.id))
@router.put("/{bot_id}")
async def update_matrix_bot(
bot_id: int,
body: MatrixBotUpdate,
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
bot = await _get_user_bot(session, bot_id, user.id)
for field, value in body.model_dump(exclude_unset=True).items():
setattr(bot, field, value)
session.add(bot)
await session.commit()
await session.refresh(bot)
return _response(bot)
@router.delete("/{bot_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_matrix_bot(
bot_id: int,
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
from .delete_protection import check_matrix_bot, raise_if_used
bot = await _get_user_bot(session, bot_id, user.id)
raise_if_used(await check_matrix_bot(session, bot.id), bot.name)
await session.delete(bot)
await session.commit()
@router.post("/{bot_id}/test")
async def test_matrix_bot(
bot_id: int,
room_id: str = "",
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
"""Test Matrix bot connection by sending a message to a room.
If room_id is not provided, just verifies the access token by calling /whoami.
"""
bot = await _get_user_bot(session, bot_id, user.id)
import aiohttp
async with aiohttp.ClientSession() as http:
# Verify token with /whoami
whoami_url = f"{bot.homeserver_url.rstrip('/')}/_matrix/client/v3/account/whoami"
headers = {"Authorization": f"Bearer {bot.access_token}"}
try:
async with http.get(whoami_url, headers=headers) as resp:
if resp.status != 200:
body = await resp.text()
return {"success": False, "error": f"Auth failed: HTTP {resp.status}{body[:200]}"}
whoami = await resp.json()
except aiohttp.ClientError as e:
return {"success": False, "error": f"Connection failed: {e}"}
result = {"success": True, "user_id": whoami.get("user_id", "")}
# Optionally send a test message
if room_id:
from notify_bridge_core.notifications.matrix.client import MatrixClient
client = MatrixClient(http, bot.homeserver_url, bot.access_token)
send_result = await client.send_message(
room_id,
"Test message from Notify Bridge",
html_message="<b>Test message</b> from Notify Bridge",
)
result["send_result"] = send_result
return result
def _response(bot: MatrixBot) -> dict:
return {
"id": bot.id,
"name": bot.name,
"icon": bot.icon,
"homeserver_url": bot.homeserver_url,
"access_token": f"{bot.access_token[:8]}...{bot.access_token[-4:]}" if len(bot.access_token) > 12 else "***",
"display_name": bot.display_name,
"created_at": bot.created_at.isoformat(),
}
async def _get_user_bot(session: AsyncSession, bot_id: int, user_id: int) -> MatrixBot:
bot = await session.get(MatrixBot, bot_id)
if not bot or bot.user_id != user_id:
raise HTTPException(status_code=404, detail="Matrix bot not found")
return bot
@@ -111,7 +111,9 @@ async def delete_notification_tracker(
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
from .delete_protection import check_notification_tracker, raise_if_used
tracker = await _get_user_tracker(session, tracker_id, user.id)
raise_if_used(await check_notification_tracker(session, tracker.id), tracker.name)
# Delete associated tracker-target links
result = await session.exec(
select(NotificationTrackerTarget).where(NotificationTrackerTarget.tracker_id == tracker_id)
@@ -189,7 +189,9 @@ async def delete_provider(
session: AsyncSession = Depends(get_session),
):
"""Delete a service provider."""
from .delete_protection import check_service_provider, raise_if_used
provider = await _get_user_provider(session, provider_id, user.id)
raise_if_used(await check_service_provider(session, provider.id), provider.name)
await session.delete(provider)
await session.commit()
@@ -31,13 +31,17 @@ class ReceiverUpdate(BaseModel):
def _receiver_key(target_type: str, config: dict[str, Any]) -> str:
"""Derive a unique key for deduplication from receiver config."""
if target_type == "telegram":
return str(config.get("chat_id", ""))
elif target_type == "webhook":
return config.get("url", "")
elif target_type == "email":
return config.get("email", "")
return ""
key_fields = {
"telegram": "chat_id",
"webhook": "url",
"email": "email",
"discord": "webhook_url",
"slack": "webhook_url",
"ntfy": "topic",
"matrix": "room_id",
}
field = key_fields.get(target_type, "")
return str(config.get(field, "")) if field else ""
@router.get("")
@@ -79,10 +79,11 @@ async def create_target(
session: AsyncSession = Depends(get_session),
):
"""Create a new notification target."""
if body.type not in ("telegram", "webhook", "email"):
valid_types = ("telegram", "webhook", "email", "discord", "slack", "ntfy", "matrix")
if body.type not in valid_types:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Type must be 'telegram', 'webhook', or 'email'",
detail=f"Type must be one of: {', '.join(valid_types)}",
)
target = NotificationTarget(
user_id=user.id,
@@ -132,15 +133,11 @@ async def delete_target(
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
"""Delete a notification target, its tracker links, and receivers."""
"""Delete a notification target. Fails if linked to any tracker."""
from .delete_protection import check_notification_target, raise_if_used
target = await _get_user_target(session, target_id, user.id)
# Delete associated tracker-target links
result = await session.exec(
select(NotificationTrackerTarget).where(NotificationTrackerTarget.target_id == target_id)
)
for tt in result.all():
await session.delete(tt)
# Delete receivers
raise_if_used(await check_notification_target(session, target.id), target.name)
# Delete child receivers
recv_result = await session.exec(
select(TargetReceiver).where(TargetReceiver.target_id == target_id)
)
@@ -124,7 +124,9 @@ async def delete_bot(
session: AsyncSession = Depends(get_session),
):
"""Delete a registered bot and its chats."""
from .delete_protection import check_telegram_bot, raise_if_used
bot = await _get_user_bot(session, bot_id, user.id)
raise_if_used(await check_telegram_bot(session, bot.id), bot.name)
# Delete associated chats
result = await session.exec(select(TelegramChat).where(TelegramChat.bot_id == bot_id))
for chat in result.all():
@@ -300,7 +300,9 @@ async def delete_config(
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
from .delete_protection import check_template_config, raise_if_used
config = await _get(session, config_id, user.id)
raise_if_used(await check_template_config(session, config.id), config.name)
# Delete child slots first
slot_result = await session.exec(
select(TemplateSlot).where(TemplateSlot.config_id == config.id)
@@ -152,7 +152,9 @@ async def delete_config(
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
from .delete_protection import check_tracking_config, raise_if_used
config = await _get(session, config_id, user.id)
raise_if_used(await check_tracking_config(session, config.id), config.name)
await session.delete(config)
await session.commit()