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
+98 -48
View File
@@ -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
}