feat: Actions system — scheduled mutations on external services
Full-stack implementation of provider-scoped Actions with extensible executor architecture. First action type: Immich auto_organize (sort assets into albums by person, CLIP search, date range, favorites). Core: - ActionTypeDefinition registry + ActionExecutor ABC with execute/validate/dry-run - ImmichActionExecutor with multi-album support and client-side filtering - ImmichClient write methods: add/remove assets, create album, paginated search Server: - Action, ActionRule, ActionExecution DB models - Full CRUD API + manual execute + dry-run + execution history endpoints - APScheduler integration (interval + cron) for automated execution - Action type discovery API + provider people endpoint Frontend: - Actions page with CRUD, execute/dry-run buttons, inline rule editor - RuleEditor: person/album MultiEntitySelect pickers, criteria config - ExecutionHistory: expandable per-rule result details - MultiEntitySelect reusable component (searchable multi-pick palette) - Notification tracker album picker migrated to MultiEntitySelect - Fixed MdiIcon race condition (icons missing after cache-clearing reload)
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
"""Action rule 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 Action, ActionRule, User
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/actions", tags=["action-rules"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Request schemas
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ActionRuleCreate(BaseModel):
|
||||
name: str = ""
|
||||
rule_config: dict = {}
|
||||
enabled: bool = True
|
||||
order: int = 0
|
||||
|
||||
|
||||
class ActionRuleUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
rule_config: dict | None = None
|
||||
enabled: bool | None = None
|
||||
order: int | None = None
|
||||
|
||||
|
||||
class ReorderBody(BaseModel):
|
||||
rule_ids: list[int]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _rule_response(rule: ActionRule) -> dict:
|
||||
return {
|
||||
"id": rule.id,
|
||||
"action_id": rule.action_id,
|
||||
"name": rule.name,
|
||||
"rule_config": rule.rule_config,
|
||||
"enabled": rule.enabled,
|
||||
"order": rule.order,
|
||||
"created_at": rule.created_at.isoformat() if rule.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
async def _get_user_action(
|
||||
session: AsyncSession, action_id: int, user: User
|
||||
) -> Action:
|
||||
action = await session.get(Action, action_id)
|
||||
if not action or action.user_id != user.id:
|
||||
raise HTTPException(status_code=404, detail="Action not found")
|
||||
return action
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Routes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/{action_id}/rules")
|
||||
async def list_rules(
|
||||
action_id: int,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
await _get_user_action(session, action_id, user)
|
||||
result = await session.exec(
|
||||
select(ActionRule)
|
||||
.where(ActionRule.action_id == action_id)
|
||||
.order_by(ActionRule.order)
|
||||
)
|
||||
return [_rule_response(r) for r in result.all()]
|
||||
|
||||
|
||||
@router.post("/{action_id}/rules", status_code=status.HTTP_201_CREATED)
|
||||
async def create_rule(
|
||||
action_id: int,
|
||||
body: ActionRuleCreate,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
await _get_user_action(session, action_id, user)
|
||||
rule = ActionRule(action_id=action_id, **body.model_dump())
|
||||
session.add(rule)
|
||||
await session.commit()
|
||||
await session.refresh(rule)
|
||||
return _rule_response(rule)
|
||||
|
||||
|
||||
@router.put("/{action_id}/rules/reorder")
|
||||
async def reorder_rules(
|
||||
action_id: int,
|
||||
body: ReorderBody,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
await _get_user_action(session, action_id, user)
|
||||
result = await session.exec(
|
||||
select(ActionRule).where(ActionRule.action_id == action_id)
|
||||
)
|
||||
rules_by_id = {r.id: r for r in result.all()}
|
||||
|
||||
for idx, rule_id in enumerate(body.rule_ids):
|
||||
rule = rules_by_id.get(rule_id)
|
||||
if rule:
|
||||
rule.order = idx
|
||||
session.add(rule)
|
||||
|
||||
await session.commit()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.put("/{action_id}/rules/{rule_id}")
|
||||
async def update_rule(
|
||||
action_id: int,
|
||||
rule_id: int,
|
||||
body: ActionRuleUpdate,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
await _get_user_action(session, action_id, user)
|
||||
rule = await session.get(ActionRule, rule_id)
|
||||
if not rule or rule.action_id != action_id:
|
||||
raise HTTPException(status_code=404, detail="Rule not found")
|
||||
|
||||
updates = body.model_dump(exclude_unset=True)
|
||||
for key, value in updates.items():
|
||||
setattr(rule, key, value)
|
||||
session.add(rule)
|
||||
await session.commit()
|
||||
await session.refresh(rule)
|
||||
return _rule_response(rule)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{action_id}/rules/{rule_id}", status_code=status.HTTP_204_NO_CONTENT
|
||||
)
|
||||
async def delete_rule(
|
||||
action_id: int,
|
||||
rule_id: int,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
await _get_user_action(session, action_id, user)
|
||||
rule = await session.get(ActionRule, rule_id)
|
||||
if not rule or rule.action_id != action_id:
|
||||
raise HTTPException(status_code=404, detail="Rule not found")
|
||||
await session.delete(rule)
|
||||
await session.commit()
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Action type discovery API routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from notify_bridge_core.providers.actions import (
|
||||
get_action_type,
|
||||
get_action_types,
|
||||
get_all_action_types,
|
||||
)
|
||||
from notify_bridge_core.providers.capabilities import get_all_capabilities
|
||||
|
||||
from ..auth.dependencies import get_current_user
|
||||
from ..database.models import User
|
||||
|
||||
router = APIRouter(prefix="/api/action-types", tags=["action-types"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_all_action_types(
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""All action types grouped by provider."""
|
||||
all_types = get_all_action_types()
|
||||
result: dict[str, list[dict]] = {}
|
||||
for provider_type, defns in all_types.items():
|
||||
result[provider_type] = [
|
||||
{
|
||||
"key": d.key,
|
||||
"provider_type": d.provider_type,
|
||||
"display_name": d.display_name,
|
||||
"description": d.description,
|
||||
}
|
||||
for d in defns
|
||||
]
|
||||
# Also include providers with no action types (from capabilities)
|
||||
all_caps = get_all_capabilities()
|
||||
for ptype in all_caps:
|
||||
if ptype not in result:
|
||||
result[ptype] = []
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/{provider_type}")
|
||||
async def list_provider_action_types(
|
||||
provider_type: str,
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Action types for a specific provider."""
|
||||
defns = get_action_types(provider_type)
|
||||
return [
|
||||
{
|
||||
"key": d.key,
|
||||
"provider_type": d.provider_type,
|
||||
"display_name": d.display_name,
|
||||
"description": d.description,
|
||||
}
|
||||
for d in defns
|
||||
]
|
||||
|
||||
|
||||
@router.get("/{provider_type}/{key}/schema")
|
||||
async def get_action_type_schema(
|
||||
provider_type: str,
|
||||
key: str,
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Get rule and config JSON schemas for an action type."""
|
||||
defn = get_action_type(provider_type, key)
|
||||
if not defn:
|
||||
raise HTTPException(status_code=404, detail="Action type not found")
|
||||
return {
|
||||
"key": defn.key,
|
||||
"provider_type": defn.provider_type,
|
||||
"display_name": defn.display_name,
|
||||
"description": defn.description,
|
||||
"rule_schema": defn.rule_schema,
|
||||
"config_schema": defn.config_schema,
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
"""Action management API routes — CRUD, execute, dry-run, executions."""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, 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 (
|
||||
Action,
|
||||
ActionExecution,
|
||||
ActionRule,
|
||||
ServiceProvider,
|
||||
User,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/actions", tags=["actions"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Request / response schemas
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ActionCreate(BaseModel):
|
||||
provider_id: int
|
||||
name: str
|
||||
icon: str = ""
|
||||
action_type: str
|
||||
config: dict = {}
|
||||
schedule_type: str = "interval"
|
||||
schedule_interval: int = 3600
|
||||
schedule_cron: str = ""
|
||||
enabled: bool = False
|
||||
|
||||
|
||||
class ActionUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
icon: str | None = None
|
||||
config: dict | None = None
|
||||
schedule_type: str | None = None
|
||||
schedule_interval: int | None = None
|
||||
schedule_cron: str | None = None
|
||||
enabled: bool | None = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _action_response(session: AsyncSession, action: Action) -> dict:
|
||||
"""Build response dict with rules inlined."""
|
||||
result = await session.exec(
|
||||
select(ActionRule)
|
||||
.where(ActionRule.action_id == action.id)
|
||||
.order_by(ActionRule.order)
|
||||
)
|
||||
rules = result.all()
|
||||
return {
|
||||
"id": action.id,
|
||||
"user_id": action.user_id,
|
||||
"provider_id": action.provider_id,
|
||||
"name": action.name,
|
||||
"icon": action.icon,
|
||||
"action_type": action.action_type,
|
||||
"config": action.config,
|
||||
"schedule_type": action.schedule_type,
|
||||
"schedule_interval": action.schedule_interval,
|
||||
"schedule_cron": action.schedule_cron,
|
||||
"enabled": action.enabled,
|
||||
"last_run_at": action.last_run_at.isoformat() if action.last_run_at else None,
|
||||
"last_run_status": action.last_run_status,
|
||||
"created_at": action.created_at.isoformat() if action.created_at else None,
|
||||
"rules": [
|
||||
{
|
||||
"id": r.id,
|
||||
"action_id": r.action_id,
|
||||
"name": r.name,
|
||||
"rule_config": r.rule_config,
|
||||
"enabled": r.enabled,
|
||||
"order": r.order,
|
||||
"created_at": r.created_at.isoformat() if r.created_at else None,
|
||||
}
|
||||
for r in rules
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CRUD
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_actions(
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
result = await session.exec(
|
||||
select(Action).where(Action.user_id == user.id)
|
||||
)
|
||||
actions = result.all()
|
||||
return [await _action_response(session, a) for a in actions]
|
||||
|
||||
|
||||
@router.post("", status_code=status.HTTP_201_CREATED)
|
||||
async def create_action(
|
||||
body: ActionCreate,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
provider = await session.get(ServiceProvider, body.provider_id)
|
||||
if not provider or provider.user_id != user.id:
|
||||
raise HTTPException(status_code=404, detail="Provider not found")
|
||||
|
||||
# Validate action_type against the registry
|
||||
from notify_bridge_core.providers.actions import get_action_type
|
||||
if not get_action_type(provider.type, body.action_type):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid action type '{body.action_type}' for provider type '{provider.type}'",
|
||||
)
|
||||
|
||||
action = Action(user_id=user.id, **body.model_dump())
|
||||
session.add(action)
|
||||
await session.commit()
|
||||
await session.refresh(action)
|
||||
|
||||
if action.enabled:
|
||||
from ..services.scheduler import schedule_action
|
||||
await schedule_action(
|
||||
action.id,
|
||||
action.schedule_type,
|
||||
action.schedule_interval,
|
||||
action.schedule_cron,
|
||||
)
|
||||
|
||||
return await _action_response(session, action)
|
||||
|
||||
|
||||
@router.get("/{action_id}")
|
||||
async def get_action(
|
||||
action_id: int,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
action = await session.get(Action, action_id)
|
||||
if not action or action.user_id != user.id:
|
||||
raise HTTPException(status_code=404, detail="Action not found")
|
||||
return await _action_response(session, action)
|
||||
|
||||
|
||||
@router.put("/{action_id}")
|
||||
async def update_action(
|
||||
action_id: int,
|
||||
body: ActionUpdate,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
action = await session.get(Action, action_id)
|
||||
if not action or action.user_id != user.id:
|
||||
raise HTTPException(status_code=404, detail="Action not found")
|
||||
|
||||
updates = body.model_dump(exclude_unset=True)
|
||||
for key, value in updates.items():
|
||||
setattr(action, key, value)
|
||||
session.add(action)
|
||||
await session.commit()
|
||||
await session.refresh(action)
|
||||
|
||||
# Reschedule or unschedule based on enabled state
|
||||
from ..services.scheduler import schedule_action, unschedule_action
|
||||
if action.enabled:
|
||||
await schedule_action(
|
||||
action.id,
|
||||
action.schedule_type,
|
||||
action.schedule_interval,
|
||||
action.schedule_cron,
|
||||
)
|
||||
else:
|
||||
await unschedule_action(action.id)
|
||||
|
||||
return await _action_response(session, action)
|
||||
|
||||
|
||||
@router.delete("/{action_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_action(
|
||||
action_id: int,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
action = await session.get(Action, action_id)
|
||||
if not action or action.user_id != user.id:
|
||||
raise HTTPException(status_code=404, detail="Action not found")
|
||||
|
||||
# Unschedule
|
||||
from ..services.scheduler import unschedule_action
|
||||
await unschedule_action(action.id)
|
||||
|
||||
# Bulk delete rules and executions
|
||||
from sqlalchemy import delete
|
||||
await session.exec(delete(ActionRule).where(ActionRule.action_id == action_id))
|
||||
await session.exec(delete(ActionExecution).where(ActionExecution.action_id == action_id))
|
||||
|
||||
await session.delete(action)
|
||||
await session.commit()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Execute / Dry-run
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.post("/{action_id}/execute")
|
||||
async def execute_action(
|
||||
action_id: int,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
action = await session.get(Action, action_id)
|
||||
if not action or action.user_id != user.id:
|
||||
raise HTTPException(status_code=404, detail="Action not found")
|
||||
|
||||
from ..services.action_runner import run_action
|
||||
result = await run_action(action_id, trigger="manual")
|
||||
return result.to_dict()
|
||||
|
||||
|
||||
@router.post("/{action_id}/dry-run")
|
||||
async def dry_run_action(
|
||||
action_id: int,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
action = await session.get(Action, action_id)
|
||||
if not action or action.user_id != user.id:
|
||||
raise HTTPException(status_code=404, detail="Action not found")
|
||||
|
||||
from ..services.action_runner import dry_run_action as _dry_run
|
||||
result = await _dry_run(action_id)
|
||||
return result.to_dict()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Execution history
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/{action_id}/executions")
|
||||
async def list_executions(
|
||||
action_id: int,
|
||||
limit: int = Query(default=20, le=100),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
action = await session.get(Action, action_id)
|
||||
if not action or action.user_id != user.id:
|
||||
raise HTTPException(status_code=404, detail="Action not found")
|
||||
|
||||
result = await session.exec(
|
||||
select(ActionExecution)
|
||||
.where(ActionExecution.action_id == action_id)
|
||||
.order_by(ActionExecution.started_at.desc())
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
)
|
||||
executions = result.all()
|
||||
return [
|
||||
{
|
||||
"id": e.id,
|
||||
"action_id": e.action_id,
|
||||
"started_at": e.started_at.isoformat() if e.started_at else None,
|
||||
"finished_at": e.finished_at.isoformat() if e.finished_at else None,
|
||||
"status": e.status,
|
||||
"rules_processed": e.rules_processed,
|
||||
"rules_succeeded": e.rules_succeeded,
|
||||
"rules_failed": e.rules_failed,
|
||||
"total_items_affected": e.total_items_affected,
|
||||
"summary": e.summary,
|
||||
"error": e.error,
|
||||
"trigger": e.trigger,
|
||||
}
|
||||
for e in executions
|
||||
]
|
||||
@@ -193,6 +193,7 @@ async def list_provider_capabilities():
|
||||
"commands": caps.commands,
|
||||
"supported_filters": caps.supported_filters,
|
||||
"webhook_based": caps.webhook_based,
|
||||
"action_types": caps.action_types,
|
||||
}
|
||||
return result
|
||||
|
||||
@@ -351,6 +352,29 @@ async def test_provider(
|
||||
return {"ok": False, "message": f"Unknown provider type: {provider.type}"}
|
||||
|
||||
|
||||
@router.get("/{provider_id}/people")
|
||||
async def list_people(
|
||||
provider_id: int,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Fetch people from a service provider (Immich only)."""
|
||||
provider = await _get_user_provider(session, provider_id, user.id)
|
||||
|
||||
if provider.type == "immich":
|
||||
from notify_bridge_core.providers.immich.client import ImmichClient
|
||||
async with aiohttp.ClientSession() as http_session:
|
||||
client = ImmichClient(
|
||||
http_session,
|
||||
provider.config.get("url", ""),
|
||||
provider.config.get("api_key", ""),
|
||||
)
|
||||
people_dict = await client.get_people()
|
||||
return [{"id": pid, "name": name} for pid, name in people_dict.items()]
|
||||
|
||||
return []
|
||||
|
||||
|
||||
@router.get("/{provider_id}/collections")
|
||||
async def list_collections(
|
||||
provider_id: int,
|
||||
|
||||
@@ -470,6 +470,60 @@ class EventLog(SQLModel, table=True):
|
||||
created_at: datetime = Field(default_factory=_utcnow)
|
||||
|
||||
|
||||
class Action(SQLModel, table=True):
|
||||
"""A scheduled action that mutates an external service."""
|
||||
|
||||
__tablename__ = "action"
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
user_id: int = Field(foreign_key="user.id")
|
||||
provider_id: int = Field(foreign_key="service_provider.id")
|
||||
name: str
|
||||
icon: str = Field(default="")
|
||||
action_type: str # e.g. "auto_organize"
|
||||
config: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
schedule_type: str = Field(default="interval") # "interval" or "cron"
|
||||
schedule_interval: int = Field(default=3600) # seconds
|
||||
schedule_cron: str = Field(default="")
|
||||
enabled: bool = Field(default=False) # default disabled for safety
|
||||
last_run_at: datetime | None = Field(default=None)
|
||||
last_run_status: str = Field(default="") # "success", "partial", "failed", ""
|
||||
created_at: datetime = Field(default_factory=_utcnow)
|
||||
|
||||
|
||||
class ActionRule(SQLModel, table=True):
|
||||
"""One rule within an Action. Executed in order."""
|
||||
|
||||
__tablename__ = "action_rule"
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
action_id: int = Field(foreign_key="action.id", index=True)
|
||||
name: str = Field(default="")
|
||||
rule_config: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
enabled: bool = Field(default=True)
|
||||
order: int = Field(default=0)
|
||||
created_at: datetime = Field(default_factory=_utcnow)
|
||||
|
||||
|
||||
class ActionExecution(SQLModel, table=True):
|
||||
"""Log of an action execution (scheduled, manual, or dry-run)."""
|
||||
|
||||
__tablename__ = "action_execution"
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
action_id: int = Field(foreign_key="action.id", index=True)
|
||||
started_at: datetime = Field(default_factory=_utcnow)
|
||||
finished_at: datetime | None = Field(default=None)
|
||||
status: str = Field(default="running") # "running", "success", "partial", "failed"
|
||||
rules_processed: int = Field(default=0)
|
||||
rules_succeeded: int = Field(default=0)
|
||||
rules_failed: int = Field(default=0)
|
||||
total_items_affected: int = Field(default=0)
|
||||
summary: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
error: str = Field(default="")
|
||||
trigger: str = Field(default="scheduled") # "scheduled", "manual", "dry_run"
|
||||
|
||||
|
||||
class AppSetting(SQLModel, table=True):
|
||||
"""Key-value app-level settings (admin-configurable)."""
|
||||
|
||||
|
||||
@@ -35,6 +35,9 @@ from .api.app_settings import router as app_settings_router
|
||||
from .api.command_configs import router as command_configs_router
|
||||
from .api.command_trackers import router as command_trackers_router
|
||||
from .api.command_template_configs import router as command_template_configs_router
|
||||
from .api.actions import router as actions_router
|
||||
from .api.action_rules import router as action_rules_router
|
||||
from .api.action_types import router as action_types_router
|
||||
from .commands.webhook import router as webhook_router, set_webhook_secret
|
||||
from .api.webhooks import router as webhooks_router
|
||||
|
||||
@@ -106,6 +109,9 @@ app.include_router(matrix_bots_router)
|
||||
app.include_router(users_router)
|
||||
app.include_router(status_router)
|
||||
app.include_router(app_settings_router)
|
||||
app.include_router(action_types_router)
|
||||
app.include_router(action_rules_router)
|
||||
app.include_router(actions_router)
|
||||
app.include_router(command_configs_router)
|
||||
app.include_router(command_trackers_router)
|
||||
app.include_router(command_template_configs_router)
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Action runner — orchestrates loading, executing, and logging actions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from notify_bridge_core.providers.action_executor import ActionResult
|
||||
|
||||
from ..database.engine import get_engine
|
||||
from ..database.models import (
|
||||
Action,
|
||||
ActionExecution,
|
||||
ActionRule,
|
||||
ServiceProvider,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def run_action(
|
||||
action_id: int, *, trigger: str = "scheduled"
|
||||
) -> ActionResult:
|
||||
"""Load an action from DB, execute it, and save the execution log."""
|
||||
engine = get_engine()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 1. Load all DB data eagerly (before aiohttp context)
|
||||
# ------------------------------------------------------------------
|
||||
async with AsyncSession(engine) as session:
|
||||
action = await session.get(Action, action_id)
|
||||
if not action:
|
||||
return ActionResult(success=False, error="Action not found")
|
||||
if not action.enabled and trigger == "scheduled":
|
||||
return ActionResult(success=False, error="Action is disabled")
|
||||
|
||||
provider = await session.get(ServiceProvider, action.provider_id)
|
||||
if not provider:
|
||||
return ActionResult(success=False, error="Provider not found")
|
||||
|
||||
result = await session.exec(
|
||||
select(ActionRule)
|
||||
.where(ActionRule.action_id == action_id)
|
||||
.where(ActionRule.enabled == True) # noqa: E712
|
||||
.order_by(ActionRule.order)
|
||||
)
|
||||
rules = result.all()
|
||||
|
||||
if not rules:
|
||||
return ActionResult(success=True, rules_processed=0)
|
||||
|
||||
# Snapshot data
|
||||
provider_type = provider.type
|
||||
provider_config = dict(provider.config)
|
||||
provider_name = provider.name
|
||||
action_type = action.action_type
|
||||
action_config = dict(action.config) if action.config else {}
|
||||
rule_configs = [
|
||||
{**dict(r.rule_config), "name": r.name} for r in rules
|
||||
]
|
||||
|
||||
# Create execution record
|
||||
execution = ActionExecution(
|
||||
action_id=action_id,
|
||||
trigger=trigger,
|
||||
status="running",
|
||||
)
|
||||
session.add(execution)
|
||||
await session.commit()
|
||||
await session.refresh(execution)
|
||||
execution_id = execution.id
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 2. Execute via provider-specific executor
|
||||
# ------------------------------------------------------------------
|
||||
is_dry_run = trigger == "dry_run"
|
||||
action_result: ActionResult
|
||||
|
||||
try:
|
||||
action_result = await _execute_with_provider(
|
||||
provider_type=provider_type,
|
||||
provider_config=provider_config,
|
||||
provider_name=provider_name,
|
||||
action_type=action_type,
|
||||
action_config=action_config,
|
||||
rule_configs=rule_configs,
|
||||
dry_run=is_dry_run,
|
||||
)
|
||||
except Exception as err:
|
||||
_LOGGER.error("Action %d execution error: %s", action_id, err)
|
||||
action_result = ActionResult(success=False, error=str(err))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 3. Save execution results
|
||||
# ------------------------------------------------------------------
|
||||
async with AsyncSession(engine) as session:
|
||||
execution = await session.get(ActionExecution, execution_id)
|
||||
if execution:
|
||||
execution.finished_at = datetime.now(timezone.utc)
|
||||
if action_result.error is not None and action_result.rules_succeeded == 0:
|
||||
execution.status = "failed"
|
||||
elif action_result.rules_failed > 0:
|
||||
execution.status = "partial"
|
||||
else:
|
||||
execution.status = "success"
|
||||
execution.rules_processed = action_result.rules_processed
|
||||
execution.rules_succeeded = action_result.rules_succeeded
|
||||
execution.rules_failed = action_result.rules_failed
|
||||
execution.total_items_affected = action_result.total_items_affected
|
||||
execution.summary = action_result.to_dict()
|
||||
execution.error = action_result.error or ""
|
||||
session.add(execution)
|
||||
|
||||
# Update action last_run metadata (skip for dry runs)
|
||||
if not is_dry_run:
|
||||
action = await session.get(Action, action_id)
|
||||
if action:
|
||||
action.last_run_at = datetime.now(timezone.utc)
|
||||
action.last_run_status = execution.status if execution else ""
|
||||
session.add(action)
|
||||
|
||||
await session.commit()
|
||||
|
||||
_LOGGER.info(
|
||||
"Action %d (%s) completed: %d/%d rules succeeded, %d items affected",
|
||||
action_id,
|
||||
trigger,
|
||||
action_result.rules_succeeded,
|
||||
action_result.rules_processed,
|
||||
action_result.total_items_affected,
|
||||
)
|
||||
return action_result
|
||||
|
||||
|
||||
async def dry_run_action(action_id: int) -> ActionResult:
|
||||
"""Execute a dry-run of an action (no mutations)."""
|
||||
return await run_action(action_id, trigger="dry_run")
|
||||
|
||||
|
||||
async def _execute_with_provider(
|
||||
*,
|
||||
provider_type: str,
|
||||
provider_config: dict[str, Any],
|
||||
provider_name: str,
|
||||
action_type: str,
|
||||
action_config: dict[str, Any],
|
||||
rule_configs: list[dict[str, Any]],
|
||||
dry_run: bool,
|
||||
) -> ActionResult:
|
||||
"""Instantiate the appropriate executor and run."""
|
||||
if provider_type == "immich":
|
||||
from notify_bridge_core.providers.immich.action_executor import (
|
||||
ImmichActionExecutor,
|
||||
)
|
||||
from notify_bridge_core.providers.immich.client import ImmichClient
|
||||
|
||||
async with aiohttp.ClientSession() as http_session:
|
||||
client = ImmichClient(
|
||||
http_session,
|
||||
provider_config.get("url", ""),
|
||||
provider_config.get("api_key", ""),
|
||||
)
|
||||
external_domain = provider_config.get("external_domain")
|
||||
if external_domain:
|
||||
client.external_domain = external_domain
|
||||
|
||||
# Verify connectivity
|
||||
if not await client.ping():
|
||||
return ActionResult(
|
||||
success=False,
|
||||
error=f"Cannot connect to Immich server ({provider_name})",
|
||||
)
|
||||
|
||||
executor = ImmichActionExecutor(client)
|
||||
if dry_run:
|
||||
return await executor.dry_run(action_type, rule_configs, action_config)
|
||||
return await executor.execute(action_type, rule_configs, action_config)
|
||||
|
||||
return ActionResult(
|
||||
success=False,
|
||||
error=f"No action executor for provider type: {provider_type}",
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
"""APScheduler-based polling scheduler for trackers."""
|
||||
"""APScheduler-based polling scheduler for trackers and actions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -25,6 +25,7 @@ async def start_scheduler() -> None:
|
||||
_LOGGER.info("Scheduler started")
|
||||
|
||||
await _load_tracker_jobs()
|
||||
await _load_action_jobs()
|
||||
|
||||
# Start Telegram bot polling for bots with active command listeners
|
||||
from .telegram_poller import start_command_listener_polling
|
||||
@@ -156,3 +157,123 @@ async def _poll_tracker(tracker_id: int) -> None:
|
||||
await check_tracker(tracker_id)
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error polling tracker %d: %s", tracker_id, e)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Action scheduling
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _load_action_jobs() -> None:
|
||||
"""Load enabled actions and schedule execution jobs."""
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
from ..database.engine import get_engine
|
||||
from ..database.models import Action
|
||||
|
||||
engine = get_engine()
|
||||
scheduler = get_scheduler()
|
||||
|
||||
async with AsyncSession(engine) as session:
|
||||
result = await session.exec(
|
||||
select(Action).where(Action.enabled == True) # noqa: E712
|
||||
)
|
||||
actions = result.all()
|
||||
|
||||
for action in actions:
|
||||
job_id = f"action_{action.id}"
|
||||
if scheduler.get_job(job_id):
|
||||
continue
|
||||
|
||||
if action.schedule_type == "cron" and action.schedule_cron:
|
||||
try:
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
trigger = CronTrigger.from_crontab(action.schedule_cron)
|
||||
scheduler.add_job(
|
||||
_run_action,
|
||||
trigger,
|
||||
id=job_id,
|
||||
args=[action.id],
|
||||
replace_existing=True,
|
||||
)
|
||||
_LOGGER.info(
|
||||
"Scheduled action %d (%s) with cron: %s",
|
||||
action.id, action.name, action.schedule_cron,
|
||||
)
|
||||
continue
|
||||
except Exception as e:
|
||||
_LOGGER.error(
|
||||
"Invalid cron for action %d (%s): %s — falling back to interval",
|
||||
action.id, action.name, e,
|
||||
)
|
||||
|
||||
scheduler.add_job(
|
||||
_run_action,
|
||||
"interval",
|
||||
seconds=action.schedule_interval,
|
||||
id=job_id,
|
||||
args=[action.id],
|
||||
replace_existing=True,
|
||||
)
|
||||
_LOGGER.info(
|
||||
"Scheduled action %d (%s) every %ds",
|
||||
action.id, action.name, action.schedule_interval,
|
||||
)
|
||||
|
||||
|
||||
async def schedule_action(
|
||||
action_id: int,
|
||||
schedule_type: str = "interval",
|
||||
interval: int = 3600,
|
||||
cron_expression: str = "",
|
||||
) -> None:
|
||||
"""Add or update a scheduler job for an action."""
|
||||
scheduler = get_scheduler()
|
||||
job_id = f"action_{action_id}"
|
||||
|
||||
if scheduler.get_job(job_id):
|
||||
scheduler.remove_job(job_id)
|
||||
|
||||
if schedule_type == "cron" and cron_expression:
|
||||
try:
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
trigger = CronTrigger.from_crontab(cron_expression)
|
||||
scheduler.add_job(
|
||||
_run_action,
|
||||
trigger,
|
||||
id=job_id,
|
||||
args=[action_id],
|
||||
replace_existing=True,
|
||||
)
|
||||
_LOGGER.info("Scheduled action %d with cron: %s", action_id, cron_expression)
|
||||
return
|
||||
except Exception as e:
|
||||
_LOGGER.error("Invalid cron for action %d: %s — using interval", action_id, e)
|
||||
|
||||
scheduler.add_job(
|
||||
_run_action,
|
||||
"interval",
|
||||
seconds=interval,
|
||||
id=job_id,
|
||||
args=[action_id],
|
||||
replace_existing=True,
|
||||
)
|
||||
_LOGGER.info("Scheduled action %d every %ds", action_id, interval)
|
||||
|
||||
|
||||
async def unschedule_action(action_id: int) -> None:
|
||||
"""Remove a scheduler job for an action."""
|
||||
scheduler = get_scheduler()
|
||||
job_id = f"action_{action_id}"
|
||||
if scheduler.get_job(job_id):
|
||||
scheduler.remove_job(job_id)
|
||||
_LOGGER.info("Unscheduled action %d", action_id)
|
||||
|
||||
|
||||
async def _run_action(action_id: int) -> None:
|
||||
"""Run an action (called by APScheduler)."""
|
||||
from .action_runner import run_action
|
||||
try:
|
||||
await run_action(action_id, trigger="scheduled")
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error running action %d: %s", action_id, e)
|
||||
|
||||
Reference in New Issue
Block a user