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()
@@ -192,31 +192,40 @@ async def handle_command(
for _, _, provider in ctx_tuples:
providers_map[provider.id] = provider
# Dispatch
# Dispatch — each handler returns (fallback_text, template_context)
# Template is tried first; if no template, fallback is returned.
if cmd == "help":
return _cmd_help(enabled, locale)
if cmd == "status":
return await _cmd_status(bot, providers_map, locale)
if cmd == "albums":
return await _cmd_albums(bot, providers_map, locale)
if cmd == "events":
return await _cmd_events(bot, providers_map, count, locale)
if cmd == "people":
return await _cmd_people(providers_map, locale)
if cmd in ("search", "find", "person", "place", "latest", "random",
"favorites", "summary", "memory"):
return await _cmd_immich(bot, cmd, args, count, locale, response_mode, providers_map)
fallback, ctx = _cmd_help(enabled, locale)
elif cmd == "status":
fallback, ctx = await _cmd_status(bot, providers_map, locale)
elif cmd == "albums":
fallback, ctx = await _cmd_albums(bot, providers_map, locale)
elif cmd == "events":
fallback, ctx = await _cmd_events(bot, providers_map, count, locale)
elif cmd == "people":
fallback, ctx = await _cmd_people(providers_map, locale)
elif cmd in ("search", "find", "person", "place", "latest", "random",
"favorites", "summary", "memory"):
return await _cmd_immich(bot, cmd, args, count, locale, response_mode, providers_map, cmd_templates)
else:
return None
return None
# Try template, fall back to hardcoded
rendered = _render_cmd_template(cmd_templates, cmd, {**ctx, "locale": locale})
return rendered if rendered else fallback
def _cmd_help(enabled: list[str], locale: str) -> str:
def _cmd_help(enabled: list[str], locale: str) -> tuple[str, dict]:
commands = []
lines = []
for cmd in enabled:
desc = COMMAND_DESCRIPTIONS.get(cmd, {})
lines.append(f"/{cmd}{desc.get(locale, desc.get('en', ''))}")
desc_text = desc.get(locale, desc.get("en", ""))
commands.append({"name": cmd, "description": desc_text})
lines.append(f"/{cmd}{desc_text}")
header = {"en": "Available commands:", "ru": "Доступные команды:"}
return header.get(locale, header["en"]) + "\n" + "\n".join(lines)
fallback = header.get(locale, header["en"]) + "\n" + "\n".join(lines)
return fallback, {"commands": commands}
async def _get_notification_trackers_for_providers(
@@ -264,7 +273,7 @@ async def _check_native_memory(bot: TelegramBot) -> bool:
return False
async def _cmd_status(bot: TelegramBot, providers_map: dict[int, ServiceProvider], locale: str) -> str:
async def _cmd_status(bot: TelegramBot, providers_map: dict[int, ServiceProvider], locale: str) -> tuple[str, dict]:
provider_ids = set(providers_map.keys())
trackers = await _get_notification_trackers_for_providers(provider_ids)
active = sum(1 for t in trackers if t.enabled)
@@ -279,27 +288,33 @@ async def _cmd_status(bot: TelegramBot, providers_map: dict[int, ServiceProvider
last_event = result.first()
last_str = last_event.created_at.strftime("%Y-%m-%d %H:%M") if last_event else "-"
ctx = {"trackers_active": active, "trackers_total": total, "total_albums": total_albums, "last_event": last_str}
if locale == "ru":
return (
fallback = (
f"📊 Статус\n"
f"Трекеры: {active}/{total} активных\n"
f"Альбомы: {total_albums}\n"
f"Последнее событие: {last_str}"
)
return (
f"📊 Status\n"
f"Trackers: {active}/{total} active\n"
f"Albums: {total_albums}\n"
f"Last event: {last_str}"
)
else:
fallback = (
f"📊 Status\n"
f"Trackers: {active}/{total} active\n"
f"Albums: {total_albums}\n"
f"Last event: {last_str}"
)
return fallback, ctx
async def _cmd_albums(bot: TelegramBot, providers_map: dict[int, ServiceProvider], locale: str) -> str:
async def _cmd_albums(bot: TelegramBot, providers_map: dict[int, ServiceProvider], locale: str) -> tuple[str, dict]:
provider_ids = set(providers_map.keys())
trackers = await _get_notification_trackers_for_providers(provider_ids)
if not trackers:
return "No tracked albums." if locale == "en" else "Нет отслеживаемых альбомов."
fallback = "No tracked albums." if locale == "en" else "Нет отслеживаемых альбомов."
return fallback, {"albums": []}
albums_data: list[dict] = []
lines = []
async with aiohttp.ClientSession() as http:
for tracker in trackers:
@@ -311,20 +326,23 @@ async def _cmd_albums(bot: TelegramBot, providers_map: dict[int, ServiceProvider
try:
album = await immich.client.get_album(album_id)
if album:
albums_data.append({"name": album.name, "asset_count": album.asset_count, "id": album_id})
lines.append(f"{album.name} ({album.asset_count} assets)")
except Exception:
lines.append(f"{album_id[:8]}... (error)")
header = "📚 Tracked albums:" if locale == "en" else "📚 Отслеживаемые альбомы:"
return header + "\n" + "\n".join(lines) if lines else header + "\n (none)"
fallback = header + "\n" + "\n".join(lines) if lines else header + "\n (none)"
return fallback, {"albums": albums_data}
async def _cmd_events(bot: TelegramBot, providers_map: dict[int, ServiceProvider], count: int, locale: str) -> str:
async def _cmd_events(bot: TelegramBot, providers_map: dict[int, ServiceProvider], count: int, locale: str) -> tuple[str, dict]:
provider_ids = set(providers_map.keys())
trackers = await _get_notification_trackers_for_providers(provider_ids)
tracker_ids = [t.id for t in trackers]
if not tracker_ids:
return "No events." if locale == "en" else "Нет событий."
fallback = "No events." if locale == "en" else "Нет событий."
return fallback, {"events": []}
engine = get_engine()
async with AsyncSession(engine) as session:
@@ -337,17 +355,22 @@ async def _cmd_events(bot: TelegramBot, providers_map: dict[int, ServiceProvider
events = result.all()
if not events:
return "No events yet." if locale == "en" else "Пока нет событий."
fallback = "No events yet." if locale == "en" else "Пока нет событий."
return fallback, {"events": []}
events_data = [{"type": e.event_type, "album": e.collection_name, "count": e.assets_count,
"date": e.created_at.strftime("%m/%d %H:%M")} for e in events]
header = f"📋 Last {len(events)} events:" if locale == "en" else f"📋 Последние {len(events)} событий:"
lines = []
for e in events:
ts = e.created_at.strftime("%m/%d %H:%M")
lines.append(f" {ts}{e.event_type}: {e.collection_name}")
return header + "\n" + "\n".join(lines)
fallback = header + "\n" + "\n".join(lines)
return fallback, {"events": events_data}
async def _cmd_people(providers_map: dict[int, ServiceProvider], locale: str) -> str:
async def _cmd_people(providers_map: dict[int, ServiceProvider], locale: str) -> tuple[str, dict]:
all_people: dict[str, str] = {}
async with aiohttp.ClientSession() as http:
@@ -359,16 +382,19 @@ async def _cmd_people(providers_map: dict[int, ServiceProvider], locale: str) ->
all_people.update(people)
if not all_people:
return "No people detected." if locale == "en" else "Люди не обнаружены."
fallback = "No people detected." if locale == "en" else "Люди не обнаружены."
return fallback, {"people": []}
names = sorted(all_people.values())
header = f"👥 {len(names)} people:" if locale == "en" else f"👥 {len(names)} людей:"
return header + "\n" + ", ".join(names)
fallback = header + "\n" + ", ".join(names)
return fallback, {"people": names}
async def _cmd_immich(
bot: TelegramBot, cmd: str, args: str, count: int, locale: str,
response_mode: str, providers_map: dict[int, ServiceProvider],
cmd_templates: dict[str, str] | None = None,
) -> str | list[dict[str, Any]]:
"""Handle commands that need Immich API access and may return media."""
if not providers_map:
@@ -398,13 +424,13 @@ async def _cmd_immich(
if not args:
return "Usage: /search <query>" if locale == "en" else "Использование: /search <запрос>"
assets = await client.search_smart(args, album_ids=all_album_ids, limit=count)
return _format_assets(assets, cmd, args, locale, response_mode, client)
return _format_assets(assets, cmd, args, locale, response_mode, client, cmd_templates)
if cmd == "find":
if not args:
return "Usage: /find <text>" if locale == "en" else "Использование: /find <текст>"
assets = await client.search_metadata(args, album_ids=all_album_ids, limit=count)
return _format_assets(assets, cmd, args, locale, response_mode, client)
return _format_assets(assets, cmd, args, locale, response_mode, client, cmd_templates)
if cmd == "person":
if not args:
@@ -418,7 +444,7 @@ async def _cmd_immich(
if not person_id:
return f"Person '{args}' not found." if locale == "en" else f"Человек '{args}' не найден."
assets = await client.search_by_person(person_id, limit=count)
return _format_assets(assets, cmd, args, locale, response_mode, client)
return _format_assets(assets, cmd, args, locale, response_mode, client, cmd_templates)
if cmd == "place":
if not args:
@@ -426,7 +452,7 @@ async def _cmd_immich(
assets = await client.search_smart(
f"photos taken in {args}", album_ids=all_album_ids, limit=count
)
return _format_assets(assets, cmd, args, locale, response_mode, client)
return _format_assets(assets, cmd, args, locale, response_mode, client, cmd_templates)
if cmd == "favorites":
fav_assets: list[dict[str, Any]] = []
@@ -444,7 +470,7 @@ async def _cmd_immich(
pass
if len(fav_assets) >= count:
break
return _format_assets(fav_assets, cmd, "", locale, response_mode, client)
return _format_assets(fav_assets, cmd, "", locale, response_mode, client, cmd_templates)
if cmd == "latest":
latest_assets: list[dict[str, Any]] = []
@@ -460,7 +486,7 @@ async def _cmd_immich(
except Exception:
pass
latest_assets.sort(key=lambda a: a.get("createdAt", ""), reverse=True)
return _format_assets(latest_assets[:count], cmd, "", locale, response_mode, client)
return _format_assets(latest_assets[:count], cmd, "", locale, response_mode, client, cmd_templates)
if cmd == "random":
random_assets: list[dict[str, Any]] = []
@@ -478,17 +504,22 @@ async def _cmd_immich(
except Exception:
pass
rng.shuffle(random_assets)
return _format_assets(random_assets[:count], cmd, "", locale, response_mode, client)
return _format_assets(random_assets[:count], cmd, "", locale, response_mode, client, cmd_templates)
if cmd == "summary":
albums_data: list[dict] = []
lines = []
for album_id in all_album_ids:
try:
album = await client.get_album(album_id)
if album:
albums_data.append({"name": album.name, "asset_count": album.asset_count, "id": album_id})
lines.append(f"{album.name}: {album.asset_count} assets")
except Exception:
pass
rendered = _render_cmd_template(cmd_templates or {}, "summary", {"albums": albums_data, "locale": locale})
if rendered:
return rendered
header = f"📋 Album summary ({len(lines)}):" if locale == "en" else f"📋 Сводка альбомов ({len(lines)}):"
return header + "\n" + "\n".join(lines) if lines else header
@@ -542,7 +573,7 @@ async def _cmd_immich(
memory_assets = memory_assets[:count]
if not memory_assets:
return "No memories for today." if locale == "en" else "Нет воспоминаний за сегодня."
return _format_assets(memory_assets, cmd, "", locale, response_mode, client)
return _format_assets(memory_assets, cmd, "", locale, response_mode, client, cmd_templates)
return "Unknown command." if locale == "en" else "Неизвестная команда."
@@ -550,9 +581,13 @@ async def _cmd_immich(
def _format_assets(
assets: list[dict[str, Any]], cmd: str, query: str,
locale: str, response_mode: str, client: Any,
cmd_templates: dict[str, str] | None = None,
) -> str | list[dict[str, Any]]:
"""Format asset results as text or media payload."""
if not assets:
rendered = _render_cmd_template(cmd_templates or {}, "no_results", {"command": cmd, "query": query, "locale": locale})
if rendered:
return rendered
return {"en": "No results found.", "ru": "Ничего не найдено."}.get(locale, "No results found.")
if response_mode == "media":
@@ -571,7 +606,17 @@ def _format_assets(
})
return media_items
# Text mode
# Text mode — try template first
# Map command names to template slot names (search/find/person/place share "search" slot)
slot_map = {"find": "search", "person": "search", "place": "search"}
slot_name = slot_map.get(cmd, cmd)
rendered = _render_cmd_template(cmd_templates or {}, slot_name, {
"assets": assets, "query": query, "command": cmd, "count": len(assets), "locale": locale,
})
if rendered:
return rendered
# Hardcoded fallback
header_map = {
"search": {"en": f'🔍 Results for "{query}":', "ru": f'🔍 Результаты для "{query}":'},
"find": {"en": f'📄 Files matching "{query}":', "ru": f'📄 Файлы по запросу "{query}":'},
@@ -53,6 +53,21 @@ class TelegramBot(SQLModel, table=True):
created_at: datetime = Field(default_factory=_utcnow)
class MatrixBot(SQLModel, table=True):
"""Matrix bot — homeserver connection for sending messages to rooms."""
__tablename__ = "matrix_bot"
id: int | None = Field(default=None, primary_key=True)
user_id: int = Field(foreign_key="user.id")
name: str
icon: str = Field(default="")
homeserver_url: str # e.g. https://matrix.org
access_token: str
display_name: str = Field(default="")
created_at: datetime = Field(default_factory=_utcnow)
class EmailBot(SQLModel, table=True):
"""Email sender — SMTP connection for sending email notifications."""
@@ -190,7 +205,7 @@ class NotificationTarget(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
user_id: int = Field(foreign_key="user.id")
type: str # "telegram", "webhook", or "email"
type: str # "telegram", "webhook", "email", "discord", "slack", "ntfy", "matrix"
name: str
icon: str = Field(default="")
config: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
@@ -23,6 +23,7 @@ from .api.targets import router as targets_router
from .api.target_receivers import router as target_receivers_router
from .api.telegram_bots import router as telegram_bots_router
from .api.email_bots import router as email_bots_router
from .api.matrix_bots import router as matrix_bots_router
from .api.users import router as users_router
from .api.status import router as status_router
from .api.template_vars import router as template_vars_router
@@ -46,6 +47,7 @@ async def lifespan(app: FastAPI):
await migrate_template_slots(engine)
await migrate_target_receivers(engine)
await _seed_default_templates()
await _seed_default_command_templates()
# Configure webhook secret from DB setting (falls back to env var)
from sqlmodel.ext.asyncio.session import AsyncSession as _AS
from .api.app_settings import get_setting as _get_setting
@@ -71,6 +73,7 @@ app.include_router(targets_router)
app.include_router(target_receivers_router)
app.include_router(telegram_bots_router)
app.include_router(email_bots_router)
app.include_router(matrix_bots_router)
app.include_router(users_router)
app.include_router(status_router)
app.include_router(app_settings_router)
@@ -155,6 +158,72 @@ async def _seed_default_templates():
await session.commit()
async def _seed_default_command_templates():
"""Seed or update default command response templates on startup."""
from sqlmodel import func, select
from sqlmodel.ext.asyncio.session import AsyncSession
from .database.engine import get_engine
from .database.models import CommandTemplateConfig, CommandTemplateSlot
from notify_bridge_core.templates.command_defaults import load_default_command_templates
engine = get_engine()
async with AsyncSession(engine) as session:
result = await session.exec(select(func.count()).select_from(CommandTemplateConfig))
count = result.one()
if count == 0:
# First startup — seed EN and RU defaults
for locale in ("en", "ru"):
slots = load_default_command_templates(locale)
if not slots:
continue
name = f"Default Commands ({locale.upper()})"
config = CommandTemplateConfig(
user_id=0,
provider_type="immich",
name=name,
description=f"Default Immich command templates ({locale.upper()})",
)
session.add(config)
await session.flush()
for slot_name, template_text in slots.items():
session.add(CommandTemplateSlot(
config_id=config.id,
slot_name=slot_name,
template=template_text,
))
else:
# Update existing system-owned command templates from files
result = await session.exec(
select(CommandTemplateConfig).where(CommandTemplateConfig.user_id == 0)
)
system_configs = result.all()
for config in system_configs:
locale = "ru" if "(RU)" in config.name else "en"
slots = load_default_command_templates(locale)
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,
)
)
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,
template=template_text,
))
await session.commit()
def run():
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8420)
@@ -17,10 +17,20 @@ _TEST_MESSAGES: dict[str, dict[str, str]] = {
"en": {
"telegram": "\u2705 Test message from <b>Notify Bridge</b>",
"webhook": "Test notification from Notify Bridge",
"email": "Test email from Notify Bridge",
"discord": "Test message from **Notify Bridge**",
"slack": "Test message from *Notify Bridge*",
"ntfy": "Test notification from Notify Bridge",
"matrix": "Test message from Notify Bridge",
},
"ru": {
"telegram": "\u2705 Тестовое сообщение от <b>Notify Bridge</b>",
"webhook": "Тестовое уведомление от Notify Bridge",
"email": "Тестовое письмо от Notify Bridge",
"discord": "Тестовое сообщение от **Notify Bridge**",
"slack": "Тестовое сообщение от *Notify Bridge*",
"ntfy": "Тестовое уведомление от Notify Bridge",
"matrix": "Тестовое сообщение от Notify Bridge",
},
}
@@ -50,12 +60,17 @@ async def send_to_target(target: NotificationTarget, message: str) -> dict:
"""
try:
receivers = await _load_receivers(target.id)
if target.type == "telegram":
return await _send_telegram_broadcast(target, message, receivers)
elif target.type == "webhook":
return await _send_webhook_broadcast(target, message, receivers)
elif target.type == "email":
return await _send_email_broadcast(target, message, receivers)
send_fn = {
"telegram": _send_telegram_broadcast,
"webhook": _send_webhook_broadcast,
"email": _send_email_broadcast,
"discord": _send_webhook_like_broadcast,
"slack": _send_webhook_like_broadcast,
"ntfy": _send_ntfy_broadcast,
"matrix": _send_matrix_broadcast,
}.get(target.type)
if send_fn:
return await send_fn(target, message, receivers)
return {"success": False, "error": f"Unknown target type: {target.type}"}
except Exception as e:
_LOGGER.error("Send failed: %s", e)
@@ -188,6 +203,107 @@ async def _send_email_broadcast(target: NotificationTarget, message: str, receiv
return {"success": False, "error": "No valid email receivers"}
async def _send_webhook_like_broadcast(target: NotificationTarget, message: str, receivers: list[dict]) -> dict:
"""Broadcast for Discord and Slack — both use webhook URLs as receivers."""
if not receivers:
webhook_url = target.config.get("webhook_url")
if webhook_url:
receivers = [{"webhook_url": webhook_url}]
else:
return {"success": False, "error": "No receivers configured"}
results: list[dict] = []
async with aiohttp.ClientSession() as session:
if target.type == "discord":
from notify_bridge_core.notifications.discord.client import DiscordClient
client = DiscordClient(session)
for recv in receivers:
url = recv.get("webhook_url")
if url:
results.append(await client.send(url, message, username=target.config.get("username")))
elif target.type == "slack":
from notify_bridge_core.notifications.slack.client import SlackClient
client = SlackClient(session)
for recv in receivers:
url = recv.get("webhook_url")
if url:
results.append(await client.send(url, message, username=target.config.get("username")))
return _aggregate(results)
async def _send_ntfy_broadcast(target: NotificationTarget, message: str, receivers: list[dict]) -> dict:
"""Broadcast to ntfy topics."""
server_url = target.config.get("server_url", "https://ntfy.sh")
auth_token = target.config.get("auth_token")
if not receivers:
topic = target.config.get("topic")
if topic:
receivers = [{"topic": topic}]
else:
return {"success": False, "error": "No receivers configured"}
from notify_bridge_core.notifications.ntfy.client import NtfyClient
results: list[dict] = []
async with aiohttp.ClientSession() as session:
client = NtfyClient(session)
for recv in receivers:
topic = recv.get("topic")
if topic:
results.append(await client.send(
server_url, topic, message,
title="Notify Bridge",
priority=recv.get("priority", 3),
auth_token=auth_token,
))
return _aggregate(results)
async def _send_matrix_broadcast(target: NotificationTarget, message: str, receivers: list[dict]) -> dict:
"""Broadcast to Matrix rooms."""
from notify_bridge_core.notifications.matrix.client import MatrixClient
from ..database.models import MatrixBot
matrix_bot_id = target.config.get("matrix_bot_id")
if not matrix_bot_id:
return {"success": False, "error": "No Matrix bot configured for this target"}
engine = get_engine()
async with AsyncSession(engine) as session:
bot = await session.get(MatrixBot, matrix_bot_id)
if not bot:
return {"success": False, "error": "Matrix bot not found"}
homeserver = bot.homeserver_url
access_token = bot.access_token
if not receivers:
return {"success": False, "error": "No receivers configured"}
results: list[dict] = []
async with aiohttp.ClientSession() as http:
client = MatrixClient(http, homeserver, access_token)
for recv in receivers:
room_id = recv.get("room_id")
if room_id:
results.append(await client.send_message(room_id, message, html_message=message))
return _aggregate(results)
def _aggregate(results: list[dict]) -> dict:
"""Aggregate broadcast results."""
successes = sum(1 for r in results if r.get("success"))
if successes == len(results) and results:
return {"success": True, "receivers": len(results)}
elif successes > 0:
return {"success": True, "receivers": len(results), "partial_failures": len(results) - successes}
elif results:
return results[0]
return {"success": False, "error": "No valid receivers"}
# --- Public API used by routes ---
@@ -19,6 +19,7 @@ from ..database.engine import get_engine
from ..database.models import (
EmailBot,
EventLog,
MatrixBot,
NotificationTarget,
NotificationTracker,
NotificationTrackerState,
@@ -162,7 +163,7 @@ async def check_tracker(tracker_id: int) -> dict[str, Any]:
template_slots[event_key] = tmpl_text
target_config = dict(target.config)
# Inject SMTP config for email targets from EmailBot
# Inject bot credentials for bot-backed target types
if target.type == "email":
email_bot_id = target.config.get("email_bot_id")
if email_bot_id:
@@ -177,6 +178,13 @@ async def check_tracker(tracker_id: int) -> dict[str, Any]:
"from_name": email_bot.name,
"use_tls": email_bot.smtp_use_tls,
}
elif target.type == "matrix":
matrix_bot_id = target.config.get("matrix_bot_id")
if matrix_bot_id:
matrix_bot = await session.get(MatrixBot, matrix_bot_id)
if matrix_bot:
target_config["homeserver_url"] = matrix_bot.homeserver_url
target_config["access_token"] = matrix_bot.access_token
link_data.append({
"target_type": target.type,