Files

767 lines
18 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math/rand/v2"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
_ "time/tzdata"
"cbnsmsinfo/internal/cbn"
)
//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"`
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"`
JitterMinutes int `json:"jitterMinutes"`
Raw map[string]json.RawMessage `json:"raw,omitempty"`
}
type overview struct {
LoggedIn bool `json:"loggedIn"`
NeedLogin bool `json:"needLogin"`
CanResume bool `json:"canResume"`
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"`
Error string `json:"error,omitempty"`
Stale bool `json:"stale"`
HasData bool `json:"hasData"`
cbn.Snapshot
}
type App struct {
client *cbn.Client
interval time.Duration
jitter time.Duration
pollText string
cfgPhone string
kick chan struct{}
saveMu sync.Mutex
mu sync.Mutex
raw map[string]json.RawMessage
phone string
sessionID string
prov string
city string
loggedIn bool
snap cbn.Snapshot
refreshedAt time.Time
nextAt time.Time
lastError string
stale bool
refreshing bool
}
func main() {
log.SetFlags(log.LstdFlags)
cfg := loadConfig()
interval, err := time.ParseDuration(cfg.PollInterval)
if err != nil || interval < time.Minute {
log.Printf("轮询间隔无效,已改用 30 分钟")
interval = 30 * time.Minute
}
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 {
log.Printf("页面参数暂未就绪,登录时会再试: %v", err)
}
prepCancel()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go app.loop(ctx)
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())
})
mux.HandleFunc("POST /api/refresh", app.manualRefresh)
mux.HandleFunc("GET /api/captcha", app.captcha)
mux.HandleFunc("POST /api/sms", app.sms)
mux.HandleFunc("POST /api/login", app.login)
mux.HandleFunc("POST /api/logout", app.logout)
mux.HandleFunc("POST /api/resume", app.resume)
mux.HandleFunc("POST /api/interval", app.setInterval)
srv := &http.Server{
Addr: cfg.Listen,
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
go func() {
<-ctx.Done()
shut, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = srv.Shutdown(shut)
}()
log.Printf("已启动,浏览器打开 %s", listenURL(cfg.Listen))
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}
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),
raw: map[string]json.RawMessage{},
snap: cbn.Snapshot{
Resources: []cbn.Resource{},
Extras: []cbn.Extra{},
Bills: []cbn.Bill{},
},
}
}
func (a *App) loop(ctx context.Context) {
timer := time.NewTimer(time.Hour)
stopTimer(timer)
if a.isLoggedIn() {
a.stampNext()
timer.Reset(a.untilNext())
go a.refresh()
}
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-a.kick:
stopTimer(timer)
if a.isLoggedIn() {
timer.Reset(a.untilNext())
}
case <-timer.C:
if !a.isLoggedIn() {
continue
}
a.stampNext()
timer.Reset(a.untilNext())
go a.refresh()
}
}
}
func stopTimer(timer *time.Timer) {
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
}
func (a *App) wakeLoop() {
select {
case a.kick <- struct{}{}:
default:
}
}
// refresh 返回 false 表示已有一次刷新在进行,本次没有执行。
func (a *App) refresh() bool {
a.mu.Lock()
if !a.loggedIn || a.sessionID == "" || a.phone == "" {
a.mu.Unlock()
return true
}
if a.refreshing {
a.mu.Unlock()
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()
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) {
replaced = !a.markLoggedOut(sid, "会话已失效,请重新登录")
return true
}
if err != nil {
errs = append(errs, item.name+":"+err.Error())
continue
}
fresh[item.path] = raw
}
a.mu.Lock()
defer a.mu.Unlock()
if a.sessionID != sid {
replaced = a.loggedIn
return true
}
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", a.snap.PhoneMasked)
}
return true
}
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) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(indexPage)
}
func (a *App) manualRefresh(w http.ResponseWriter, r *http.Request) {
if a.isLoggedIn() && a.refresh() && a.isLoggedIn() {
a.stampNext()
a.wakeLoop()
a.save()
}
writeJSON(w, http.StatusOK, a.view())
}
func (a *App) captcha(w http.ResponseWriter, r *http.Request) {
body, ctype, err := a.client.Captcha(r.Context())
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"ok": false, "message": err.Error()})
return
}
a.save()
w.Header().Set("Content-Type", ctype)
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}
func (a *App) sms(w http.ResponseWriter, r *http.Request) {
var req struct {
Phone string `json:"phone"`
}
if err := decode(r, &req); err != nil {
writeErr(w, "请求格式不对")
return
}
phone := strings.TrimSpace(req.Phone)
if !validPhone(phone) {
writeErr(w, "请输入正确的手机号码")
return
}
msg, err := a.client.SendSMS(r.Context(), phone)
if err != nil {
writeErr(w, cleanErr(err))
return
}
a.save()
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": msg})
}
func (a *App) login(w http.ResponseWriter, r *http.Request) {
var req struct {
Phone string `json:"phone"`
ImageCode string `json:"imageCode"`
SMSCode string `json:"smsCode"`
}
if err := decode(r, &req); err != nil {
writeErr(w, "请求格式不对")
return
}
phone := strings.TrimSpace(req.Phone)
image := strings.TrimSpace(req.ImageCode)
sms := strings.TrimSpace(req.SMSCode)
if !validPhone(phone) {
writeErr(w, "请输入正确的手机号码")
return
}
if image == "" {
writeErr(w, "请输入图形验证码")
return
}
if sms == "" {
writeErr(w, "请输入短信验证码")
return
}
result, err := a.client.Login(r.Context(), phone, image, sms)
if err != nil {
writeErr(w, cleanErr(err))
return
}
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
a.lastError = ""
a.stale = false
a.mu.Unlock()
a.stampNext()
a.wakeLoop()
a.save()
a.refresh()
log.Printf("登录成功 %s", cbn.MaskPhone(result.Phone))
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "登录成功"})
}
func (a *App) logout(w http.ResponseWriter, r *http.Request) {
a.mu.Lock()
a.loggedIn = false
a.lastError = ""
a.nextAt = time.Time{}
a.mu.Unlock()
a.wakeLoop()
a.save()
writeJSON(w, http.StatusOK, a.view())
}
func (a *App) resume(w http.ResponseWriter, r *http.Request) {
var req struct {
Phone string `json:"phone"`
}
if err := decode(r, &req); err != nil {
writeErr(w, "请求格式不对")
return
}
phone := strings.TrimSpace(req.Phone)
a.mu.Lock()
same := a.sessionID != "" && a.phone != "" && a.phone == phone
a.mu.Unlock()
if !same {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "needCode": true})
return
}
a.mu.Lock()
a.loggedIn = true
a.lastError = ""
a.mu.Unlock()
a.stampNext()
a.wakeLoop()
a.refresh()
if !a.isLoggedIn() {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "expired": true, "message": "会话已过期"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
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.stampNextLocked()
}
a.mu.Unlock()
select {
case a.kick <- struct{}{}:
default:
}
a.save()
writeJSON(w, http.StatusOK, a.view())
}
func (a *App) untilNext() time.Duration {
a.mu.Lock()
defer a.mu.Unlock()
if !a.nextAt.IsZero() {
if d := time.Until(a.nextAt); d > 0 {
return d
}
}
return time.Second
}
func (a *App) view() overview {
a.mu.Lock()
defer a.mu.Unlock()
snap := a.snap
if snap.Resources == nil {
snap.Resources = []cbn.Resource{}
}
if snap.Extras == nil {
snap.Extras = []cbn.Extra{}
}
if snap.Bills == nil {
snap.Bills = []cbn.Bill{}
}
if len(snap.Resources) > 0 || len(snap.Extras) > 0 {
snap.DataTotal, snap.DataUsed, snap.DataRemain, snap.DataExtra = cbn.SummarizeTraffic(snap.Resources, snap.Extras)
snap.VoiceTotal, snap.VoiceRemain = cbn.SummarizeVoice(snap.Resources)
}
if !a.loggedIn {
phone := a.phone
snap = emptySnap()
snap.Phone = phone
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),
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")
}
if a.loggedIn && !a.nextAt.IsZero() {
left := time.Until(a.nextAt)
if left < 0 {
left = 0
}
out.SecondsLeft = int(left.Round(time.Second) / time.Second)
out.NextRefreshAt = a.nextAt.In(shanghai()).Format("15:04:05")
}
return out
}
func emptySnap() cbn.Snapshot {
return cbn.Snapshot{
Resources: []cbn.Resource{},
Extras: []cbn.Extra{},
Bills: []cbn.Bill{},
}
}
func (a *App) load() {
b, err := os.ReadFile(statePath)
if err != nil {
a.phone = a.cfgPhone
return
}
var st savedState
if json.Unmarshal(b, &st) != nil {
a.phone = a.cfgPhone
return
}
a.phone = strings.TrimSpace(st.Phone)
if a.phone == "" {
a.phone = a.cfgPhone
}
a.sessionID = st.SessionID
a.prov = st.Prov
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
if st.PollMinutes >= 1 && st.PollMinutes <= 1440 {
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))
}
}
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,
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),
Raw: raw,
}
a.mu.Unlock()
st.Cookies = a.client.ExportCookies()
buf, err := json.MarshalIndent(st, "", " ")
if err != nil {
log.Printf("保存会话失败: %v", err)
return
}
if err := writeFileAtomic(statePath, buf); err != nil {
log.Printf("保存会话失败: %v", err)
}
}
func (a *App) isLoggedIn() bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.loggedIn
}
func (a *App) stampNext() {
a.mu.Lock()
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
}
maxSec := int64(a.jitter / time.Second)
if maxSec <= 0 {
return base
}
return base + time.Duration(rand.Int64N(maxSec+1))*time.Second
}
func hasData(s cbn.Snapshot) bool {
return s.Balance != "" || s.PackageName != "" || s.MonthFee != "" || len(s.Resources) > 0 || len(s.Bills) > 0
}
func loadConfig() Config {
cfg := Config{Listen: ":8787", PollInterval: "30m"}
b, err := os.ReadFile("config.json")
if err != nil {
if os.IsNotExist(err) {
buf, _ := json.MarshalIndent(cfg, "", " ")
buf = append(buf, '\n')
if werr := os.WriteFile("config.json", buf, 0644); werr != nil {
log.Printf("未写入 config.json: %v", werr)
}
}
} else if json.Unmarshal(b, &cfg) != nil {
cfg = Config{Listen: ":8787", PollInterval: "30m"}
}
if strings.TrimSpace(cfg.Listen) == "" {
cfg.Listen = ":8787"
}
if strings.TrimSpace(cfg.PollInterval) == "" {
cfg.PollInterval = "30m"
}
if v := strings.TrimSpace(os.Getenv("CBN_LISTEN")); v != "" {
cfg.Listen = v
}
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
}
return cfg
}
func writeFileAtomic(path string, b []byte) error {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, b, 0600); err != nil {
return err
}
return os.Rename(tmp, path)
}
func decode(r *http.Request, dest any) error {
defer r.Body.Close()
return json.NewDecoder(io.LimitReader(r.Body, 1<<16)).Decode(dest)
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(code)
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
_ = enc.Encode(v)
}
func writeErr(w http.ResponseWriter, msg string) {
writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "message": msg})
}
func cleanErr(err error) string {
if err == nil {
return "请求失败"
}
msg := err.Error()
if msg == "" {
return "请求失败"
}
return msg
}
func validPhone(s string) bool {
if len(s) != 11 || s[0] != '1' {
return false
}
for _, c := range s {
if c < '0' || c > '9' {
return false
}
}
return true
}
func humanInterval(d time.Duration) string {
if d >= time.Hour && d%time.Hour == 0 {
return fmt.Sprintf("%d 小时", int(d.Hours()))
}
if d >= time.Minute && d%time.Minute == 0 {
return fmt.Sprintf("%d 分钟", int(d.Minutes()))
}
return d.String()
}
func listenURL(addr string) string {
if strings.HasPrefix(addr, ":") {
return "http://127.0.0.1" + addr
}
return "http://" + addr
}
func shanghai() *time.Location {
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
return time.FixedZone("CST", 8*3600)
}
return loc
}