83 lines
2.4 KiB
Python
83 lines
2.4 KiB
Python
from typing import Optional, List
|
|
from fastapi import APIRouter, Depends, Query, HTTPException
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from backend.database import get_db
|
|
from backend.schemas import NotifyRequest, NotifyResponse
|
|
from backend.notify_service import NotifyService
|
|
|
|
router = APIRouter(prefix="/api", tags=["notify"])
|
|
|
|
@router.post("/notify", response_model=NotifyResponse)
|
|
async def send_notification(
|
|
request: NotifyRequest,
|
|
db: AsyncSession = Depends(get_db)
|
|
):
|
|
"""发送通知到指定通道或按标签发送"""
|
|
if not request.channels and not request.tags:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="Either 'channels' or 'tags' must be provided"
|
|
)
|
|
|
|
service = NotifyService()
|
|
results = await service.send_to_channels(
|
|
db,
|
|
request.channels,
|
|
request.tags,
|
|
request.title,
|
|
request.body,
|
|
request.priority
|
|
)
|
|
|
|
total = len(results)
|
|
sent = sum(1 for r in results if r["status"] == "sent")
|
|
failed = sum(1 for r in results if r["status"] == "failed")
|
|
|
|
return {
|
|
"success": sent == total,
|
|
"results": results,
|
|
"total": total,
|
|
"sent": sent,
|
|
"failed": failed
|
|
}
|
|
|
|
@router.get("/notify")
|
|
async def send_notification_get(
|
|
channels: Optional[str] = Query(None, description="通道名称,多个用逗号分隔"),
|
|
tags: Optional[str] = Query(None, description="标签,多个用逗号分隔"),
|
|
title: Optional[str] = Query(None),
|
|
body: str = Query(..., description="消息内容"),
|
|
priority: str = Query("normal"),
|
|
db: AsyncSession = Depends(get_db)
|
|
):
|
|
"""通过 GET 请求发送通知(方便脚本调用)"""
|
|
channel_list = channels.split(",") if channels else None
|
|
tag_list = tags.split(",") if tags else None
|
|
|
|
if not channel_list and not tag_list:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="Either 'channels' or 'tags' must be provided"
|
|
)
|
|
|
|
service = NotifyService()
|
|
results = await service.send_to_channels(
|
|
db,
|
|
channel_list,
|
|
tag_list,
|
|
title,
|
|
body,
|
|
priority
|
|
)
|
|
|
|
total = len(results)
|
|
sent = sum(1 for r in results if r["status"] == "sent")
|
|
|
|
return {
|
|
"success": sent == total,
|
|
"results": results,
|
|
"total": total,
|
|
"sent": sent,
|
|
"failed": total - sent
|
|
}
|