fix: 刷新改为后台执行并在部分失败时保留已有数据

This commit is contained in:
2026-10-15 11:07:29 +08:00
parent 0255067c77
commit efd21d3cf8
5 changed files with 80 additions and 53 deletions
+5 -3
View File
@@ -6,7 +6,7 @@
## 使用 ## 使用
在程序目录放 `config.json`,然后运行编译好的程序,浏览器打开它监听的地址。 程序从**当前工作目录**读取 `config.json` 并写入 `data/`,所以请先进入程序所在目录再启动,浏览器打开它监听的地址。
```json ```json
{ {
@@ -21,11 +21,13 @@
| --- | --- | | --- | --- |
| `listen` | 监听地址,默认 `:8787` | | `listen` | 监听地址,默认 `:8787` |
| `pollInterval` | 登录后的基础刷新间隔,最短 1 分钟,例如 `30m`、`1h` | | `pollInterval` | 登录后的基础刷新间隔,最短 1 分钟,例如 `30m`、`1h` |
| `jitterMinutes` | 每次额外随机增加的上限,0 到这个分钟数。0 表示不加 | | `jitterMinutes` | 每次额外随机增加 0 到这个分钟数之间的时间,精确到秒。0 表示不加 |
| `phone` | 可选。写上后登录页会预先填好号码 | | `phone` | 可选。写上后登录页会预先填好号码 |
环境变量 `CBN_LISTEN`、`CBN_POLL`、`CBN_JITTER`、`CBN_PHONE` 会覆盖同名字段。`CBN_JITTER` 用和 `CBN_POLL` 一样的时长写法,例如 `10m`。 环境变量 `CBN_LISTEN`、`CBN_POLL`、`CBN_JITTER`、`CBN_PHONE` 会覆盖同名字段。`CBN_JITTER` 用和 `CBN_POLL` 一样的时长写法,例如 `10m`。
`pollInterval` 和 `jitterMinutes` 只是首次运行的默认值。之后程序会把当前的间隔存进 `data/state.json`,并以它为准;要改间隔请在页面的设置里改,直接改 `config.json` 不会生效。
登录页输入号码。如果这个号码上次的会话还在,点登录会直接进入主页并开始倒计时。会话失效后才出现图形验证码和短信验证码。主页右上角菜单里可以改刷新间隔和随机分钟、立刻刷新,或退出。退出只回到登录页,不向运营商注销,也不再自动刷新,让会话自己过期。运营商判定会话失效后,页面会回到登录页并提示重新登录。 登录页输入号码。如果这个号码上次的会话还在,点登录会直接进入主页并开始倒计时。会话失效后才出现图形验证码和短信验证码。主页右上角菜单里可以改刷新间隔和随机分钟、立刻刷新,或退出。退出只回到登录页,不向运营商注销,也不再自动刷新,让会话自己过期。运营商判定会话失效后,页面会回到登录页并提示重新登录。
会话、Cookie 和站点参数写在程序目录的 `data/`。不要把这个目录交给别人。 会话、Cookie 和站点参数写在程序目录的 `data/`。不要把这个目录交给别人。
@@ -44,7 +46,7 @@ go build -trimpath -ldflags="-s -w" -o cbn-dashboard .
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o cbn-dashboard . CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o cbn-dashboard .
``` ```
把二进制和 `config.json` 放在同一目录运行。程序会在该目录创建 `data/`。 把二进制和 `config.json` 放在同一目录,在该目录下启动。
## 流程 ## 流程
+1 -1
View File
@@ -501,7 +501,7 @@ func parseBody(buf []byte, priv *rsa.PrivateKey) (*Result, error) {
if json.Unmarshal(raw, &s) == nil && s != "" { if json.Unmarshal(raw, &s) == nil && s != "" {
plain, err := decryptLong(priv, s) plain, err := decryptLong(priv, s)
if err != nil { if err != nil {
return nil, errors.New("无法解密网站响应") return nil, errDecrypt
} }
decoded, err := decodeURIComponent(plain) decoded, err := decodeURIComponent(plain)
if err != nil { if err != nil {
+1 -1
View File
@@ -16,7 +16,7 @@ import (
"strings" "strings"
) )
var errDecrypt = errors.New("无法用当前密钥解密") var errDecrypt = errors.New("无法解密网站响应")
func encryptLong(pub *rsa.PublicKey, plain string) (string, error) { func encryptLong(pub *rsa.PublicKey, plain string) (string, error) {
if pub == nil { if pub == nil {
+62 -43
View File
@@ -50,6 +50,8 @@ type savedState struct {
Stale bool `json:"stale"` Stale bool `json:"stale"`
PollMinutes int `json:"pollMinutes"` PollMinutes int `json:"pollMinutes"`
JitterMinutes int `json:"jitterMinutes"` JitterMinutes int `json:"jitterMinutes"`
Raw map[string]json.RawMessage `json:"raw,omitempty"`
} }
type overview struct { type overview struct {
@@ -76,8 +78,10 @@ type App struct {
pollText string pollText string
cfgPhone string cfgPhone string
kick chan struct{} kick chan struct{}
saveMu sync.Mutex
mu sync.Mutex mu sync.Mutex
raw map[string]json.RawMessage
phone string phone string
sessionID string sessionID string
prov string prov string
@@ -158,6 +162,7 @@ func newApp(client *cbn.Client, phone string, interval, jitter time.Duration) *A
pollText: humanInterval(interval), pollText: humanInterval(interval),
cfgPhone: phone, cfgPhone: phone,
kick: make(chan struct{}, 1), kick: make(chan struct{}, 1),
raw: map[string]json.RawMessage{},
snap: cbn.Snapshot{ snap: cbn.Snapshot{
Resources: []cbn.Resource{}, Resources: []cbn.Resource{},
Extras: []cbn.Extra{}, Extras: []cbn.Extra{},
@@ -172,7 +177,7 @@ func (a *App) loop(ctx context.Context) {
if a.isLoggedIn() { if a.isLoggedIn() {
a.stampNext() a.stampNext()
timer.Reset(a.untilNext()) timer.Reset(a.untilNext())
a.refresh() go a.refresh()
} }
defer timer.Stop() defer timer.Stop()
for { for {
@@ -190,7 +195,7 @@ func (a *App) loop(ctx context.Context) {
} }
a.stampNext() a.stampNext()
timer.Reset(a.untilNext()) timer.Reset(a.untilNext())
a.refresh() go a.refresh()
} }
} }
} }
@@ -211,89 +216,95 @@ func (a *App) wakeLoop() {
} }
} }
func (a *App) refresh() { // refresh 返回 false 表示已有一次刷新在进行,本次没有执行。
func (a *App) refresh() bool {
a.mu.Lock() a.mu.Lock()
if !a.loggedIn || a.sessionID == "" || a.phone == "" { if !a.loggedIn || a.sessionID == "" || a.phone == "" {
a.mu.Unlock() a.mu.Unlock()
return return true
} }
if a.refreshing { if a.refreshing {
a.mu.Unlock() a.mu.Unlock()
return return false
} }
a.refreshing = true a.refreshing = true
phone, sid, prov, city := a.phone, a.sessionID, a.prov, a.city phone, sid, prov, city := a.phone, a.sessionID, a.prov, a.city
a.mu.Unlock() a.mu.Unlock()
replaced := false
defer func() { defer func() {
a.mu.Lock() a.mu.Lock()
a.refreshing = false a.refreshing = false
a.mu.Unlock() a.mu.Unlock()
a.save() a.save()
if replaced {
go a.refresh()
}
}() }()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel() defer cancel()
type call struct { calls := []struct{ name, path string }{
name string {"余额", cbn.PathBalance},
path string {"账单", cbn.PathBill},
raw *json.RawMessage {"余量", cbn.PathResource},
} {"套餐", cbn.PathSubscribe},
var balance, bill, resource, subscribe json.RawMessage
calls := []call{
{"余额", cbn.PathBalance, &balance},
{"账单", cbn.PathBill, &bill},
{"余量", cbn.PathResource, &resource},
{"套餐", cbn.PathSubscribe, &subscribe},
} }
fresh := map[string]json.RawMessage{}
var errs []string var errs []string
for _, item := range calls { for _, item := range calls {
raw, err := a.client.Query(ctx, item.path, phone, sid) raw, err := a.client.Query(ctx, item.path, phone, sid)
if errors.Is(err, cbn.ErrNeedLogin) { if errors.Is(err, cbn.ErrNeedLogin) {
a.markLoggedOut("会话已失效,请重新登录") replaced = !a.markLoggedOut(sid, "会话已失效,请重新登录")
return return true
} }
if err != nil { if err != nil {
errs = append(errs, item.name+":"+err.Error()) errs = append(errs, item.name+":"+err.Error())
continue continue
} }
*item.raw = raw fresh[item.path] = raw
} }
a.mu.Lock() a.mu.Lock()
defer a.mu.Unlock() defer a.mu.Unlock()
if len(errs) > 0 && hasData(a.snap) && balance == nil && bill == nil && resource == nil && subscribe == nil { if a.sessionID != sid {
a.stale = true replaced = a.loggedIn
a.lastError = strings.Join(errs, ";") return true
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.stale = len(errs) > 0
a.lastError = strings.Join(errs, ";") a.lastError = strings.Join(errs, ";")
if len(fresh) == 0 {
return true
}
for k, v := range fresh {
a.raw[k] = v
}
a.snap = cbn.BuildSnapshot(phone, prov, city, a.raw[cbn.PathBalance], a.raw[cbn.PathBill], a.raw[cbn.PathResource], a.raw[cbn.PathSubscribe])
if len(errs) == 0 { if len(errs) == 0 {
a.refreshedAt = time.Now() a.refreshedAt = time.Now()
log.Printf("同步完成 %s", snap.PhoneMasked) log.Printf("同步完成 %s", a.snap.PhoneMasked)
} }
return true
} }
func (a *App) markLoggedOut(msg string) { func (a *App) markLoggedOut(sid, msg string) bool {
a.client.Reset()
a.mu.Lock() a.mu.Lock()
if a.sessionID != sid {
a.mu.Unlock()
return false
}
a.loggedIn = false a.loggedIn = false
a.sessionID = "" a.sessionID = ""
a.raw = map[string]json.RawMessage{}
a.snap = emptySnap() a.snap = emptySnap()
a.stale = false a.stale = false
a.refreshedAt = time.Time{} a.refreshedAt = time.Time{}
a.lastError = msg a.lastError = msg
a.nextAt = time.Time{} a.nextAt = time.Time{}
a.mu.Unlock() a.mu.Unlock()
a.client.Reset()
return true
} }
func (a *App) page(w http.ResponseWriter, r *http.Request) { func (a *App) page(w http.ResponseWriter, r *http.Request) {
@@ -303,14 +314,11 @@ func (a *App) page(w http.ResponseWriter, r *http.Request) {
} }
func (a *App) manualRefresh(w http.ResponseWriter, r *http.Request) { func (a *App) manualRefresh(w http.ResponseWriter, r *http.Request) {
if a.isLoggedIn() { if a.isLoggedIn() && a.refresh() && a.isLoggedIn() {
a.refresh()
if a.isLoggedIn() {
a.stampNext() a.stampNext()
a.wakeLoop() a.wakeLoop()
a.save() a.save()
} }
}
writeJSON(w, http.StatusOK, a.view()) writeJSON(w, http.StatusOK, a.view())
} }
@@ -339,9 +347,6 @@ func (a *App) sms(w http.ResponseWriter, r *http.Request) {
writeErr(w, "请输入正确的手机号码") writeErr(w, "请输入正确的手机号码")
return return
} }
a.mu.Lock()
a.phone = phone
a.mu.Unlock()
msg, err := a.client.SendSMS(r.Context(), phone) msg, err := a.client.SendSMS(r.Context(), phone)
if err != nil { if err != nil {
writeErr(w, cleanErr(err)) writeErr(w, cleanErr(err))
@@ -384,6 +389,10 @@ func (a *App) login(w http.ResponseWriter, r *http.Request) {
a.mu.Lock() a.mu.Lock()
a.loggedIn = true a.loggedIn = true
a.sessionID = result.SessionID a.sessionID = result.SessionID
a.raw = map[string]json.RawMessage{}
if a.phone != result.Phone {
a.snap = emptySnap()
}
a.phone = result.Phone a.phone = result.Phone
a.prov = result.Prov a.prov = result.Prov
a.city = result.City a.city = result.City
@@ -557,6 +566,9 @@ func (a *App) load() {
a.city = st.City a.city = st.City
a.loggedIn = st.LoggedIn && st.SessionID != "" a.loggedIn = st.LoggedIn && st.SessionID != ""
a.snap = st.Snapshot a.snap = st.Snapshot
for k, v := range st.Raw {
a.raw[k] = v
}
a.refreshedAt = st.RefreshedAt a.refreshedAt = st.RefreshedAt
a.lastError = st.LastError a.lastError = st.LastError
a.stale = st.Stale a.stale = st.Stale
@@ -574,7 +586,13 @@ func (a *App) load() {
} }
func (a *App) save() { func (a *App) save() {
a.saveMu.Lock()
defer a.saveMu.Unlock()
a.mu.Lock() a.mu.Lock()
raw := make(map[string]json.RawMessage, len(a.raw))
for k, v := range a.raw {
raw[k] = v
}
st := savedState{ st := savedState{
Phone: a.phone, Phone: a.phone,
SessionID: a.sessionID, SessionID: a.sessionID,
@@ -587,6 +605,7 @@ func (a *App) save() {
Stale: a.stale, Stale: a.stale,
PollMinutes: int(a.interval / time.Minute), PollMinutes: int(a.interval / time.Minute),
JitterMinutes: int(a.jitter / time.Minute), JitterMinutes: int(a.jitter / time.Minute),
Raw: raw,
} }
a.mu.Unlock() a.mu.Unlock()
st.Cookies = a.client.ExportCookies() st.Cookies = a.client.ExportCookies()
@@ -621,11 +640,11 @@ func (a *App) nextWaitLocked() time.Duration {
if base < time.Minute { if base < time.Minute {
base = 30 * time.Minute base = 30 * time.Minute
} }
maxMin := int(a.jitter / time.Minute) maxSec := int64(a.jitter / time.Second)
if maxMin <= 0 { if maxSec <= 0 {
return base return base
} }
return base + time.Duration(rand.IntN(maxMin+1))*time.Minute return base + time.Duration(rand.Int64N(maxSec+1))*time.Second
} }
func hasData(s cbn.Snapshot) bool { func hasData(s cbn.Snapshot) bool {
+8 -2
View File
@@ -464,7 +464,7 @@
} }
paintCountdown(); paintCountdown();
syncPoll(!!data.loggedIn); syncPoll(!!data.loggedIn);
$("dash").classList.toggle("stale", !!(data.stale && data.hasData && !data.loggedIn)); $("dash").classList.toggle("stale", !!(data.stale && data.hasData));
$("error").hidden = !data.error; $("error").hidden = !data.error;
$("error").textContent = data.error || ""; $("error").textContent = data.error || "";
if ($("settings").hidden) { if ($("settings").hidden) {
@@ -579,6 +579,7 @@
const res = await fetch("/api/overview", { cache: "no-store" }); const res = await fetch("/api/overview", { cache: "no-store" });
render(await res.json()); render(await res.json());
} catch (err) { } catch (err) {
lastKey = "";
$("error").hidden = false; $("error").hidden = false;
$("error").textContent = "连接失败"; $("error").textContent = "连接失败";
} }
@@ -656,7 +657,9 @@
$("settings").addEventListener("click", (event) => { $("settings").addEventListener("click", (event) => {
if (event.target === $("settings")) $("settings").hidden = true; if (event.target === $("settings")) $("settings").hidden = true;
}); });
$("settingsSave").addEventListener("click", () => { saveInterval().catch(() => {}); }); $("settingsSave").addEventListener("click", () => {
saveInterval().catch(() => { $("settingsMsg").textContent = "未保存"; });
});
$("captcha").addEventListener("click", () => { loadCaptcha(); captchaReady = true; }); $("captcha").addEventListener("click", () => { loadCaptcha(); captchaReady = true; });
$("captcha").addEventListener("error", () => { setLoginMsg("验证码加载失败"); }); $("captcha").addEventListener("error", () => { setLoginMsg("验证码加载失败"); });
@@ -779,6 +782,7 @@
lastKey = ""; lastKey = "";
render(data); render(data);
if (!res.ok || !data.loggedIn) toast(data.error || "刷新失败"); if (!res.ok || !data.loggedIn) toast(data.error || "刷新失败");
else if (data.refreshing) toast("正在刷新,稍后自动更新", true);
else if (data.error) toast(data.error); else if (data.error) toast(data.error);
else toast("刷新成功", true); else toast("刷新成功", true);
} catch (err) { } catch (err) {
@@ -806,6 +810,8 @@
$("sms").value = ""; $("sms").value = "";
setLoginMsg(""); setLoginMsg("");
render(await res.json()); render(await res.json());
} catch (err) {
toast("退出失败");
} finally { } finally {
$("logoutConfirm").disabled = false; $("logoutConfirm").disabled = false;
} }