package main import ( "context" _ "embed" "encoding/json" "errors" "io" "log" "math/rand/v2" "net/http" "os" "os/signal" "path/filepath" "strconv" "strings" "sync" "syscall" "time" _ "time/tzdata" "cusiminfo/internal/unicom" ) //go:embed web/index.html var indexPage []byte //go:embed web/favicon.ico var favicon []byte const statePath = "data/state.json" type Config struct { Listen string `json:"listen"` PollInterval string `json:"pollInterval"` JitterMinutes int `json:"jitterMinutes"` Phone string `json:"phone"` } type savedState struct { PollMinutes int `json:"pollMinutes"` JitterMinutes int `json:"jitterMinutes"` } type overview struct { LoggedIn bool `json:"loggedIn"` NeedLogin bool `json:"needLogin"` Refreshing bool `json:"refreshing"` PollEvery string `json:"pollEvery"` PollMinutes int `json:"pollMinutes"` JitterMinutes int `json:"jitterMinutes"` SecondsLeft int `json:"secondsLeft"` RefreshedAt string `json:"refreshedAt,omitempty"` Error string `json:"error,omitempty"` HasData bool `json:"hasData"` LoginEpoch int `json:"loginEpoch"` CaptchaScript string `json:"captchaScript,omitempty"` CaptchaAppID string `json:"captchaAppId,omitempty"` PhonePrefill string `json:"phonePrefill,omitempty"` unicom.Snapshot } type App struct { client *unicom.Client cfgPhone string interval time.Duration jitter time.Duration mu sync.Mutex phone string loggedIn bool snap unicom.Snapshot lastError string refreshed time.Time refreshing bool nextAt time.Time epoch int } func main() { cfg := loadConfig() client, err := unicom.New() if err != nil { log.Fatal(err) } app := &App{client: client, cfgPhone: strings.TrimSpace(cfg.Phone)} app.interval = 30 * time.Minute if d, err := time.ParseDuration(cfg.PollInterval); err == nil && d >= time.Minute { app.interval = d } if cfg.JitterMinutes > 0 { app.jitter = time.Duration(cfg.JitterMinutes) * time.Minute } app.load() prepCtx, cancel := context.WithTimeout(context.Background(), 45*time.Second) if err := app.client.Prepare(prepCtx); err != nil { log.Printf("登录参数暂未就绪,登录时会再试: %v", err) } cancel() ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() go app.loop(ctx) mux := http.NewServeMux() mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-store") _, _ = w.Write(indexPage) }) mux.HandleFunc("GET /favicon.ico", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "image/x-icon") w.Header().Set("Cache-Control", "public, max-age=86400") _, _ = w.Write(favicon) }) mux.HandleFunc("GET /api/overview", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, app.view()) }) mux.HandleFunc("POST /api/sms", app.sms) mux.HandleFunc("POST /api/login", app.login) mux.HandleFunc("GET /api/qr", app.qrCode) mux.HandleFunc("GET /api/qr/poll", app.qrPoll) mux.HandleFunc("POST /api/logout", app.logout) mux.HandleFunc("POST /api/refresh", app.manualRefresh) mux.HandleFunc("POST /api/interval", app.setInterval) srv := &http.Server{Addr: cfg.Listen, Handler: mux, ReadHeaderTimeout: 10 * time.Second} go func() { <-ctx.Done() shut, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() _ = srv.Shutdown(shut) }() log.Printf("已启动,浏览器打开 http://127.0.0.1%s", strings.TrimPrefix(cfg.Listen, "0.0.0.0")) if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatal(err) } } func (a *App) sms(w http.ResponseWriter, r *http.Request) { var req struct { Phone string `json:"phone"` Ticket string `json:"ticket"` Randstr string `json:"randstr"` } if err := decode(r, &req); err != nil { writeErr(w, "请求无法识别") return } phone := strings.TrimSpace(req.Phone) if !validPhone(phone) { writeErr(w, "请输入 11 位手机号") return } if strings.TrimSpace(req.Ticket) == "" || strings.TrimSpace(req.Randstr) == "" { writeErr(w, "请先完成验证码") return } ctx, cancel := context.WithTimeout(r.Context(), 40*time.Second) defer cancel() msg, err := a.client.SendSMS(ctx, phone, req.Ticket, req.Randstr) if err != nil { writeErr(w, err.Error()) return } writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": msg}) } func (a *App) login(w http.ResponseWriter, r *http.Request) { var req struct { Phone string `json:"phone"` SMSCode string `json:"smsCode"` Ticket string `json:"ticket"` Randstr string `json:"randstr"` } if err := decode(r, &req); err != nil { writeErr(w, "请求无法识别") return } phone := strings.TrimSpace(req.Phone) if !validPhone(phone) || strings.TrimSpace(req.SMSCode) == "" { writeErr(w, "请填写手机号和短信验证码") return } ctx, cancel := context.WithTimeout(r.Context(), 50*time.Second) defer cancel() result, err := a.client.Login(ctx, phone, strings.TrimSpace(req.SMSCode), req.Ticket, req.Randstr) if err != nil { writeErr(w, err.Error()) return } a.acceptLogin(result.Phone) writeJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (a *App) qrCode(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 40*time.Second) defer cancel() img, ctype, err := a.client.QRCode(ctx) if err != nil { writeErr(w, err.Error()) return } if ctype == "" { ctype = "image/png" } w.Header().Set("Content-Type", ctype) w.Header().Set("Cache-Control", "no-store") _, _ = w.Write(img) } func (a *App) qrPoll(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 40*time.Second) defer cancel() status, err := a.client.PollQR(ctx) if err != nil { writeErr(w, err.Error()) return } if !status.Waiting && !status.Expired { a.acceptLogin(status.Result.Phone) } writeJSON(w, http.StatusOK, map[string]any{ "ok": true, "waiting": status.Waiting, "scanned": status.Scanned, "expired": status.Expired, "message": status.Message, "loggedIn": !status.Waiting && !status.Expired, }) } func (a *App) acceptLogin(phone string) { a.mu.Lock() a.loggedIn = true if phone != "" { a.phone = phone } a.lastError = "" a.mu.Unlock() a.refresh() a.mu.Lock() if a.loggedIn { log.Printf("登录成功 %s", unicom.MaskPhone(a.phone)) } a.mu.Unlock() } func (a *App) logout(w http.ResponseWriter, r *http.Request) { a.client.Reset() a.mu.Lock() a.loggedIn = false a.phone = "" a.snap = unicom.Snapshot{} a.lastError = "" a.refreshed = time.Time{} a.nextAt = time.Time{} a.epoch++ a.mu.Unlock() writeJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (a *App) manualRefresh(w http.ResponseWriter, r *http.Request) { a.mu.Lock() ok := a.loggedIn a.mu.Unlock() if !ok { writeErr(w, "请先登录") return } a.refresh() writeJSON(w, http.StatusOK, a.view()) } func (a *App) setInterval(w http.ResponseWriter, r *http.Request) { var req struct { PollMinutes int `json:"pollMinutes"` JitterMinutes int `json:"jitterMinutes"` } if err := decode(r, &req); err != nil { writeErr(w, "请求无法识别") return } if req.PollMinutes < 1 { req.PollMinutes = 1 } if req.PollMinutes > 24*60 { req.PollMinutes = 24 * 60 } if req.JitterMinutes < 0 { req.JitterMinutes = 0 } if req.JitterMinutes > 24*60 { req.JitterMinutes = 24 * 60 } a.mu.Lock() a.interval = time.Duration(req.PollMinutes) * time.Minute a.jitter = time.Duration(req.JitterMinutes) * time.Minute if a.loggedIn { a.nextAt = time.Now().Add(a.wait()) } a.mu.Unlock() _ = a.save() writeJSON(w, http.StatusOK, a.view()) } func (a *App) loop(ctx context.Context) { ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: a.mu.Lock() due := a.loggedIn && !a.refreshing && !a.nextAt.IsZero() && !time.Now().Before(a.nextAt) a.mu.Unlock() if due { a.refresh() } } } } func (a *App) refresh() { a.mu.Lock() if !a.loggedIn || a.refreshing { a.mu.Unlock() return } a.refreshing = true phone := a.phone a.mu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second) snap, err := a.client.Query(ctx, phone) cancel() a.mu.Lock() defer a.mu.Unlock() a.refreshing = false if !a.loggedIn { return } if err != nil { if errors.Is(err, unicom.ErrNeedLogin) { a.loggedIn = false a.phone = "" a.snap = unicom.Snapshot{} a.lastError = "会话已失效,请重新登录" a.epoch++ a.client.Reset() return } a.lastError = err.Error() if snap.Balance != "" || len(snap.Resources) > 0 { a.snap = snap a.refreshed = time.Now() } } else { a.snap = snap a.lastError = "" a.refreshed = time.Now() if a.phone == "" && snap.Phone != "" { a.phone = snap.Phone } } a.nextAt = time.Now().Add(a.wait()) } func (a *App) wait() time.Duration { d := a.interval if a.jitter > 0 { d += time.Duration(rand.Int64N(int64(a.jitter))) } if d < time.Second { d = time.Second } return d } func (a *App) view() overview { a.mu.Lock() defer a.mu.Unlock() script, appID := a.client.Captcha() left := 0 if a.loggedIn && !a.nextAt.IsZero() { left = int(time.Until(a.nextAt).Seconds()) if left < 0 { left = 0 } } out := overview{ LoggedIn: a.loggedIn, NeedLogin: !a.loggedIn, Refreshing: a.refreshing, PollEvery: a.interval.String(), PollMinutes: int(a.interval / time.Minute), JitterMinutes: int(a.jitter / time.Minute), SecondsLeft: left, Error: a.lastError, HasData: a.snap.Balance != "" || len(a.snap.Resources) > 0, LoginEpoch: a.epoch, CaptchaScript: script, CaptchaAppID: appID, PhonePrefill: a.cfgPhone, Snapshot: a.snap, } if !a.refreshed.IsZero() { out.RefreshedAt = a.refreshed.Format("2006-01-02 15:04:05") } return out } func (a *App) load() { b, err := os.ReadFile(statePath) if err != nil { return } var saved savedState if json.Unmarshal(b, &saved) != nil { return } if saved.PollMinutes >= 1 { a.interval = time.Duration(saved.PollMinutes) * time.Minute } if saved.JitterMinutes >= 0 { a.jitter = time.Duration(saved.JitterMinutes) * time.Minute } } func (a *App) save() error { a.mu.Lock() saved := savedState{ PollMinutes: int(a.interval / time.Minute), JitterMinutes: int(a.jitter / time.Minute), } a.mu.Unlock() if err := os.MkdirAll(filepath.Dir(statePath), 0700); err != nil { return err } b, err := json.MarshalIndent(saved, "", " ") if err != nil { return err } tmp := statePath + ".tmp" if err := os.WriteFile(tmp, b, 0600); err != nil { return err } return os.Rename(tmp, statePath) } func loadConfig() Config { cfg := Config{Listen: ":8786", PollInterval: "30m"} if b, err := os.ReadFile("config.json"); err == nil { _ = json.Unmarshal(b, &cfg) } if v := os.Getenv("CU_LISTEN"); v != "" { cfg.Listen = v } if v := os.Getenv("CU_POLL"); v != "" { cfg.PollInterval = v } if v := os.Getenv("CU_JITTER"); v != "" { if n, err := strconv.Atoi(v); err == nil { cfg.JitterMinutes = n } } if v := os.Getenv("CU_PHONE"); v != "" { cfg.Phone = v } if cfg.Listen == "" { cfg.Listen = ":8786" } return cfg } func decode(r *http.Request, dest any) error { defer r.Body.Close() return json.NewDecoder(io.LimitReader(r.Body, 1<<16)).Decode(dest) } func writeJSON(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Cache-Control", "no-store") w.WriteHeader(code) enc := json.NewEncoder(w) enc.SetEscapeHTML(false) _ = enc.Encode(v) } func writeErr(w http.ResponseWriter, msg string) { writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "message": msg}) } func validPhone(s string) bool { if len(s) != 11 || s[0] != '1' { return false } for _, c := range s { if c < '0' || c > '9' { return false } } return true }