280 lines
11 KiB
Python
280 lines
11 KiB
Python
"""
|
||
远程控制路由:云端下发开始/结束任务,客户端轮询执行并回调。
|
||
|
||
- 状态快照 rpa_status:心跳携带全量状态上报,每用户一行(单设备)
|
||
- 任务 rpa_task:pending → running → done/failed,pending 超时 → expired
|
||
(start_apply / stop_apply 可由控制端手动下发;start_activate / stop_activate
|
||
仅由定时调度器下发)
|
||
- 去重(服务端权威拦截):同类型任务未达终态时拒绝重复下发
|
||
- 定时排程 rpa_schedule:每日到点由 scheduler 自动下发对应任务
|
||
"""
|
||
import json
|
||
import re
|
||
from datetime import datetime, timedelta
|
||
|
||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||
from sqlalchemy.orm import Session
|
||
|
||
from ..auth import get_current_user
|
||
from ..database import get_db
|
||
from ..models import User, RpaStatus, RpaTask, RpaSchedule
|
||
from ..online import is_online
|
||
from ..scheduler import KIND_TASK_TYPES, PENDING_EXPIRE_MINUTES
|
||
from ..schemas import RpaTaskIn, RpaTaskFinishIn, RpaScheduleIn, Message
|
||
|
||
router = APIRouter(prefix="/api/rpa", tags=["远程控制"])
|
||
|
||
# 任务终态:达到终态后同类型任务才允许再次下发
|
||
TERMINAL_STATUS = ("done", "failed", "expired")
|
||
# 定时排程时间格式:HH:MM(零填充 24 小时制)
|
||
_TIME_RE = re.compile(r"^([01]\d|2[0-3]):[0-5]\d$")
|
||
|
||
|
||
def _task_dict(t: RpaTask) -> dict:
|
||
return {
|
||
"id": t.id,
|
||
"task_type": t.task_type,
|
||
"params": json.loads(t.params) if t.params else None,
|
||
"status": t.status,
|
||
"result": t.result,
|
||
"created_at": (t.created_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
|
||
"updated_at": (t.updated_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
|
||
}
|
||
|
||
|
||
@router.get("/status", response_model=dict)
|
||
def get_rpa_status(
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""RPA 状态快照(控制端展示):在线 + Boss登录 + 浏览器 + 投递状态"""
|
||
st = db.query(RpaStatus).filter(RpaStatus.user_id == current_user.id).first()
|
||
return {
|
||
"online": is_online(current_user),
|
||
"boss_login": st.boss_login if st else "unknown",
|
||
"browser": st.browser if st else "unknown",
|
||
"apply_status": st.apply_status if st else "idle",
|
||
"current": st.current if st else None,
|
||
"applied": st.applied if st else 0,
|
||
"skipped": st.skipped if st else 0,
|
||
"updated_at": (st.updated_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S") if st else None,
|
||
}
|
||
|
||
|
||
@router.post("/tasks", response_model=dict)
|
||
def create_task(
|
||
req: RpaTaskIn,
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""控制端下发任务。服务端权威去重:同类型非终态任务存在时拒绝"""
|
||
if req.task_type not in ("start_apply", "stop_apply"):
|
||
raise HTTPException(status_code=422, detail="未知任务类型")
|
||
|
||
if not is_online(current_user):
|
||
raise HTTPException(status_code=409, detail="RPA 客户端离线,无法下发任务")
|
||
|
||
# 去重拦截:同类型任务未达终态,禁止重复下发
|
||
dup = db.query(RpaTask).filter(
|
||
RpaTask.user_id == current_user.id,
|
||
RpaTask.task_type == req.task_type,
|
||
RpaTask.status.in_(("pending", "running")),
|
||
).first()
|
||
if dup:
|
||
raise HTTPException(
|
||
status_code=409,
|
||
detail=f"已有同类型任务未结束(#{dup.id} 状态={dup.status}),请勿重复下发")
|
||
|
||
# 基于状态快照的业务预检,避免下发必然失败的任务
|
||
st = db.query(RpaStatus).filter(RpaStatus.user_id == current_user.id).first()
|
||
if req.task_type == "start_apply" and st and st.apply_status == "running":
|
||
raise HTTPException(status_code=409, detail="投递任务已在运行中")
|
||
if req.task_type == "stop_apply" and st and st.apply_status != "running":
|
||
raise HTTPException(status_code=409, detail="当前没有运行中的投递任务")
|
||
|
||
if req.task_type == "start_apply":
|
||
params = req.params or {}
|
||
if not params.get("keywords") or not params.get("city"):
|
||
raise HTTPException(status_code=422, detail="开始投递必须提供 keywords 与 city")
|
||
|
||
task = RpaTask(
|
||
user_id=current_user.id,
|
||
task_type=req.task_type,
|
||
params=json.dumps(req.params or {}, ensure_ascii=False),
|
||
)
|
||
db.add(task)
|
||
db.commit()
|
||
db.refresh(task)
|
||
return _task_dict(task)
|
||
|
||
|
||
@router.get("/tasks", response_model=dict)
|
||
def list_tasks(
|
||
limit: int = Query(20, ge=1, le=100),
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""控制端任务历史(倒序)"""
|
||
rows = db.query(RpaTask).filter(RpaTask.user_id == current_user.id) \
|
||
.order_by(RpaTask.id.desc()).limit(limit).all()
|
||
return {"items": [_task_dict(t) for t in rows]}
|
||
|
||
|
||
@router.get("/tasks/pending", response_model=dict)
|
||
def fetch_pending_task(
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""客户端轮询:取走最早一条 pending 并标记 running(认领即占位,防重复拉取)"""
|
||
# 顺带过期清理:pending 超时未认领 → expired
|
||
cutoff = datetime.utcnow() - timedelta(minutes=PENDING_EXPIRE_MINUTES)
|
||
stale = db.query(RpaTask).filter(
|
||
RpaTask.user_id == current_user.id,
|
||
RpaTask.status == "pending",
|
||
RpaTask.created_at < cutoff,
|
||
).all()
|
||
for t in stale:
|
||
t.status = "expired"
|
||
t.result = f"超过 {PENDING_EXPIRE_MINUTES} 分钟未执行,自动过期"
|
||
|
||
task = db.query(RpaTask).filter(
|
||
RpaTask.user_id == current_user.id,
|
||
RpaTask.status == "pending",
|
||
).order_by(RpaTask.id.asc()).first()
|
||
if not task:
|
||
db.commit()
|
||
return {"task": None}
|
||
task.status = "running"
|
||
db.commit()
|
||
db.refresh(task)
|
||
return {"task": _task_dict(task)}
|
||
|
||
|
||
@router.post("/tasks/{task_id}/finish", response_model=Message)
|
||
def finish_task(
|
||
task_id: int,
|
||
req: RpaTaskFinishIn,
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""客户端执行完回调:更新任务终态与结果"""
|
||
if req.status not in ("done", "failed"):
|
||
raise HTTPException(status_code=422, detail="回调状态只能为 done/failed")
|
||
task = db.query(RpaTask).filter(
|
||
RpaTask.id == task_id,
|
||
RpaTask.user_id == current_user.id,
|
||
).first()
|
||
if not task:
|
||
raise HTTPException(status_code=404, detail="任务不存在")
|
||
task.status = req.status
|
||
task.result = (req.result or "")[:500]
|
||
db.commit()
|
||
return Message(msg="ok")
|
||
|
||
|
||
# =======================================================
|
||
# 定时任务排程(每日到点由调度器自动下发 RpaTask)
|
||
# =======================================================
|
||
def _schedule_dict(s: RpaSchedule) -> dict:
|
||
return {
|
||
"id": s.id,
|
||
"kind": s.kind,
|
||
"params": json.loads(s.params) if s.params else None,
|
||
"start_time": s.start_time,
|
||
"end_time": s.end_time,
|
||
"enabled": bool(s.enabled),
|
||
"last_start_date": s.last_start_date,
|
||
"last_stop_date": s.last_stop_date,
|
||
"last_result": s.last_result,
|
||
"created_at": (s.created_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
|
||
}
|
||
|
||
|
||
@router.get("/schedules", response_model=dict)
|
||
def list_schedules(
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""当前用户的定时排程列表(倒序)"""
|
||
rows = db.query(RpaSchedule).filter(RpaSchedule.user_id == current_user.id) \
|
||
.order_by(RpaSchedule.id.desc()).all()
|
||
return {"items": [_schedule_dict(s) for s in rows]}
|
||
|
||
|
||
@router.post("/schedules", response_model=dict)
|
||
def create_schedule(
|
||
req: RpaScheduleIn,
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""创建定时排程。不做客户端在线预检(定时本就是为无人值守场景,
|
||
下发时若离线由 pending 过期机制兑底)"""
|
||
if req.kind not in KIND_TASK_TYPES:
|
||
raise HTTPException(status_code=422, detail="任务类型只能为 apply(自动投递)或 activate(Boss激活)")
|
||
if not _TIME_RE.match(req.start_time or "") or not _TIME_RE.match(req.end_time or ""):
|
||
raise HTTPException(status_code=422, detail="时间格式应为 HH:MM(24 小时制)")
|
||
if req.end_time <= req.start_time:
|
||
raise HTTPException(status_code=422, detail="结束时间必须晚于开始时间")
|
||
|
||
params = req.params or {}
|
||
if req.kind == "apply":
|
||
if not params.get("keywords") or not params.get("city"):
|
||
raise HTTPException(status_code=422, detail="定时投递必须提供 keywords 与 city")
|
||
else: # activate
|
||
if not (params.get("match_text") or "").strip():
|
||
raise HTTPException(status_code=422, detail="定时激活必须提供匹配条件文本 match_text")
|
||
if not (params.get("reply_message") or "").strip():
|
||
raise HTTPException(status_code=422, detail="定时激活必须提供激活消息 reply_message")
|
||
if params.get("status_filter") not in (None, "unread", "read", "all"):
|
||
raise HTTPException(status_code=422, detail="消息状态过滤取值非法")
|
||
|
||
sched = RpaSchedule(
|
||
user_id=current_user.id,
|
||
kind=req.kind,
|
||
params=json.dumps(params, ensure_ascii=False),
|
||
start_time=req.start_time,
|
||
end_time=req.end_time,
|
||
enabled=True,
|
||
)
|
||
db.add(sched)
|
||
db.commit()
|
||
db.refresh(sched)
|
||
return _schedule_dict(sched)
|
||
|
||
|
||
@router.put("/schedules/{schedule_id}", response_model=dict)
|
||
def toggle_schedule(
|
||
schedule_id: int,
|
||
enabled: bool = Query(..., description="启用/停用"),
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""启用/停用定时排程"""
|
||
sched = db.query(RpaSchedule).filter(
|
||
RpaSchedule.id == schedule_id,
|
||
RpaSchedule.user_id == current_user.id,
|
||
).first()
|
||
if not sched:
|
||
raise HTTPException(status_code=404, detail="排程不存在")
|
||
sched.enabled = enabled
|
||
db.commit()
|
||
return _schedule_dict(sched)
|
||
|
||
|
||
@router.delete("/schedules/{schedule_id}", response_model=Message)
|
||
def delete_schedule(
|
||
schedule_id: int,
|
||
current_user: User = Depends(get_current_user),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
"""删除定时排程(仅停止后续调度,不影响已下发的任务)"""
|
||
sched = db.query(RpaSchedule).filter(
|
||
RpaSchedule.id == schedule_id,
|
||
RpaSchedule.user_id == current_user.id,
|
||
).first()
|
||
if not sched:
|
||
raise HTTPException(status_code=404, detail="排程不存在")
|
||
db.delete(sched)
|
||
db.commit()
|
||
return Message(msg="已删除")
|