package main import ( "context" _ "embed" "encoding/json" "errors" "fmt" "io" "log" "net/http" "os" "os/signal" "path/filepath" "strings" "sync" "syscall" "time" _ "time/tzdata" "cbnsmsinfo/internal/cbn" ) //go:embed web/index.html var indexPage []byte const statePath = "data/state.json" type Config struct { Listen string `json:"listen"` PollInterval string `json:"pollInterval"` Phone string `json:"phone"` } type savedState struct { Phone string `json:"phone"` SessionID string `json:"sessionId"` Prov string `json:"prov"` City string `json:"city"` LoggedIn bool `json:"loggedIn"` Cookies []cbn.Cookie `json:"cookies"` Snapshot cbn.Snapshot `json:"snapshot"` RefreshedAt time.Time `json:"refreshedAt"` LastError string `json:"lastError"` Stale bool `json:"stale"` PollMinutes int `json:"pollMinutes"` } type overview struct { LoggedIn bool `json:"loggedIn"` NeedLogin bool `json:"needLogin"` CanResume bool `json:"canResume"` Refreshing bool `json:"refreshing"` PollEvery string `json:"pollEvery"` PollMinutes int `json:"pollMinutes"` SecondsLeft int `json:"secondsLeft"` RefreshedAt string `json:"refreshedAt,omitempty"` NextRefreshAt string `json:"nextRefreshAt,omitempty"` Error string `json:"error,omitempty"` Stale bool `json:"stale"` HasData bool `json:"hasData"` cbn.Snapshot } type App struct { client *cbn.Client interval time.Duration pollText string cfgPhone string kick chan struct{} mu sync.Mutex phone string sessionID string prov string city string loggedIn bool snap cbn.Snapshot refreshedAt time.Time nextAt time.Time lastError string stale bool refreshing bool } func main() { log.SetFlags(log.LstdFlags) cfg := loadConfig() interval, err := time.ParseDuration(cfg.PollInterval) if err != nil || interval < time.Minute { log.Printf("轮询间隔无效,已改用 30 分钟") interval = 30 * time.Minute } app := newApp(cbn.New(), strings.TrimSpace(cfg.Phone), interval) app.load() prepCtx, prepCancel := context.WithTimeout(context.Background(), 45*time.Second) if err := app.client.Prepare(prepCtx); err != nil { log.Printf("页面参数暂未就绪,登录时会再试: %v", err) } prepCancel() ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() go app.loop(ctx) mux := http.NewServeMux() mux.HandleFunc("GET /{$}", app.page) mux.HandleFunc("GET /api/overview", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, app.view()) }) mux.HandleFunc("POST /api/refresh", app.manualRefresh) mux.HandleFunc("GET /api/captcha", app.captcha) mux.HandleFunc("POST /api/sms", app.sms) mux.HandleFunc("POST /api/login", app.login) mux.HandleFunc("POST /api/logout", app.logout) mux.HandleFunc("POST /api/resume", app.resume) 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("已启动,浏览器打开 %s", listenURL(cfg.Listen)) if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatal(err) } } func newApp(client *cbn.Client, phone string, interval time.Duration) *App { return &App{ client: client, interval: interval, pollText: humanInterval(interval), cfgPhone: phone, kick: make(chan struct{}, 1), snap: cbn.Snapshot{ Resources: []cbn.Resource{}, Extras: []cbn.Extra{}, Bills: []cbn.Bill{}, }, } } func (a *App) loop(ctx context.Context) { timer := time.NewTimer(a.currentInterval()) stopTimer(timer) if a.isLoggedIn() { a.stampNext() a.refresh() timer.Reset(a.currentInterval()) } defer timer.Stop() for { select { case <-ctx.Done(): return case <-a.kick: stopTimer(timer) if a.isLoggedIn() { timer.Reset(a.currentInterval()) } case <-timer.C: if !a.isLoggedIn() { continue } a.stampNext() a.refresh() if a.isLoggedIn() { timer.Reset(a.currentInterval()) } } } } func stopTimer(timer *time.Timer) { if !timer.Stop() { select { case <-timer.C: default: } } } func (a *App) wakeLoop() { select { case a.kick <- struct{}{}: default: } } func (a *App) refresh() { a.mu.Lock() if !a.loggedIn || a.sessionID == "" || a.phone == "" { a.mu.Unlock() return } if a.refreshing { a.mu.Unlock() return } a.refreshing = true phone, sid, prov, city := a.phone, a.sessionID, a.prov, a.city a.mu.Unlock() defer func() { a.mu.Lock() a.refreshing = false a.mu.Unlock() a.save() }() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() type call struct { name string path string raw *json.RawMessage } var balance, bill, resource, subscribe json.RawMessage calls := []call{ {"余额", cbn.PathBalance, &balance}, {"账单", cbn.PathBill, &bill}, {"余量", cbn.PathResource, &resource}, {"套餐", cbn.PathSubscribe, &subscribe}, } var errs []string for _, item := range calls { raw, err := a.client.Query(ctx, item.path, phone, sid) if errors.Is(err, cbn.ErrNeedLogin) { a.markLoggedOut("会话已失效,请重新登录") return } if err != nil { errs = append(errs, item.name+":"+err.Error()) continue } *item.raw = raw } a.mu.Lock() defer a.mu.Unlock() if len(errs) > 0 && hasData(a.snap) && balance == nil && bill == nil && resource == nil && subscribe == nil { a.stale = true a.lastError = strings.Join(errs, ";") return } if len(errs) > 0 && hasData(a.snap) { a.stale = true a.lastError = strings.Join(errs, ";") return } snap := cbn.BuildSnapshot(phone, prov, city, balance, bill, resource, subscribe) a.snap = snap a.stale = len(errs) > 0 a.lastError = strings.Join(errs, ";") if len(errs) == 0 { a.refreshedAt = time.Now() log.Printf("同步完成 %s", snap.PhoneMasked) } } func (a *App) markLoggedOut(msg string) { a.client.Reset() a.mu.Lock() a.loggedIn = false a.sessionID = "" a.snap = emptySnap() a.stale = false a.refreshedAt = time.Time{} a.lastError = msg a.nextAt = time.Time{} a.mu.Unlock() } func (a *App) page(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) } func (a *App) manualRefresh(w http.ResponseWriter, r *http.Request) { if a.isLoggedIn() { a.refresh() } writeJSON(w, http.StatusOK, a.view()) } func (a *App) captcha(w http.ResponseWriter, r *http.Request) { body, ctype, err := a.client.Captcha(r.Context()) if err != nil { writeJSON(w, http.StatusBadGateway, map[string]any{"ok": false, "message": err.Error()}) return } a.save() w.Header().Set("Content-Type", ctype) w.Header().Set("Cache-Control", "no-store") _, _ = w.Write(body) } func (a *App) sms(w http.ResponseWriter, r *http.Request) { var req struct { Phone string `json:"phone"` } if err := decode(r, &req); err != nil { writeErr(w, "请求格式不对") return } phone := strings.TrimSpace(req.Phone) if !validPhone(phone) { writeErr(w, "请输入正确的手机号码") return } a.mu.Lock() a.phone = phone a.mu.Unlock() msg, err := a.client.SendSMS(r.Context(), phone) if err != nil { writeErr(w, cleanErr(err)) return } a.save() 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"` ImageCode string `json:"imageCode"` SMSCode string `json:"smsCode"` } if err := decode(r, &req); err != nil { writeErr(w, "请求格式不对") return } phone := strings.TrimSpace(req.Phone) image := strings.TrimSpace(req.ImageCode) sms := strings.TrimSpace(req.SMSCode) if !validPhone(phone) { writeErr(w, "请输入正确的手机号码") return } if image == "" { writeErr(w, "请输入图形验证码") return } if sms == "" { writeErr(w, "请输入短信验证码") return } result, err := a.client.Login(r.Context(), phone, image, sms) if err != nil { writeErr(w, cleanErr(err)) return } a.mu.Lock() a.loggedIn = true a.sessionID = result.SessionID a.phone = result.Phone a.prov = result.Prov a.city = result.City a.lastError = "" a.stale = false a.mu.Unlock() a.stampNext() a.wakeLoop() a.save() a.refresh() log.Printf("登录成功 %s", cbn.MaskPhone(result.Phone)) writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "登录成功"}) } func (a *App) logout(w http.ResponseWriter, r *http.Request) { a.mu.Lock() a.loggedIn = false a.lastError = "" a.nextAt = time.Time{} a.mu.Unlock() a.wakeLoop() a.save() writeJSON(w, http.StatusOK, a.view()) } func (a *App) resume(w http.ResponseWriter, r *http.Request) { var req struct { Phone string `json:"phone"` } if err := decode(r, &req); err != nil { writeErr(w, "请求格式不对") return } phone := strings.TrimSpace(req.Phone) a.mu.Lock() same := a.sessionID != "" && a.phone != "" && a.phone == phone a.mu.Unlock() if !same { writeJSON(w, http.StatusOK, map[string]any{"ok": false, "needCode": true}) return } a.mu.Lock() a.loggedIn = true a.lastError = "" a.mu.Unlock() a.stampNext() a.wakeLoop() a.refresh() if !a.isLoggedIn() { writeJSON(w, http.StatusOK, map[string]any{"ok": false, "expired": true, "message": "会话已过期"}) return } writeJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (a *App) setInterval(w http.ResponseWriter, r *http.Request) { var req struct { Minutes int `json:"minutes"` } if err := decode(r, &req); err != nil || req.Minutes < 1 || req.Minutes > 1440 { writeErr(w, "间隔需在 1 到 1440 分钟之间") return } a.mu.Lock() a.interval = time.Duration(req.Minutes) * time.Minute a.pollText = humanInterval(a.interval) if a.loggedIn { a.nextAt = time.Now().Add(a.interval) } a.mu.Unlock() select { case a.kick <- struct{}{}: default: } a.save() writeJSON(w, http.StatusOK, a.view()) } func (a *App) currentInterval() time.Duration { a.mu.Lock() defer a.mu.Unlock() if a.interval < time.Minute { return 30 * time.Minute } return a.interval } func (a *App) view() overview { a.mu.Lock() defer a.mu.Unlock() snap := a.snap if snap.Resources == nil { snap.Resources = []cbn.Resource{} } if snap.Extras == nil { snap.Extras = []cbn.Extra{} } if snap.Bills == nil { snap.Bills = []cbn.Bill{} } if len(snap.Resources) > 0 || len(snap.Extras) > 0 { snap.DataTotal, snap.DataUsed, snap.DataRemain, snap.DataExtra = cbn.SummarizeTraffic(snap.Resources, snap.Extras) snap.VoiceTotal, snap.VoiceRemain = cbn.SummarizeVoice(snap.Resources) } if !a.loggedIn { phone := a.phone snap = emptySnap() snap.Phone = phone snap.PhoneMasked = cbn.MaskPhone(phone) } out := overview{ LoggedIn: a.loggedIn, NeedLogin: !a.loggedIn, CanResume: !a.loggedIn && a.sessionID != "" && a.phone != "", Refreshing: a.refreshing, PollEvery: a.pollText, PollMinutes: int(a.interval / time.Minute), Error: a.lastError, Stale: a.loggedIn && a.stale, HasData: a.loggedIn && hasData(snap), Snapshot: snap, } if a.loggedIn && !a.refreshedAt.IsZero() { out.RefreshedAt = a.refreshedAt.In(shanghai()).Format("2006-01-02 15:04") } if a.loggedIn && !a.nextAt.IsZero() { left := time.Until(a.nextAt) if left < 0 { left = 0 } out.SecondsLeft = int(left.Round(time.Second) / time.Second) out.NextRefreshAt = a.nextAt.In(shanghai()).Format("15:04:05") } return out } func emptySnap() cbn.Snapshot { return cbn.Snapshot{ Resources: []cbn.Resource{}, Extras: []cbn.Extra{}, Bills: []cbn.Bill{}, } } func (a *App) load() { b, err := os.ReadFile(statePath) if err != nil { a.phone = a.cfgPhone return } var st savedState if json.Unmarshal(b, &st) != nil { a.phone = a.cfgPhone return } a.phone = strings.TrimSpace(st.Phone) if a.phone == "" { a.phone = a.cfgPhone } a.sessionID = st.SessionID a.prov = st.Prov a.city = st.City a.loggedIn = st.LoggedIn && st.SessionID != "" a.snap = st.Snapshot a.refreshedAt = st.RefreshedAt a.lastError = st.LastError a.stale = st.Stale if st.PollMinutes >= 1 && st.PollMinutes <= 1440 { a.interval = time.Duration(st.PollMinutes) * time.Minute a.pollText = humanInterval(a.interval) } a.client.ImportCookies(st.Cookies) if a.loggedIn { log.Printf("已恢复会话 %s", cbn.MaskPhone(a.phone)) } } func (a *App) save() { a.mu.Lock() st := savedState{ Phone: a.phone, SessionID: a.sessionID, Prov: a.prov, City: a.city, LoggedIn: a.loggedIn, Snapshot: a.snap, RefreshedAt: a.refreshedAt, LastError: a.lastError, Stale: a.stale, PollMinutes: int(a.interval / time.Minute), } a.mu.Unlock() st.Cookies = a.client.ExportCookies() buf, err := json.MarshalIndent(st, "", " ") if err != nil { log.Printf("保存会话失败: %v", err) return } if err := writeFileAtomic(statePath, buf); err != nil { log.Printf("保存会话失败: %v", err) } } func (a *App) isLoggedIn() bool { a.mu.Lock() defer a.mu.Unlock() return a.loggedIn } func (a *App) stampNext() { a.mu.Lock() a.nextAt = time.Now().Add(a.interval) a.mu.Unlock() } func hasData(s cbn.Snapshot) bool { return s.Balance != "" || s.PackageName != "" || s.MonthFee != "" || len(s.Resources) > 0 || len(s.Bills) > 0 } func loadConfig() Config { cfg := Config{Listen: ":8787", PollInterval: "30m"} b, err := os.ReadFile("config.json") if err != nil { if os.IsNotExist(err) { buf, _ := json.MarshalIndent(cfg, "", " ") buf = append(buf, '\n') if werr := os.WriteFile("config.json", buf, 0644); werr != nil { log.Printf("未写入 config.json: %v", werr) } } } else if json.Unmarshal(b, &cfg) != nil { cfg = Config{Listen: ":8787", PollInterval: "30m"} } if strings.TrimSpace(cfg.Listen) == "" { cfg.Listen = ":8787" } if strings.TrimSpace(cfg.PollInterval) == "" { cfg.PollInterval = "30m" } if v := strings.TrimSpace(os.Getenv("CBN_LISTEN")); v != "" { cfg.Listen = v } if v := strings.TrimSpace(os.Getenv("CBN_POLL")); v != "" { cfg.PollInterval = v } if v := strings.TrimSpace(os.Getenv("CBN_PHONE")); v != "" { cfg.Phone = v } return cfg } func writeFileAtomic(path string, b []byte) error { if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { return err } tmp := path + ".tmp" if err := os.WriteFile(tmp, b, 0600); err != nil { return err } return os.Rename(tmp, path) } 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 cleanErr(err error) string { if err == nil { return "请求失败" } msg := err.Error() if msg == "" { return "请求失败" } return 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 } func humanInterval(d time.Duration) string { if d >= time.Hour && d%time.Hour == 0 { return fmt.Sprintf("%d 小时", int(d.Hours())) } if d >= time.Minute && d%time.Minute == 0 { return fmt.Sprintf("%d 分钟", int(d.Minutes())) } return d.String() } func listenURL(addr string) string { if strings.HasPrefix(addr, ":") { return "http://127.0.0.1" + addr } return "http://" + addr } func shanghai() *time.Location { loc, err := time.LoadLocation("Asia/Shanghai") if err != nil { return time.FixedZone("CST", 8*3600) } return loc }