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