diff --git a/README.md b/README.md index b8c977e..ed887f5 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ { "listen": ":8787", "pollInterval": "30m", + "jitterMinutes": 0, "phone": "" } ``` @@ -19,12 +20,13 @@ | 字段 | 作用 | | --- | --- | | `listen` | 监听地址,默认 `:8787` | -| `pollInterval` | 登录后的刷新间隔,最短 1 分钟,例如 `30m`、`1h` | +| `pollInterval` | 登录后的基础刷新间隔,最短 1 分钟,例如 `30m`、`1h` | +| `jitterMinutes` | 每次额外随机增加的上限,0 到这个分钟数。0 表示不加 | | `phone` | 可选。写上后登录页会预先填好号码 | -环境变量 `CBN_LISTEN`、`CBN_POLL`、`CBN_PHONE` 会覆盖同名字段。 +环境变量 `CBN_LISTEN`、`CBN_POLL`、`CBN_JITTER`、`CBN_PHONE` 会覆盖同名字段。`CBN_JITTER` 用和 `CBN_POLL` 一样的时长写法,例如 `10m`。 -登录页输入号码。如果这个号码上次的会话还在,点登录会直接进入主页并开始倒计时。会话失效后才出现图形验证码和短信验证码。主页右上角「更多」里可以改刷新间隔、立刻刷新,或退出。退出只回到登录页,不向运营商注销,也不再自动刷新,让会话自己过期。运营商判定会话失效后,页面会回到登录页并提示重新登录。 +登录页输入号码。如果这个号码上次的会话还在,点登录会直接进入主页并开始倒计时。会话失效后才出现图形验证码和短信验证码。主页右上角菜单里可以改刷新间隔和随机分钟、立刻刷新,或退出。退出只回到登录页,不向运营商注销,也不再自动刷新,让会话自己过期。运营商判定会话失效后,页面会回到登录页并提示重新登录。 会话、Cookie 和站点参数写在程序目录的 `data/`。不要把这个目录交给别人。 diff --git a/config.example.json b/config.example.json index c69ce2b..8a4ccf9 100644 --- a/config.example.json +++ b/config.example.json @@ -1,5 +1,6 @@ { "listen": ":8787", "pollInterval": "30m", + "jitterMinutes": 0, "phone": "" } diff --git a/main.go b/main.go index f4ab3ab..8d1fc0f 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "log" + "math/rand/v2" "net/http" "os" "os/signal" @@ -24,26 +25,31 @@ import ( //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"` - Phone string `json:"phone"` + Listen string `json:"listen"` + PollInterval string `json:"pollInterval"` + JitterMinutes int `json:"jitterMinutes"` + 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"` + 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"` + JitterMinutes int `json:"jitterMinutes"` } type overview struct { @@ -53,6 +59,7 @@ type overview struct { 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"` NextRefreshAt string `json:"nextRefreshAt,omitempty"` @@ -65,6 +72,7 @@ type overview struct { type App struct { client *cbn.Client interval time.Duration + jitter time.Duration pollText string cfgPhone string kick chan struct{} @@ -91,7 +99,11 @@ func main() { log.Printf("轮询间隔无效,已改用 30 分钟") interval = 30 * time.Minute } - app := newApp(cbn.New(), strings.TrimSpace(cfg.Phone), interval) + if cfg.JitterMinutes < 0 || cfg.JitterMinutes > 1440 { + log.Printf("随机分钟无效,已改用 0") + cfg.JitterMinutes = 0 + } + app := newApp(cbn.New(), strings.TrimSpace(cfg.Phone), interval, time.Duration(cfg.JitterMinutes)*time.Minute) app.load() prepCtx, prepCancel := context.WithTimeout(context.Background(), 45*time.Second) if err := app.client.Prepare(prepCtx); err != nil { @@ -105,6 +117,11 @@ func main() { mux := http.NewServeMux() mux.HandleFunc("GET /{$}", app.page) + 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()) }) @@ -133,10 +150,11 @@ func main() { } } -func newApp(client *cbn.Client, phone string, interval time.Duration) *App { +func newApp(client *cbn.Client, phone string, interval, jitter time.Duration) *App { return &App{ client: client, interval: interval, + jitter: jitter, pollText: humanInterval(interval), cfgPhone: phone, kick: make(chan struct{}, 1), @@ -149,12 +167,12 @@ func newApp(client *cbn.Client, phone string, interval time.Duration) *App { } func (a *App) loop(ctx context.Context) { - timer := time.NewTimer(a.currentInterval()) + timer := time.NewTimer(time.Hour) stopTimer(timer) if a.isLoggedIn() { a.stampNext() + timer.Reset(a.untilNext()) a.refresh() - timer.Reset(a.currentInterval()) } defer timer.Stop() for { @@ -164,17 +182,15 @@ func (a *App) loop(ctx context.Context) { case <-a.kick: stopTimer(timer) if a.isLoggedIn() { - timer.Reset(a.currentInterval()) + timer.Reset(a.untilNext()) } case <-timer.C: if !a.isLoggedIn() { continue } a.stampNext() + timer.Reset(a.untilNext()) a.refresh() - if a.isLoggedIn() { - timer.Reset(a.currentInterval()) - } } } } @@ -426,16 +442,22 @@ func (a *App) resume(w http.ResponseWriter, r *http.Request) { func (a *App) setInterval(w http.ResponseWriter, r *http.Request) { var req struct { Minutes int `json:"minutes"` + Jitter int `json:"jitter"` } if err := decode(r, &req); err != nil || req.Minutes < 1 || req.Minutes > 1440 { writeErr(w, "间隔需在 1 到 1440 分钟之间") return } + if req.Jitter < 0 || req.Jitter > 1440 { + writeErr(w, "随机需在 0 到 1440 分钟之间") + return + } a.mu.Lock() a.interval = time.Duration(req.Minutes) * time.Minute + a.jitter = time.Duration(req.Jitter) * time.Minute a.pollText = humanInterval(a.interval) if a.loggedIn { - a.nextAt = time.Now().Add(a.interval) + a.stampNextLocked() } a.mu.Unlock() select { @@ -446,13 +468,15 @@ func (a *App) setInterval(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, a.view()) } -func (a *App) currentInterval() time.Duration { +func (a *App) untilNext() time.Duration { a.mu.Lock() defer a.mu.Unlock() - if a.interval < time.Minute { - return 30 * time.Minute + if !a.nextAt.IsZero() { + if d := time.Until(a.nextAt); d > 0 { + return d + } } - return a.interval + return time.Second } func (a *App) view() overview { @@ -479,16 +503,17 @@ func (a *App) view() overview { 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, + 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), + JitterMinutes: int(a.jitter / 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") @@ -539,6 +564,9 @@ func (a *App) load() { a.interval = time.Duration(st.PollMinutes) * time.Minute a.pollText = humanInterval(a.interval) } + if st.JitterMinutes >= 0 && st.JitterMinutes <= 1440 { + a.jitter = time.Duration(st.JitterMinutes) * time.Minute + } a.client.ImportCookies(st.Cookies) if a.loggedIn { log.Printf("已恢复会话 %s", cbn.MaskPhone(a.phone)) @@ -548,16 +576,17 @@ func (a *App) load() { 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), + 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), + JitterMinutes: int(a.jitter / time.Minute), } a.mu.Unlock() st.Cookies = a.client.ExportCookies() @@ -579,10 +608,26 @@ func (a *App) isLoggedIn() bool { func (a *App) stampNext() { a.mu.Lock() - a.nextAt = time.Now().Add(a.interval) + a.stampNextLocked() a.mu.Unlock() } +func (a *App) stampNextLocked() { + a.nextAt = time.Now().Add(a.nextWaitLocked()) +} + +func (a *App) nextWaitLocked() time.Duration { + base := a.interval + if base < time.Minute { + base = 30 * time.Minute + } + maxMin := int(a.jitter / time.Minute) + if maxMin <= 0 { + return base + } + return base + time.Duration(rand.IntN(maxMin+1))*time.Minute +} + func hasData(s cbn.Snapshot) bool { return s.Balance != "" || s.PackageName != "" || s.MonthFee != "" || len(s.Resources) > 0 || len(s.Bills) > 0 } @@ -613,6 +658,11 @@ func loadConfig() Config { if v := strings.TrimSpace(os.Getenv("CBN_POLL")); v != "" { cfg.PollInterval = v } + if v := strings.TrimSpace(os.Getenv("CBN_JITTER")); v != "" { + if n, err := time.ParseDuration(v); err == nil { + cfg.JitterMinutes = int(n / time.Minute) + } + } if v := strings.TrimSpace(os.Getenv("CBN_PHONE")); v != "" { cfg.Phone = v } diff --git a/web/favicon.ico b/web/favicon.ico new file mode 100644 index 0000000..dd98c12 Binary files /dev/null and b/web/favicon.ico differ diff --git a/web/index.html b/web/index.html index 013a351..352d2f5 100644 --- a/web/index.html +++ b/web/index.html @@ -4,6 +4,7 @@ 广电账户 +