feat: 刷新间隔增加随机分钟并使用广电图标

This commit is contained in:
2026-10-13 10:37:21 +08:00
parent 24cffd7c56
commit 0255067c77
5 changed files with 129 additions and 58 deletions
+5 -3
View File
@@ -12,6 +12,7 @@
{ {
"listen": ":8787", "listen": ":8787",
"pollInterval": "30m", "pollInterval": "30m",
"jitterMinutes": 0,
"phone": "" "phone": ""
} }
``` ```
@@ -19,12 +20,13 @@
| 字段 | 作用 | | 字段 | 作用 |
| --- | --- | | --- | --- |
| `listen` | 监听地址,默认 `:8787` | | `listen` | 监听地址,默认 `:8787` |
| `pollInterval` | 登录后的刷新间隔,最短 1 分钟,例如 `30m`、`1h` | | `pollInterval` | 登录后的基础刷新间隔,最短 1 分钟,例如 `30m`、`1h` |
| `jitterMinutes` | 每次额外随机增加的上限,0 到这个分钟数。0 表示不加 |
| `phone` | 可选。写上后登录页会预先填好号码 | | `phone` | 可选。写上后登录页会预先填好号码 |
环境变量 `CBN_LISTEN`、`CBN_POLL`、`CBN_PHONE` 会覆盖同名字段。 环境变量 `CBN_LISTEN`、`CBN_POLL`、`CBN_JITTER`、`CBN_PHONE` 会覆盖同名字段。`CBN_JITTER` 用和 `CBN_POLL` 一样的时长写法,例如 `10m`。
登录页输入号码。如果这个号码上次的会话还在,点登录会直接进入主页并开始倒计时。会话失效后才出现图形验证码和短信验证码。主页右上角「更多」里可以改刷新间隔、立刻刷新,或退出。退出只回到登录页,不向运营商注销,也不再自动刷新,让会话自己过期。运营商判定会话失效后,页面会回到登录页并提示重新登录。 登录页输入号码。如果这个号码上次的会话还在,点登录会直接进入主页并开始倒计时。会话失效后才出现图形验证码和短信验证码。主页右上角菜单里可以改刷新间隔和随机分钟、立刻刷新,或退出。退出只回到登录页,不向运营商注销,也不再自动刷新,让会话自己过期。运营商判定会话失效后,页面会回到登录页并提示重新登录。
会话、Cookie 和站点参数写在程序目录的 `data/`。不要把这个目录交给别人。 会话、Cookie 和站点参数写在程序目录的 `data/`。不要把这个目录交给别人。
+1
View File
@@ -1,5 +1,6 @@
{ {
"listen": ":8787", "listen": ":8787",
"pollInterval": "30m", "pollInterval": "30m",
"jitterMinutes": 0,
"phone": "" "phone": ""
} }
+98 -48
View File
@@ -8,6 +8,7 @@ import (
"fmt" "fmt"
"io" "io"
"log" "log"
"math/rand/v2"
"net/http" "net/http"
"os" "os"
"os/signal" "os/signal"
@@ -24,26 +25,31 @@ import (
//go:embed web/index.html //go:embed web/index.html
var indexPage []byte var indexPage []byte
//go:embed web/favicon.ico
var favicon []byte
const statePath = "data/state.json" const statePath = "data/state.json"
type Config struct { type Config struct {
Listen string `json:"listen"` Listen string `json:"listen"`
PollInterval string `json:"pollInterval"` PollInterval string `json:"pollInterval"`
Phone string `json:"phone"` JitterMinutes int `json:"jitterMinutes"`
Phone string `json:"phone"`
} }
type savedState struct { type savedState struct {
Phone string `json:"phone"` Phone string `json:"phone"`
SessionID string `json:"sessionId"` SessionID string `json:"sessionId"`
Prov string `json:"prov"` Prov string `json:"prov"`
City string `json:"city"` City string `json:"city"`
LoggedIn bool `json:"loggedIn"` LoggedIn bool `json:"loggedIn"`
Cookies []cbn.Cookie `json:"cookies"` Cookies []cbn.Cookie `json:"cookies"`
Snapshot cbn.Snapshot `json:"snapshot"` Snapshot cbn.Snapshot `json:"snapshot"`
RefreshedAt time.Time `json:"refreshedAt"` RefreshedAt time.Time `json:"refreshedAt"`
LastError string `json:"lastError"` LastError string `json:"lastError"`
Stale bool `json:"stale"` Stale bool `json:"stale"`
PollMinutes int `json:"pollMinutes"` PollMinutes int `json:"pollMinutes"`
JitterMinutes int `json:"jitterMinutes"`
} }
type overview struct { type overview struct {
@@ -53,6 +59,7 @@ type overview struct {
Refreshing bool `json:"refreshing"` Refreshing bool `json:"refreshing"`
PollEvery string `json:"pollEvery"` PollEvery string `json:"pollEvery"`
PollMinutes int `json:"pollMinutes"` PollMinutes int `json:"pollMinutes"`
JitterMinutes int `json:"jitterMinutes"`
SecondsLeft int `json:"secondsLeft"` SecondsLeft int `json:"secondsLeft"`
RefreshedAt string `json:"refreshedAt,omitempty"` RefreshedAt string `json:"refreshedAt,omitempty"`
NextRefreshAt string `json:"nextRefreshAt,omitempty"` NextRefreshAt string `json:"nextRefreshAt,omitempty"`
@@ -65,6 +72,7 @@ type overview struct {
type App struct { type App struct {
client *cbn.Client client *cbn.Client
interval time.Duration interval time.Duration
jitter time.Duration
pollText string pollText string
cfgPhone string cfgPhone string
kick chan struct{} kick chan struct{}
@@ -91,7 +99,11 @@ func main() {
log.Printf("轮询间隔无效,已改用 30 分钟") log.Printf("轮询间隔无效,已改用 30 分钟")
interval = 30 * time.Minute 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() app.load()
prepCtx, prepCancel := context.WithTimeout(context.Background(), 45*time.Second) prepCtx, prepCancel := context.WithTimeout(context.Background(), 45*time.Second)
if err := app.client.Prepare(prepCtx); err != nil { if err := app.client.Prepare(prepCtx); err != nil {
@@ -105,6 +117,11 @@ func main() {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", app.page) 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) { mux.HandleFunc("GET /api/overview", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, app.view()) 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{ return &App{
client: client, client: client,
interval: interval, interval: interval,
jitter: jitter,
pollText: humanInterval(interval), pollText: humanInterval(interval),
cfgPhone: phone, cfgPhone: phone,
kick: make(chan struct{}, 1), 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) { func (a *App) loop(ctx context.Context) {
timer := time.NewTimer(a.currentInterval()) timer := time.NewTimer(time.Hour)
stopTimer(timer) stopTimer(timer)
if a.isLoggedIn() { if a.isLoggedIn() {
a.stampNext() a.stampNext()
timer.Reset(a.untilNext())
a.refresh() a.refresh()
timer.Reset(a.currentInterval())
} }
defer timer.Stop() defer timer.Stop()
for { for {
@@ -164,17 +182,15 @@ func (a *App) loop(ctx context.Context) {
case <-a.kick: case <-a.kick:
stopTimer(timer) stopTimer(timer)
if a.isLoggedIn() { if a.isLoggedIn() {
timer.Reset(a.currentInterval()) timer.Reset(a.untilNext())
} }
case <-timer.C: case <-timer.C:
if !a.isLoggedIn() { if !a.isLoggedIn() {
continue continue
} }
a.stampNext() a.stampNext()
timer.Reset(a.untilNext())
a.refresh() 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) { func (a *App) setInterval(w http.ResponseWriter, r *http.Request) {
var req struct { var req struct {
Minutes int `json:"minutes"` Minutes int `json:"minutes"`
Jitter int `json:"jitter"`
} }
if err := decode(r, &req); err != nil || req.Minutes < 1 || req.Minutes > 1440 { if err := decode(r, &req); err != nil || req.Minutes < 1 || req.Minutes > 1440 {
writeErr(w, "间隔需在 1 到 1440 分钟之间") writeErr(w, "间隔需在 1 到 1440 分钟之间")
return return
} }
if req.Jitter < 0 || req.Jitter > 1440 {
writeErr(w, "随机需在 0 到 1440 分钟之间")
return
}
a.mu.Lock() a.mu.Lock()
a.interval = time.Duration(req.Minutes) * time.Minute a.interval = time.Duration(req.Minutes) * time.Minute
a.jitter = time.Duration(req.Jitter) * time.Minute
a.pollText = humanInterval(a.interval) a.pollText = humanInterval(a.interval)
if a.loggedIn { if a.loggedIn {
a.nextAt = time.Now().Add(a.interval) a.stampNextLocked()
} }
a.mu.Unlock() a.mu.Unlock()
select { select {
@@ -446,13 +468,15 @@ func (a *App) setInterval(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, a.view()) writeJSON(w, http.StatusOK, a.view())
} }
func (a *App) currentInterval() time.Duration { func (a *App) untilNext() time.Duration {
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if a.interval < time.Minute { if !a.nextAt.IsZero() {
return 30 * time.Minute if d := time.Until(a.nextAt); d > 0 {
return d
}
} }
return a.interval return time.Second
} }
func (a *App) view() overview { func (a *App) view() overview {
@@ -479,16 +503,17 @@ func (a *App) view() overview {
snap.PhoneMasked = cbn.MaskPhone(phone) snap.PhoneMasked = cbn.MaskPhone(phone)
} }
out := overview{ out := overview{
LoggedIn: a.loggedIn, LoggedIn: a.loggedIn,
NeedLogin: !a.loggedIn, NeedLogin: !a.loggedIn,
CanResume: !a.loggedIn && a.sessionID != "" && a.phone != "", CanResume: !a.loggedIn && a.sessionID != "" && a.phone != "",
Refreshing: a.refreshing, Refreshing: a.refreshing,
PollEvery: a.pollText, PollEvery: a.pollText,
PollMinutes: int(a.interval / time.Minute), PollMinutes: int(a.interval / time.Minute),
Error: a.lastError, JitterMinutes: int(a.jitter / time.Minute),
Stale: a.loggedIn && a.stale, Error: a.lastError,
HasData: a.loggedIn && hasData(snap), Stale: a.loggedIn && a.stale,
Snapshot: snap, HasData: a.loggedIn && hasData(snap),
Snapshot: snap,
} }
if a.loggedIn && !a.refreshedAt.IsZero() { if a.loggedIn && !a.refreshedAt.IsZero() {
out.RefreshedAt = a.refreshedAt.In(shanghai()).Format("2006-01-02 15:04") 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.interval = time.Duration(st.PollMinutes) * time.Minute
a.pollText = humanInterval(a.interval) 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) a.client.ImportCookies(st.Cookies)
if a.loggedIn { if a.loggedIn {
log.Printf("已恢复会话 %s", cbn.MaskPhone(a.phone)) log.Printf("已恢复会话 %s", cbn.MaskPhone(a.phone))
@@ -548,16 +576,17 @@ func (a *App) load() {
func (a *App) save() { func (a *App) save() {
a.mu.Lock() a.mu.Lock()
st := savedState{ st := savedState{
Phone: a.phone, Phone: a.phone,
SessionID: a.sessionID, SessionID: a.sessionID,
Prov: a.prov, Prov: a.prov,
City: a.city, City: a.city,
LoggedIn: a.loggedIn, LoggedIn: a.loggedIn,
Snapshot: a.snap, Snapshot: a.snap,
RefreshedAt: a.refreshedAt, RefreshedAt: a.refreshedAt,
LastError: a.lastError, LastError: a.lastError,
Stale: a.stale, Stale: a.stale,
PollMinutes: int(a.interval / time.Minute), PollMinutes: int(a.interval / time.Minute),
JitterMinutes: int(a.jitter / time.Minute),
} }
a.mu.Unlock() a.mu.Unlock()
st.Cookies = a.client.ExportCookies() st.Cookies = a.client.ExportCookies()
@@ -579,10 +608,26 @@ func (a *App) isLoggedIn() bool {
func (a *App) stampNext() { func (a *App) stampNext() {
a.mu.Lock() a.mu.Lock()
a.nextAt = time.Now().Add(a.interval) a.stampNextLocked()
a.mu.Unlock() 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 { func hasData(s cbn.Snapshot) bool {
return s.Balance != "" || s.PackageName != "" || s.MonthFee != "" || len(s.Resources) > 0 || len(s.Bills) > 0 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 != "" { if v := strings.TrimSpace(os.Getenv("CBN_POLL")); v != "" {
cfg.PollInterval = 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 != "" { if v := strings.TrimSpace(os.Getenv("CBN_PHONE")); v != "" {
cfg.Phone = v cfg.Phone = v
} }
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

+25 -7
View File
@@ -4,6 +4,7 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>广电账户</title> <title>广电账户</title>
<link rel="icon" href="/favicon.ico">
<style> <style>
:root { :root {
--bg: #eef1f6; --bg: #eef1f6;
@@ -202,6 +203,7 @@
#smsBtn { flex: none; height: 32px; padding: 0 8px; } #smsBtn { flex: none; height: 32px; padding: 0 8px; }
#loginMsg { min-height: 18px; margin: 8px 0 0; font-size: 12px; color: var(--danger); } #loginMsg { min-height: 18px; margin: 8px 0 0; font-size: 12px; color: var(--danger); }
#loginMsg.ok { color: var(--ok); } #loginMsg.ok { color: var(--ok); }
.unit { flex: none; color: var(--muted); font-size: 12px; }
.hero { display: grid; grid-template-columns: 220px 1fr; overflow: hidden; margin-bottom: 10px; } .hero { display: grid; grid-template-columns: 220px 1fr; overflow: hidden; margin-bottom: 10px; }
.identity { padding: 16px 18px; background: #173a6b; color: #fff; } .identity { padding: 16px 18px; background: #173a6b; color: #fff; }
.brand { font-size: 12px; letter-spacing: 0.06em; opacity: 0.85; } .brand { font-size: 12px; letter-spacing: 0.06em; opacity: 0.85; }
@@ -394,9 +396,19 @@
<div id="settings" class="mask" hidden> <div id="settings" class="mask" hidden>
<div class="dialog card" role="dialog" aria-labelledby="settingsTitle"> <div class="dialog card" role="dialog" aria-labelledby="settingsTitle">
<h2 id="settingsTitle">同步间隔</h2> <h2 id="settingsTitle">同步间隔</h2>
<div class="field"> <div class="login-row">
<label for="pollMinutes">分钟</label> <label for="pollMinutes">间隔</label>
<input id="pollMinutes" type="number" min="1" max="1440" inputmode="numeric" value="30"> <div class="control">
<input id="pollMinutes" type="number" min="1" max="1440" inputmode="numeric" value="30">
<span class="unit">分钟</span>
</div>
</div>
<div class="login-row">
<label for="jitterMinutes">随机</label>
<div class="control">
<input id="jitterMinutes" type="number" min="0" max="1440" inputmode="numeric" value="0">
<span class="unit">分钟</span>
</div>
</div> </div>
<p id="settingsMsg"></p> <p id="settingsMsg"></p>
<div class="dialog-actions"> <div class="dialog-actions">
@@ -455,8 +467,9 @@
$("dash").classList.toggle("stale", !!(data.stale && data.hasData && !data.loggedIn)); $("dash").classList.toggle("stale", !!(data.stale && data.hasData && !data.loggedIn));
$("error").hidden = !data.error; $("error").hidden = !data.error;
$("error").textContent = data.error || ""; $("error").textContent = data.error || "";
if ($("settings").hidden && data.pollMinutes) { if ($("settings").hidden) {
$("pollMinutes").value = data.pollMinutes; if (data.pollMinutes) $("pollMinutes").value = data.pollMinutes;
if (Number.isInteger(data.jitterMinutes)) $("jitterMinutes").value = data.jitterMinutes;
} }
canResume = !!data.canResume; canResume = !!data.canResume;
@@ -573,14 +586,19 @@
async function saveInterval() { async function saveInterval() {
const minutes = Number($("pollMinutes").value); const minutes = Number($("pollMinutes").value);
const jitter = Number($("jitterMinutes").value);
if (!Number.isInteger(minutes) || minutes < 1 || minutes > 1440) { if (!Number.isInteger(minutes) || minutes < 1 || minutes > 1440) {
$("settingsMsg").textContent = "需在 1 到 1440 之间"; $("settingsMsg").textContent = "间隔需在 1 到 1440 之间";
return;
}
if (!Number.isInteger(jitter) || jitter < 0 || jitter > 1440) {
$("settingsMsg").textContent = "随机需在 0 到 1440 之间";
return; return;
} }
const res = await fetch("/api/interval", { const res = await fetch("/api/interval", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ minutes }) body: JSON.stringify({ minutes, jitter })
}); });
const data = await res.json(); const data = await res.json();
if (!res.ok) { if (!res.ok) {