package panel import ( "context" "encoding/json" "errors" "net/http" "net/url" "sea-vhost/internal/schedulerbridge" "strconv" "strings" ) type SystemScheduler interface { EnsureSystemScheduler(context.Context) (int64, error) } func (c *BrokerClient) EnsureSystemScheduler(ctx context.Context) (int64, error) { v, e := c.operation(ctx, brokerRequest{Operation: "ensure_scheduler"}) return v.ID, e } func (Mock) EnsureSystemScheduler(context.Context) (int64, error) { return 1, nil } func (c *Client) EnsureSystemScheduler(ctx context.Context) (int64, error) { raw, e := c.request(ctx, http.MethodPost, "/crontab", url.Values{"action": {"GetCrontab"}, "search": {schedulerbridge.CronName}}) if e != nil { return 0, e } type task struct { ID int64 `json:"id"` Name string `json:"name"` Body string `json:"sBody"` Status int `json:"status"` Type string `json:"type"` Where1 json.RawMessage `json:"where1"` } var rows []task if json.Unmarshal(raw, &rows) != nil { var envelope struct { Data []task `json:"data"` } if json.Unmarshal(raw, &envelope) != nil || envelope.Data == nil { return 0, errors.New("无法读取宝塔计划任务") } rows = envelope.Data } for _, v := range rows { if v.Name == schedulerbridge.CronName { if v.Body != schedulerbridge.Command || v.Type != "minute-n" || strings.Trim(string(v.Where1), `"`) != "1" { return 0, errors.New("同名计划任务配置不同,请在宝塔检查") } if v.Status != 1 { if _, e = c.call(ctx, http.MethodPost, "/crontab", url.Values{"action": {"set_cron_status"}, "id": {strconv.FormatInt(v.ID, 10)}}); e != nil { return 0, e } } return v.ID, nil } } v, e := c.call(ctx, http.MethodPost, "/crontab", url.Values{"action": {"AddCrontab"}, "name": {schedulerbridge.CronName}, "type": {"minute-n"}, "where1": {"1"}, "where_hour": {"0"}, "where_minute": {"0"}, "user": {"root"}, "urladdress": {"http://"}, "save_local": {"0"}, "notice": {"0"}, "notice_channel": {""}, "sType": {"toShell"}, "sBody": {schedulerbridge.Command}, "sName": {schedulerbridge.CronName}, "save": {"0"}, "backupTo": {"localhost"}}) if e != nil { return 0, e } if v.ID < 1 { return 0, errors.New("宝塔未返回计划任务编号") } return v.ID, nil }