feat: 新增壳子内置定时任务功能,支持配置备份与恢复
本次提交新增完整的定时任务系统: 1. 后端支持cron表达式调度插件执行,与手动运行共用执行链路 2. 前端新增定时任务管理页面,支持增删改查与启停操作 3. 实现配置自动备份到中心机,启动时自动从云端恢复任务 4. 配套新增数据库表与控制面API接口 5. 同时优化了考勤异常检查的规则细节
This commit is contained in:
@@ -1,19 +1,18 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。"""
|
||||
"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。
|
||||
|
||||
手动启动入口复用 runner.submit_run(与定时任务共用同一执行链路);
|
||||
本文件只承担:登录门槛 + 插件查找 + 授权校验(403 前置门禁)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, WebSocket
|
||||
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.runner import RunReq, _run_target, terminate_run
|
||||
from webhost.backend.core.runner import RunReq, submit_run, terminate_run
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
@@ -36,51 +35,7 @@ def start_run(req: RunReq, request: Request) -> dict:
|
||||
if deny:
|
||||
_LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny)
|
||||
raise HTTPException(403, deny)
|
||||
run_id = uuid.uuid4().hex
|
||||
with _st.RUN_LOCK:
|
||||
if len(_st.RUNS) >= _st.MAX_RUNS:
|
||||
_st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录
|
||||
_st.RUNS[run_id] = {"status": "running", "account": account,
|
||||
"version": getattr(plugin, "version", "0"),
|
||||
"started": time.time(),
|
||||
"result": None, "error": None}
|
||||
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"at": datetime.now().strftime("%H:%M:%S")})
|
||||
licensing.report(account=account, device_id="", plugin_id=plugin.id,
|
||||
version=getattr(plugin, "version", "0"), status="start")
|
||||
|
||||
def _queued():
|
||||
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
|
||||
gate = _st._ns_gate(plugin.platform)
|
||||
if gate.locked():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
|
||||
with gate:
|
||||
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
|
||||
if _scheduler._is_busy():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
# start_fn 无参调用(scheduler 约定):run_id 由外层闭包捕获;
|
||||
# 之前签名带 _run_id 形参会因 TypeError 启动失败且被静默吞掉,运行记录永久卡 running
|
||||
def _start():
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, req.fields, run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
return run_id
|
||||
r = _scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
if not r.get("ok"):
|
||||
# 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待
|
||||
_st._set_run(run_id, status="error", result=None,
|
||||
error=r.get("error") or "启动失败")
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": r.get("error") or "启动失败"})
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
run_id = submit_run(account, plugin, req.fields or {})
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「定时任务」路由:增删改查 + 启停;变更后自动备份到中心机(防丢失)。
|
||||
|
||||
- 任务归属创建者账号(配置时登录账号),仅创建者可修改/删除/启停。
|
||||
- cron 为 5 段标准表达式(分 时 日 月 周),由 core.tasks 解析与触发。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend.core import tasks as _tasks
|
||||
from webhost.backend.core.session import _require_login
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class _SchedIn(BaseModel):
|
||||
name: str = ""
|
||||
plugin_id: str = ""
|
||||
fields: dict = {}
|
||||
cron: str = ""
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class _ToggleIn(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
|
||||
def _find_owned(sid: str, account: str) -> dict:
|
||||
"""按 id 取任务并校验归属;不存在/非本人抛 HTTP 异常。"""
|
||||
s = _tasks.get_schedule(sid)
|
||||
if s is None:
|
||||
raise HTTPException(404, "任务不存在")
|
||||
if s.get("account") != account:
|
||||
raise HTTPException(403, "仅创建者可管理该任务")
|
||||
return s
|
||||
|
||||
|
||||
@router.get("/api/schedules")
|
||||
def sched_list(request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
return {"schedules": _tasks.list_schedules(account)}
|
||||
|
||||
|
||||
@router.post("/api/schedules", status_code=201)
|
||||
def sched_create(b: _SchedIn, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
if not b.plugin_id:
|
||||
raise HTTPException(400, "请选择插件")
|
||||
try:
|
||||
PLUGINS.find(b.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
try:
|
||||
rec = _tasks.create_schedule(account, b.model_dump())
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, f"cron 表达式无效:{e}")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return rec
|
||||
|
||||
|
||||
@router.put("/api/schedules/{sid}")
|
||||
def sched_update(sid: str, b: _SchedIn, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
_find_owned(sid, account)
|
||||
if b.plugin_id:
|
||||
try:
|
||||
PLUGINS.find(b.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
try:
|
||||
rec = _tasks.update_schedule(sid, b.model_dump(exclude_unset=True))
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, f"cron 表达式无效:{e}")
|
||||
if rec is None:
|
||||
raise HTTPException(404, "任务不存在")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return rec
|
||||
|
||||
|
||||
@router.delete("/api/schedules/{sid}")
|
||||
def sched_delete(sid: str, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
_find_owned(sid, account)
|
||||
if not _tasks.delete_schedule(sid):
|
||||
raise HTTPException(404, "任务不存在")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/schedules/{sid}/toggle")
|
||||
def sched_toggle(sid: str, b: _ToggleIn, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
_find_owned(sid, account)
|
||||
rec = _tasks.toggle_schedule(sid, b.enabled)
|
||||
if rec is None:
|
||||
raise HTTPException(404, "任务不存在")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return rec
|
||||
@@ -13,6 +13,7 @@ import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
@@ -32,6 +33,61 @@ class RunReq(BaseModel):
|
||||
fields: dict = {}
|
||||
|
||||
|
||||
def submit_run(account: str, plugin, fields: dict) -> str:
|
||||
"""启动一次插件运行(手动 POST /api/runs 与定时任务共用入口)。
|
||||
|
||||
- 登记运行记录 + 广播 run_start + 上报 start;
|
||||
- 后台线程执行:命名空间并发闸(同平台串行)→ 设备级单活(排队等待当前插件结束)
|
||||
→ 拉起执行子进程;启动失败回滚单活槽位并广播 run_done(error)。
|
||||
返回 run_id。
|
||||
"""
|
||||
run_id = uuid.uuid4().hex
|
||||
with _st.RUN_LOCK:
|
||||
if len(_st.RUNS) >= _st.MAX_RUNS:
|
||||
_st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录
|
||||
_st.RUNS[run_id] = {"status": "running", "account": account,
|
||||
"version": getattr(plugin, "version", "0"),
|
||||
"started": time.time(),
|
||||
"result": None, "error": None}
|
||||
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"at": datetime.now().strftime("%H:%M:%S")})
|
||||
licensing.report(account=account, device_id="", plugin_id=plugin.id,
|
||||
version=getattr(plugin, "version", "0"), status="start")
|
||||
|
||||
def _queued():
|
||||
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
|
||||
gate = _st._ns_gate(plugin.platform)
|
||||
if gate.locked():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
|
||||
with gate:
|
||||
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
|
||||
if _scheduler._is_busy():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
def _start():
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, fields, run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
return run_id
|
||||
|
||||
r = _scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
if not r.get("ok"):
|
||||
# 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待
|
||||
_st._set_run(run_id, status="error", result=None,
|
||||
error=r.get("error") or "启动失败")
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": r.get("error") or "启动失败"})
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
return run_id
|
||||
|
||||
|
||||
# ==================== 手动强制停止 ====================
|
||||
# run_id → 执行中 Job 句柄(供 POST /api/runs/{id}/stop 整树强杀,含浏览器孙进程)
|
||||
_ACTIVE: dict = {}
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主定时任务(壳子内置定时):按 cron 触发插件运行。
|
||||
|
||||
- 配置真源:%LOCALAPPDATA%\\37duAutomation\\schedules.json(按账号隔离,任务归属创建者账号)。
|
||||
- 触发链路与手动 POST /api/runs 完全一致(runner.submit_run):
|
||||
命名空间并发闸 + 设备级单活排队 + 授权/下架/禁用/强制更新校验(licensing.run_check_allowed)。
|
||||
- 变更即备份:增删改/启停后把该账号全量配置推送到中心机(/api/schedules/backup);
|
||||
本地缺失时启动按账号从服务端合并恢复(见 restore_from_cloud),配置不丢失。
|
||||
- 后台线程每 30s 检查一次,到点触发;last_run_at 记忆上次触发时刻,
|
||||
壳子重启后错过的触发点会立即补跑(last_run_at 之前的值保留,不重复触发同一时刻)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
or Path.home(), "37duAutomation")
|
||||
_SCHED_FILE = _APP_DATA / "schedules.json"
|
||||
|
||||
_TICK_SECS = 30 # 后台检查周期(秒)
|
||||
_STARTED = False
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
# 内存中的任务列表(dict 列表),持久化到 _SCHED_FILE
|
||||
_SCHEDULES: list = []
|
||||
|
||||
|
||||
# ==================== 标准 5 段 cron 解析 ====================
|
||||
# 字段顺序:分 时 日 月 周(minute hour day-of-month month day-of-week)
|
||||
def _parse_field(spec: str, lo: int, hi: int) -> set:
|
||||
"""解析单个 cron 字段为命中集合;支持 * ? */n a-b a-b/n 与逗号列表。非法抛 ValueError。"""
|
||||
if spec in ("*", "?"):
|
||||
return set(range(lo, hi + 1))
|
||||
out: set = set()
|
||||
for part in str(spec).split(","):
|
||||
part = part.strip()
|
||||
if not part:
|
||||
continue
|
||||
step = 1
|
||||
if "/" in part:
|
||||
part, _, step_s = part.partition("/")
|
||||
try:
|
||||
step = int(step_s)
|
||||
except ValueError:
|
||||
raise ValueError(f"无效步长:{step_s}")
|
||||
if step < 1:
|
||||
raise ValueError(f"无效步长:{step_s}")
|
||||
if part in ("*", "?"):
|
||||
rng = (lo, hi)
|
||||
elif "-" in part:
|
||||
a, _, b = part.partition("-")
|
||||
rng = (int(a), int(b))
|
||||
else:
|
||||
v = int(part)
|
||||
rng = (v, v)
|
||||
a, b = rng
|
||||
if not (lo <= a <= hi and lo <= b <= hi) or a > b:
|
||||
raise ValueError(f"字段越界:{part}")
|
||||
out.update(range(a, b + 1, step))
|
||||
if not out:
|
||||
raise ValueError("空字段")
|
||||
return out
|
||||
|
||||
|
||||
def parse_cron(expr: str) -> dict:
|
||||
"""解析 5 段 cron 表达式;非法抛 ValueError。返回 {minute,hour,dom,month,dow} 集合。"""
|
||||
parts = str(expr or "").strip().split()
|
||||
if len(parts) != 5:
|
||||
raise ValueError("cron 需为 5 段:分 时 日 月 周")
|
||||
minute = _parse_field(parts[0], 0, 59)
|
||||
hour = _parse_field(parts[1], 0, 23)
|
||||
dom = _parse_field(parts[2], 1, 31)
|
||||
month = _parse_field(parts[3], 1, 12)
|
||||
dow = _parse_field(parts[4], 0, 7)
|
||||
has7 = 7 in dow # 标准 cron 中 0 与 7 均表示周日
|
||||
dow.discard(7)
|
||||
if has7:
|
||||
dow.add(0)
|
||||
return {"minute": minute, "hour": hour, "dom": dom, "month": month, "dow": dow}
|
||||
|
||||
|
||||
def _cron_dow(dt: datetime) -> int:
|
||||
"""cron 周日编号:0=周日,1=周一 … 6=周六。"""
|
||||
return (dt.weekday() + 1) % 7
|
||||
|
||||
|
||||
def next_match(cron: dict, after: datetime) -> datetime | None:
|
||||
"""返回严格晚于 after 的最近一个匹配时刻;一年内无匹配返回 None(如 2 月 30 日)。"""
|
||||
minute, hour, dom, month, dow = (cron["minute"], cron["hour"], cron["dom"],
|
||||
cron["month"], cron["dow"])
|
||||
dom_any = dom == set(range(1, 32))
|
||||
dow_any = dow == set(range(0, 7))
|
||||
t = after.replace(second=0, microsecond=0) + timedelta(minutes=1)
|
||||
for _ in range(10000):
|
||||
if t.month not in month:
|
||||
y, m = (t.year + 1, 1) if t.month == 12 else (t.year, t.month + 1)
|
||||
t = datetime(y, m, 1)
|
||||
continue
|
||||
# 标准语义:dom 与 dow 均有限制时,命中其一即可;仅一方限制则只按该方
|
||||
if not dom_any and not dow_any:
|
||||
day_ok = (t.day in dom) or (_cron_dow(t) in dow)
|
||||
elif not dow_any:
|
||||
day_ok = _cron_dow(t) in dow
|
||||
elif not dom_any:
|
||||
day_ok = t.day in dom
|
||||
else:
|
||||
day_ok = True
|
||||
if not day_ok:
|
||||
t = (t + timedelta(days=1)).replace(hour=0, minute=0)
|
||||
continue
|
||||
if t.hour not in hour:
|
||||
t = (t + timedelta(hours=1)).replace(minute=0)
|
||||
continue
|
||||
if t.minute not in minute:
|
||||
t += timedelta(minutes=1)
|
||||
continue
|
||||
return t
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 本地存储与 CRUD ====================
|
||||
def _load() -> None:
|
||||
global _SCHEDULES
|
||||
with _LOCK:
|
||||
if _SCHED_FILE.is_file():
|
||||
try:
|
||||
data = json.loads(_SCHED_FILE.read_text(encoding="utf-8"))
|
||||
_SCHEDULES = [s for s in (data or {}).get("schedules", [])
|
||||
if isinstance(s, dict)]
|
||||
except (OSError, ValueError):
|
||||
_LOGGER.warning("定时任务配置损坏,已忽略:%s", _SCHED_FILE)
|
||||
_SCHEDULES = []
|
||||
else:
|
||||
_SCHEDULES = []
|
||||
|
||||
|
||||
def _persist() -> None:
|
||||
with _LOCK:
|
||||
_SCHED_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
_SCHED_FILE.write_text(
|
||||
json.dumps({"schedules": _SCHEDULES}, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _new_id() -> str:
|
||||
return f"{int(time.time() * 1000):x}{os.urandom(4).hex()}"
|
||||
|
||||
|
||||
def get_schedule(sid: str) -> dict | None:
|
||||
"""按 id 取原始记录(调用方须持锁前读取,路由层只读不持有引用长期使用)。"""
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if s.get("id") == sid:
|
||||
return dict(s)
|
||||
return None
|
||||
|
||||
|
||||
def list_schedules(account: str) -> list:
|
||||
with _LOCK:
|
||||
return [_public(s) for s in _SCHEDULES if s.get("account") == account]
|
||||
|
||||
|
||||
def create_schedule(account: str, payload: dict) -> dict:
|
||||
"""新增定时任务(cron 非法抛 ValueError)。"""
|
||||
cron = (payload.get("cron") or "").strip()
|
||||
parse_cron(cron)
|
||||
rec = {
|
||||
"id": _new_id(),
|
||||
"name": (payload.get("name") or "").strip() or "定时任务",
|
||||
"account": account,
|
||||
"plugin_id": payload.get("plugin_id", ""),
|
||||
"fields": payload.get("fields") or {},
|
||||
"cron": cron,
|
||||
"enabled": bool(payload.get("enabled", True)),
|
||||
"last_run_at": "",
|
||||
"created_at": _now(),
|
||||
"updated_at": _now(),
|
||||
}
|
||||
with _LOCK:
|
||||
_SCHEDULES.append(rec)
|
||||
_persist()
|
||||
return dict(rec)
|
||||
|
||||
|
||||
def update_schedule(sid: str, payload: dict) -> dict | None:
|
||||
"""更新任务(仅覆盖 payload 中出现的字段;cron 非法抛 ValueError)。"""
|
||||
if payload.get("cron"):
|
||||
parse_cron(payload["cron"])
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if s.get("id") != sid:
|
||||
continue
|
||||
if "name" in payload:
|
||||
s["name"] = (payload["name"] or "").strip() or "定时任务"
|
||||
if "plugin_id" in payload:
|
||||
s["plugin_id"] = payload["plugin_id"]
|
||||
if "fields" in payload:
|
||||
s["fields"] = payload["fields"] or {}
|
||||
if payload.get("cron"):
|
||||
s["cron"] = payload["cron"].strip()
|
||||
if "enabled" in payload:
|
||||
s["enabled"] = bool(payload["enabled"])
|
||||
s["updated_at"] = _now()
|
||||
_persist()
|
||||
return dict(s)
|
||||
return None
|
||||
|
||||
|
||||
def delete_schedule(sid: str) -> bool:
|
||||
with _LOCK:
|
||||
for i, s in enumerate(_SCHEDULES):
|
||||
if s.get("id") == sid:
|
||||
_SCHEDULES.pop(i)
|
||||
_persist()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def toggle_schedule(sid: str, enabled: bool) -> dict | None:
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if s.get("id") == sid:
|
||||
s["enabled"] = bool(enabled)
|
||||
s["updated_at"] = _now()
|
||||
_persist()
|
||||
return dict(s)
|
||||
return None
|
||||
|
||||
|
||||
def next_run_at(s: dict) -> datetime | None:
|
||||
"""该任务最近一次触发后的下一次触发时刻(未跑过则取首次未来触发)。"""
|
||||
try:
|
||||
cron = parse_cron(s.get("cron", ""))
|
||||
except ValueError:
|
||||
return None
|
||||
try:
|
||||
last = datetime.fromisoformat(s.get("last_run_at")) if s.get("last_run_at") else None
|
||||
except (TypeError, ValueError):
|
||||
last = None
|
||||
return next_match(cron, last if last else datetime.now())
|
||||
|
||||
|
||||
def _public(s: dict) -> dict:
|
||||
out = dict(s)
|
||||
out["enabled"] = bool(out.get("enabled"))
|
||||
out["last_run_at"] = out.get("last_run_at") or ""
|
||||
nxt = next_run_at(s)
|
||||
out["next_run_at"] = nxt.strftime("%Y-%m-%d %H:%M:%S") if nxt else ""
|
||||
return out
|
||||
|
||||
|
||||
def _export(account: str) -> list:
|
||||
with _LOCK:
|
||||
return [dict(s) for s in _SCHEDULES if s.get("account") == account]
|
||||
|
||||
|
||||
# ==================== 后台触发 ====================
|
||||
def start() -> None:
|
||||
"""启动后台定时检查线程(幂等)。"""
|
||||
global _STARTED
|
||||
with _LOCK:
|
||||
if _STARTED:
|
||||
return
|
||||
_STARTED = True
|
||||
threading.Thread(target=_loop, daemon=True, name="sched-tick").start()
|
||||
_LOGGER.info("定时任务后台检查已启动(每 %ds 一次)", _TICK_SECS)
|
||||
|
||||
|
||||
def _loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
_tick()
|
||||
except Exception as _exc: # noqa: BLE001 单轮异常不影响后续检查
|
||||
_LOGGER.warning("定时任务检查异常:%s", _exc)
|
||||
time.sleep(_TICK_SECS)
|
||||
|
||||
|
||||
def _tick() -> None:
|
||||
now = datetime.now()
|
||||
due = []
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if not s.get("enabled"):
|
||||
continue
|
||||
try:
|
||||
cron = parse_cron(s.get("cron", ""))
|
||||
except ValueError:
|
||||
continue
|
||||
try:
|
||||
last = (datetime.fromisoformat(s.get("last_run_at"))
|
||||
if s.get("last_run_at") else None)
|
||||
except (TypeError, ValueError):
|
||||
last = None
|
||||
nxt = next_match(cron, last if last else now)
|
||||
if nxt and nxt <= now:
|
||||
due.append((s, nxt))
|
||||
fired = False
|
||||
for s, nxt in due:
|
||||
if _fire(s):
|
||||
with _LOCK:
|
||||
s["last_run_at"] = nxt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
fired = True
|
||||
if fired:
|
||||
_persist()
|
||||
|
||||
|
||||
def _fire(s: dict) -> bool:
|
||||
"""触发一次定时任务:授权校验通过后走 submit_run 启动;返回是否已启动。"""
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core.runner import submit_run
|
||||
|
||||
try:
|
||||
plugin = PLUGINS.find(s.get("plugin_id", ""))
|
||||
except KeyError:
|
||||
_LOGGER.warning("定时任务「%s」的插件 %s 不存在,跳过触发",
|
||||
s.get("name"), s.get("plugin_id"))
|
||||
return False
|
||||
account = s.get("account", "")
|
||||
deny = licensing.run_check_allowed(plugin.id, account, licensing.is_online())
|
||||
if deny:
|
||||
_LOGGER.warning("定时任务「%s」触发被拒(账号 %s):%s",
|
||||
s.get("name"), account, deny)
|
||||
return False
|
||||
try:
|
||||
submit_run(account, plugin, s.get("fields") or {})
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("定时任务「%s」启动失败:%s", s.get("name"), _exc)
|
||||
return False
|
||||
_LOGGER.info("定时任务触发:「%s」(插件 %s,账号 %s)",
|
||||
s.get("name"), plugin.id, account)
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 中心机备份(防丢失) ====================
|
||||
def push_backup_async(request, account: str) -> None:
|
||||
"""变更后把该账号全量配置异步备份到中心机;失败静默(不阻断用户操作)。"""
|
||||
from webhost.backend import config
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return
|
||||
|
||||
def _run():
|
||||
try:
|
||||
from webhost.backend.core.cpapi import _cp_headers, _cp_call
|
||||
headers = {**_cp_headers(request), "Content-Type": "application/json"}
|
||||
_cp_call("POST", "/api/schedules/backup",
|
||||
headers=headers,
|
||||
json={"data": {"schedules": _export(account)}})
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("定时任务备份失败(账号 %s):%s", account, _exc)
|
||||
|
||||
threading.Thread(target=_run, daemon=True, name="sched-backup").start()
|
||||
|
||||
|
||||
def restore_from_cloud() -> None:
|
||||
"""启动时按当前活跃账号从中心机合并恢复缺失的任务(本地已有 id 不覆盖)。
|
||||
|
||||
仅作「防丢失」兜底:本地配置为真源,服务端备份只在本地缺失对应任务时补充。
|
||||
"""
|
||||
from webhost.backend import config
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return
|
||||
from webhost.backend.core.session import _sess_active_account, _ACCT_CLOUD_TOKEN
|
||||
account = _sess_active_account()
|
||||
if not account:
|
||||
return
|
||||
headers = {"X-Admin-User": account}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
cloud_tok = (_ACCT_CLOUD_TOKEN or {}).get(account)
|
||||
if cloud_tok:
|
||||
headers["Authorization"] = f"Bearer {cloud_tok}"
|
||||
import requests
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/schedules/backup",
|
||||
headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
remote = (r.json().get("data") or {}).get("schedules") or []
|
||||
except Exception as _exc: # noqa: BLE001 恢复失败不影响启动
|
||||
_LOGGER.warning("定时任务云端恢复失败(跳过):%s", _exc)
|
||||
return
|
||||
added = 0
|
||||
with _LOCK:
|
||||
local_ids = {s.get("id") for s in _SCHEDULES}
|
||||
for s in remote:
|
||||
if (not isinstance(s, dict) or s.get("id") in local_ids
|
||||
or s.get("account") != account):
|
||||
continue
|
||||
try:
|
||||
parse_cron(s.get("cron", ""))
|
||||
except ValueError:
|
||||
continue
|
||||
_SCHEDULES.append(s)
|
||||
added += 1
|
||||
if added:
|
||||
_persist()
|
||||
if added:
|
||||
_LOGGER.info("定时任务云端恢复 %d 条(账号 %s)", added, account)
|
||||
|
||||
|
||||
def init() -> None:
|
||||
"""启动初始化:加载本地配置 + 启动后台检查线程 + 云端补恢复。"""
|
||||
_load()
|
||||
start()
|
||||
restore_from_cloud()
|
||||
@@ -33,6 +33,7 @@ from webhost.backend.apis import dingtalk as api_dingtalk
|
||||
from webhost.backend.apis import meta as api_meta
|
||||
from webhost.backend.apis import plugin_ui as api_plugin_ui
|
||||
from webhost.backend.apis import runs as api_runs
|
||||
from webhost.backend.apis import schedules as api_schedules
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -92,6 +93,9 @@ async def lifespan(app: FastAPI):
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
_shell_updater.start_check()
|
||||
_shell_updater.start_periodic_check()
|
||||
# 壳子内置定时任务:加载本地配置 + 启动后台触发线程 + 从中心机合并恢复(防丢失)
|
||||
from webhost.backend.core import tasks as _boot_tasks
|
||||
_boot_tasks.init()
|
||||
yield
|
||||
except BaseException:
|
||||
# lifespan 失败会被 uvicorn 吞成 SystemExit(3);frozen 下 stderr 已重定向 devnull,
|
||||
@@ -115,6 +119,7 @@ app.include_router(api_admin.router)
|
||||
app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_meta.router)
|
||||
app.include_router(api_runs.router)
|
||||
app.include_router(api_schedules.router)
|
||||
app.include_router(api_plugin_ui.router)
|
||||
|
||||
|
||||
|
||||
@@ -137,6 +137,12 @@
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="!store.plugins.length" class="scene-empty">当前账号暂无可用场景<br><span>请联系管理员进行授权</span></div>
|
||||
<div class="side-nav" @click="openSchedules">
|
||||
<span class="nav-item" :class="{ active: store.view === 'schedules' }">
|
||||
<el-icon><Clock /></el-icon>
|
||||
<span>定时任务</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="side-foot">
|
||||
<div class="foot-ver">
|
||||
<span class="ver-num">壳子 {{ shellUpdate.current ? 'v' + shellUpdate.current : '未打包' }}</span>
|
||||
@@ -151,6 +157,7 @@
|
||||
<main class="main">
|
||||
<div class="page-scroll panel">
|
||||
<PluginPage v-if="store.view === 'plugin'" />
|
||||
<SchedulePage v-else-if="store.view === 'schedules'" />
|
||||
</div>
|
||||
<LogPanel />
|
||||
</main>
|
||||
@@ -185,8 +192,9 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { Clock, Refresh } from '@element-plus/icons-vue'
|
||||
import PluginPage from './components/PluginPage.vue'
|
||||
import SchedulePage from './components/SchedulePage.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import ProfilePanel from './components/ProfilePanel.vue'
|
||||
@@ -208,6 +216,10 @@ function openPlugin(id) {
|
||||
store.view = 'plugin'
|
||||
}
|
||||
|
||||
function openSchedules() {
|
||||
store.view = 'schedules'
|
||||
}
|
||||
|
||||
function openWS() {
|
||||
if (window.__ws) window.__ws.close()
|
||||
const ws = connectWS(handleEvent)
|
||||
@@ -764,6 +776,19 @@ async function login(id) {
|
||||
}
|
||||
.scene-empty span { font-size: 11px; color: var(--text-faint); }
|
||||
.side-foot { font-size: 10px; color: var(--text-faint); text-align: center; padding-top: 10px; border-top: 1px dashed var(--border); margin-top: 8px; display: flex; flex-direction: column; gap: 4px; }
|
||||
.side-nav { padding: 6px 4px; }
|
||||
.nav-item {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 9px 10px; border-radius: var(--radius-sm); cursor: pointer;
|
||||
color: var(--text-sub); font-size: 13px; position: relative;
|
||||
transition: background .13s;
|
||||
}
|
||||
.side-nav:hover .nav-item { background: var(--surface-2); }
|
||||
.nav-item.active { background: var(--primary-weak); color: var(--primary); font-weight: 600; }
|
||||
.nav-item.active::before {
|
||||
content: ''; position: absolute; left: 0; top: 9px; bottom: 9px;
|
||||
width: 3px; border-radius: 3px; background: var(--primary);
|
||||
}
|
||||
.foot-ver { display: flex; align-items: center; justify-content: center; gap: 8px; }
|
||||
.ver-num { font-variant-numeric: tabular-nums; }
|
||||
.check-link { font-size: 10px; vertical-align: baseline; }
|
||||
|
||||
@@ -69,6 +69,35 @@ export async function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
// ===== 定时任务(壳子内置定时,配置自动备份中心机) =====
|
||||
export async function listSchedules() {
|
||||
return j('/api/schedules')
|
||||
}
|
||||
export async function createSchedule(body) {
|
||||
return j('/api/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function updateSchedule(sid, body) {
|
||||
return j(`/api/schedules/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function deleteSchedule(sid) {
|
||||
return j(`/api/schedules/${sid}`, { method: 'DELETE' })
|
||||
}
|
||||
export async function toggleSchedule(sid, enabled) {
|
||||
return j(`/api/schedules/${sid}/toggle`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled }),
|
||||
})
|
||||
}
|
||||
|
||||
export function connectWS(onEvent) {
|
||||
const ws = new WebSocket(WS_BASE + '/ws')
|
||||
ws.onmessage = (e) => {
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
<template>
|
||||
<div class="sched-page">
|
||||
<div class="head">
|
||||
<div class="ident">
|
||||
<span class="avatar"><el-icon><Clock /></el-icon></span>
|
||||
<div class="ident-meta">
|
||||
<h2>定时任务</h2>
|
||||
<p>壳子内置定时:按 cron 到点自动执行插件,配置自动备份到中心机防丢失</p>
|
||||
</div>
|
||||
</div>
|
||||
<el-button type="primary" :icon="Plus" @click="openCreate">新建任务</el-button>
|
||||
</div>
|
||||
|
||||
<el-empty v-if="!list.length" description="暂无定时任务,点击右上角「新建任务」创建" />
|
||||
|
||||
<el-table v-else :data="list" class="sched-table" row-key="id">
|
||||
<el-table-column label="任务" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<div class="cell-main">
|
||||
<span class="t-name">{{ row.name }}</span>
|
||||
<span class="t-plugin">{{ pluginName(row.plugin_id) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="cron 表达式" width="140">
|
||||
<template #default="{ row }">
|
||||
<code class="cron">{{ row.cron }}</code>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="下次执行" width="158">
|
||||
<template #default="{ row }">{{ row.next_run_at || '-' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最近执行" width="158">
|
||||
<template #default="{ row }">{{ row.last_run_at || '从未' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="启用" width="80" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-switch :model-value="row.enabled" @change="(v) => onToggle(row, v)" />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="130" align="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="openEdit(row)">编辑</el-button>
|
||||
<el-button link type="danger" @click="onDelete(row)">删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<el-dialog v-model="dlg" :title="editing ? '编辑定时任务' : '新建定时任务'" width="560px" align-center>
|
||||
<el-form label-width="86px" class="dlg-form">
|
||||
<el-form-item label="任务名称">
|
||||
<el-input v-model="form.name" placeholder="如:每日考勤封存检查" maxlength="32" />
|
||||
</el-form-item>
|
||||
<el-form-item label="执行插件">
|
||||
<el-select v-model="form.plugin_id" placeholder="选择要定时执行的插件" class="w-full" @change="onPluginChange">
|
||||
<el-option v-for="p in store.plugins" :key="p.id" :value="p.id"
|
||||
:label="`${p.name}(${p.id})`" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="触发时间">
|
||||
<div class="cron-row">
|
||||
<el-input v-model="form.cron" placeholder="标准 5 段 cron,如 0 8 * * *" class="cron-input">
|
||||
<template #prepend>cron</template>
|
||||
</el-input>
|
||||
<el-select v-model="preset" placeholder="快捷项" class="preset-sel" @change="onPreset">
|
||||
<el-option v-for="p in presets" :key="p.cron" :value="p.cron" :label="p.label" />
|
||||
</el-select>
|
||||
</div>
|
||||
<div class="cron-tip">5 段格式:分 时 日 月 周(0-59 0-23 1-31 1-12 0-6,0/7 均为周日)</div>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="pluginFields.length" label="执行参数">
|
||||
<div class="fields">
|
||||
<div v-for="f in pluginFields" :key="f.key" class="field">
|
||||
<span class="field-label">{{ f.label }}</span>
|
||||
<el-input-number v-if="f.type === 'int'" v-model="form.fields[f.key]" :controls="false"
|
||||
placeholder="0" class="field-ctl" />
|
||||
<el-input v-else-if="f.type === 'password'" v-model="form.fields[f.key]" type="password"
|
||||
show-password :placeholder="String(f.default ?? '')" class="field-ctl" />
|
||||
<el-input v-else-if="f.type === 'text'" v-model="form.fields[f.key]"
|
||||
:placeholder="String(f.default ?? '')" class="field-ctl" />
|
||||
<el-select v-else-if="f.type === 'multiselect'" v-model="form.fields[f.key]" multiple
|
||||
filterable allow-create default-first-option placeholder="选择或输入后回车" class="field-ctl">
|
||||
<el-option v-for="opt in (f.options || [])" :key="opt" :value="opt" :label="opt" />
|
||||
</el-select>
|
||||
<el-select v-else v-model="form.fields[f.key]" class="field-ctl">
|
||||
<el-option v-for="opt in f.options" :key="opt" :value="opt" :label="opt" />
|
||||
</el-select>
|
||||
</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="启用">
|
||||
<el-switch v-model="form.enabled" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="dlg = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="onSave">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Clock, Plus } from '@element-plus/icons-vue'
|
||||
import { store } from '../store'
|
||||
import { listSchedules, createSchedule, updateSchedule, deleteSchedule, toggleSchedule } from '../api'
|
||||
|
||||
const list = ref([])
|
||||
const dlg = ref(false)
|
||||
const editing = ref(null)
|
||||
const saving = ref(false)
|
||||
const preset = ref('')
|
||||
|
||||
const presets = [
|
||||
{ label: '每天 08:00', cron: '0 8 * * *' },
|
||||
{ label: '每天 12:00', cron: '0 12 * * *' },
|
||||
{ label: '每天 18:00', cron: '0 18 * * *' },
|
||||
{ label: '每小时整点', cron: '0 * * * *' },
|
||||
{ label: '每周一 09:00', cron: '0 9 * * 1' },
|
||||
{ label: '每月 1 日 09:00', cron: '0 9 1 * *' },
|
||||
]
|
||||
|
||||
const form = ref({ name: '', plugin_id: '', cron: '', enabled: true, fields: {} })
|
||||
|
||||
const pluginFields = computed(() => {
|
||||
const p = store.plugins.find((x) => x.id === form.value.plugin_id)
|
||||
return (p && p.fields) || []
|
||||
})
|
||||
|
||||
function pluginName(id) {
|
||||
return store.plugins.find((p) => p.id === id)?.name || id
|
||||
}
|
||||
|
||||
function buildFields(p) {
|
||||
const f = {}
|
||||
if (p) p.fields.forEach((x) => (f[x.key] = x.default ?? (x.type === 'int' ? 0 : '')))
|
||||
return f
|
||||
}
|
||||
|
||||
function onPluginChange(id) {
|
||||
form.value.fields = buildFields(store.plugins.find((x) => x.id === id))
|
||||
}
|
||||
|
||||
function onPreset(cron) {
|
||||
form.value.cron = cron
|
||||
preset.value = ''
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const r = await listSchedules()
|
||||
list.value = r.schedules || []
|
||||
} catch (e) {
|
||||
ElMessage.error('加载定时任务失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
editing.value = null
|
||||
form.value = { name: '', plugin_id: '', cron: '', enabled: true, fields: {} }
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
function openEdit(row) {
|
||||
editing.value = row
|
||||
form.value = {
|
||||
name: row.name || '',
|
||||
plugin_id: row.plugin_id || '',
|
||||
cron: row.cron || '',
|
||||
enabled: !!row.enabled,
|
||||
fields: buildFields(store.plugins.find((x) => x.id === row.plugin_id)),
|
||||
}
|
||||
Object.assign(form.value.fields, row.fields || {})
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
async function onSave() {
|
||||
if (!form.value.plugin_id) { ElMessage.warning('请选择执行插件'); return }
|
||||
if (!form.value.cron.trim()) { ElMessage.warning('请填写 cron 表达式'); return }
|
||||
saving.value = true
|
||||
try {
|
||||
if (editing.value) {
|
||||
await updateSchedule(editing.value.id, { ...form.value })
|
||||
ElMessage.success('已保存')
|
||||
} else {
|
||||
await createSchedule({ ...form.value })
|
||||
ElMessage.success('已创建,配置已备份到中心机')
|
||||
}
|
||||
dlg.value = false
|
||||
await load()
|
||||
} catch (e) {
|
||||
ElMessage.error(e.message || String(e))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function onToggle(row, v) {
|
||||
try {
|
||||
await toggleSchedule(row.id, v)
|
||||
row.enabled = v
|
||||
ElMessage.success(v ? '已启用' : '已停用')
|
||||
} catch (e) {
|
||||
ElMessage.error('操作失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
async function onDelete(row) {
|
||||
try {
|
||||
await ElMessageBox.confirm(`确定删除定时任务「${row.name}」?删除后其配置备份会一并移除。`, '删除确认', {
|
||||
type: 'warning',
|
||||
confirmButtonText: '删除',
|
||||
cancelButtonText: '取消',
|
||||
})
|
||||
} catch (_) { return }
|
||||
try {
|
||||
await deleteSchedule(row.id)
|
||||
ElMessage.success('已删除')
|
||||
await load()
|
||||
} catch (e) {
|
||||
ElMessage.error('删除失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
load()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.sched-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.ident {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 13px;
|
||||
flex-shrink: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #fff;
|
||||
background: var(--primary-grad, linear-gradient(135deg, #3b6cff, #7c5cff));
|
||||
box-shadow: var(--shadow-md);
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.ident-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ident-meta h2 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.ident-meta p {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--text-sub);
|
||||
}
|
||||
|
||||
.sched-table {
|
||||
--el-table-border-color: var(--border);
|
||||
--el-table-header-bg-color: var(--surface-2, #f7f8fa);
|
||||
}
|
||||
|
||||
.cell-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.t-name {
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.t-plugin {
|
||||
font-size: 11px;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
.cron {
|
||||
font-family: Consolas, Monaco, monospace;
|
||||
font-size: 12px;
|
||||
color: var(--primary);
|
||||
background: var(--primary-weak, #eef2ff);
|
||||
border-radius: 6px;
|
||||
padding: 2px 6px;
|
||||
}
|
||||
|
||||
.cron-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.cron-input {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.preset-sel {
|
||||
width: 128px;
|
||||
}
|
||||
|
||||
.cron-tip {
|
||||
font-size: 11px;
|
||||
color: var(--text-faint);
|
||||
margin-top: 6px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
width: 96px;
|
||||
flex-shrink: 0;
|
||||
font-size: 13px;
|
||||
color: var(--text-sub);
|
||||
}
|
||||
|
||||
.field-ctl {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.w-full {
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
Reference in New Issue
Block a user