Files
CMNETSMSInfo/main.go
T

797 lines
19 KiB
Go

package main
import (
"bytes"
"context"
crand "crypto/rand"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math/rand/v2"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
_ "time/tzdata"
"cmnetsmsinfo/internal/cmnet"
)
//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"`
ProvCode string `json:"provCode"`
DeviceID string `json:"deviceId"`
LoggedIn bool `json:"loggedIn"`
SessionOK bool `json:"sessionOk"`
Cookies []cmnet.Cookie `json:"cookies"`
Snapshot cmnet.Snapshot `json:"snapshot"`
RealRaw json.RawMessage `json:"realRaw,omitempty"`
PlanRaw json.RawMessage `json:"planRaw,omitempty"`
RefreshedAt time.Time `json:"refreshedAt"`
LastError string `json:"lastError"`
Stale bool `json:"stale"`
PollMinutes int `json:"pollMinutes"`
JitterMinutes int `json:"jitterMinutes"`
}
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"`
Error string `json:"error,omitempty"`
Stale bool `json:"stale"`
HasData bool `json:"hasData"`
LoginEpoch int `json:"loginEpoch"`
cmnet.Snapshot
}
type App struct {
client *cmnet.Client
interval time.Duration
jitter time.Duration
pollText string
cfgPhone string
kick chan struct{}
saveMu sync.Mutex
mu sync.Mutex
phone string
provCode string
deviceID string
loggedIn bool
sessionOK bool
snap cmnet.Snapshot
realRaw json.RawMessage
planRaw json.RawMessage
refreshedAt time.Time
nextAt time.Time
lastError string
stale bool
refreshing bool
loginEpoch int
}
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 {
cfg.JitterMinutes = 0
}
app := newApp(cmnet.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("GET /api/qr", app.qrCode)
mux.HandleFunc("GET /api/qr/poll", app.qrPoll)
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: logLocalAPI(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 *cmnet.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),
deviceID: newDeviceID(),
snap: cmnet.Snapshot{
Resources: []cmnet.Resource{},
Extras: []cmnet.Extra{},
Bills: []cmnet.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:
}
}
func (a *App) refresh() bool {
a.mu.Lock()
if !a.loggedIn || a.phone == "" {
a.mu.Unlock()
return true
}
if a.refreshing {
a.mu.Unlock()
return false
}
a.refreshing = true
phone, prov := a.phone, a.provCode
a.mu.Unlock()
defer func() {
a.mu.Lock()
a.refreshing = false
a.mu.Unlock()
a.save()
}()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
real, plan, err := a.client.Query(ctx, phone, prov)
cmnet.Debugf("刷新 phone=%s prov=%s err=%v", phone, prov, err)
if errors.Is(err, cmnet.ErrNeedLogin) {
if a.client.SessionAlive(ctx) {
a.mu.Lock()
a.stale = true
a.lastError = "账户数据暂时没有刷新"
a.mu.Unlock()
return true
}
a.markLoggedOut("会话已失效,请重新登录")
return true
}
a.mu.Lock()
defer a.mu.Unlock()
if a.phone != phone || !a.loggedIn {
return true
}
if err != nil && real == nil && plan == nil {
a.stale = true
a.lastError = err.Error()
return true
}
if real != nil {
a.realRaw = real
}
if plan != nil {
a.planRaw = plan
}
a.snap = cmnet.BuildSnapshot(phone, a.client.ProvinceName(prov), a.realRaw, a.planRaw)
a.stale = err != nil
if err != nil {
a.lastError = err.Error()
return true
}
a.lastError = ""
a.refreshedAt = time.Now()
log.Printf("同步完成 %s", a.snap.PhoneMasked)
return true
}
func (a *App) markLoggedOut(msg string) {
cmnet.Debugf("清除登录状态 %s", msg)
a.client.Reset()
a.mu.Lock()
a.loggedIn = false
a.sessionOK = false
a.snap = emptySnap()
a.realRaw, a.planRaw = nil, nil
a.stale = false
a.refreshedAt = time.Time{}
a.lastError = msg
a.nextAt = time.Time{}
a.loginEpoch++
a.mu.Unlock()
a.save()
}
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"`
ImageCode string `json:"imageCode"`
}
if err := decode(r, &req); err != nil {
writeErr(w, "请求格式不对")
return
}
phone := strings.TrimSpace(req.Phone)
image := strings.TrimSpace(req.ImageCode)
if !validPhone(phone) {
writeErr(w, "请输入正确的手机号码")
return
}
if image == "" {
writeErr(w, "请填写图形验证码")
return
}
msg, err := a.client.SendSMS(r.Context(), phone, image)
if err != nil {
writeErr(w, err.Error())
return
}
a.mu.Lock()
a.phone = phone
a.mu.Unlock()
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) || image == "" || sms == "" {
writeErr(w, "请填写手机号、图形验证码和短信验证码")
return
}
a.mu.Lock()
deviceID := a.deviceID
a.mu.Unlock()
result, err := a.client.Login(r.Context(), phone, image, sms, deviceID)
if err != nil {
writeErr(w, err.Error())
return
}
a.acceptLogin(result)
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "登录成功"})
}
func (a *App) qrCode(w http.ResponseWriter, r *http.Request) {
body, err := a.client.QRCode(r.Context())
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"ok": false, "message": err.Error()})
return
}
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}
func (a *App) qrPoll(w http.ResponseWriter, r *http.Request) {
status, err := a.client.PollQR(r.Context())
if err != nil {
writeErr(w, err.Error())
return
}
if status.Expired {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "expired": true, "message": "二维码已失效,请刷新"})
return
}
if status.Waiting || status.Result.Phone == "" {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "waiting": true})
return
}
a.acceptLogin(status.Result)
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "登录成功"})
}
func (a *App) acceptLogin(result cmnet.LoginResult) {
a.mu.Lock()
a.loggedIn = true
a.sessionOK = true
a.phone = result.Phone
a.provCode = result.ProvCode
a.lastError = ""
a.stale = false
a.mu.Unlock()
a.stampNext()
a.wakeLoop()
a.save()
a.refresh()
log.Printf("登录成功 %s", cmnet.MaskPhone(result.Phone))
}
func (a *App) logout(w http.ResponseWriter, r *http.Request) {
cmnet.Debugf("用户退出,清除登录状态")
a.client.Reset()
a.mu.Lock()
a.loggedIn = false
a.sessionOK = false
a.snap = emptySnap()
a.realRaw, a.planRaw = nil, nil
a.stale = false
a.refreshedAt = time.Time{}
a.lastError = ""
a.nextAt = time.Time{}
a.loginEpoch++
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.sessionOK && 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) clientCookies() []cmnet.Cookie {
return a.client.ExportCookies()
}
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()
a.wakeLoop()
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 = []cmnet.Resource{}
}
if snap.Extras == nil {
snap.Extras = []cmnet.Extra{}
}
if snap.Bills == nil {
snap.Bills = []cmnet.Bill{}
}
if !a.loggedIn {
phone := a.phone
snap = emptySnap()
snap.Phone = phone
snap.PhoneMasked = cmnet.MaskPhone(phone)
} else if name := a.client.ProvinceName(a.provCode); name != "" {
snap.Region = name
a.snap.Region = name
}
out := overview{
LoggedIn: a.loggedIn,
NeedLogin: !a.loggedIn,
CanResume: !a.loggedIn && a.sessionOK && 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),
LoginEpoch: a.loginEpoch,
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)
}
return out
}
func emptySnap() cmnet.Snapshot {
return cmnet.Snapshot{Resources: []cmnet.Resource{}, Extras: []cmnet.Extra{}, Bills: []cmnet.Bill{}}
}
func (a *App) load() {
a.phone = a.cfgPhone
b, err := os.ReadFile(statePath)
if err != nil {
return
}
var st savedState
if json.Unmarshal(b, &st) != nil {
return
}
if st.DeviceID != "" {
a.deviceID = st.DeviceID
}
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.save()
}
func (a *App) save() {
a.saveMu.Lock()
defer a.saveMu.Unlock()
a.mu.Lock()
st := savedState{
DeviceID: a.deviceID,
PollMinutes: int(a.interval / time.Minute),
JitterMinutes: int(a.jitter / time.Minute),
}
a.mu.Unlock()
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 cmnet.Snapshot) bool {
return s.Balance != "" || len(s.Resources) > 0 || s.MonthFee != ""
}
func loadConfig() Config {
cfg := Config{Listen: ":8788", PollInterval: "30m"}
b, err := os.ReadFile("config.json")
if err != nil {
if os.IsNotExist(err) {
buf, _ := json.MarshalIndent(cfg, "", " ")
buf = append(buf, '\n')
_ = os.WriteFile("config.json", buf, 0644)
}
} else if json.Unmarshal(b, &cfg) != nil {
cfg = Config{Listen: ":8788", PollInterval: "30m"}
}
if strings.TrimSpace(cfg.Listen) == "" {
cfg.Listen = ":8788"
}
if strings.TrimSpace(cfg.PollInterval) == "" {
cfg.PollInterval = "30m"
}
if v := strings.TrimSpace(os.Getenv("CMNET_LISTEN")); v != "" {
cfg.Listen = v
}
if v := strings.TrimSpace(os.Getenv("CMNET_POLL")); v != "" {
cfg.PollInterval = v
}
if v := strings.TrimSpace(os.Getenv("CMNET_JITTER")); v != "" {
if n, err := time.ParseDuration(v); err == nil {
cfg.JitterMinutes = int(n / time.Minute)
}
}
if v := strings.TrimSpace(os.Getenv("CMNET_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 logLocalAPI(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !cmnet.DebugOn() || !strings.HasPrefix(r.URL.Path, "/api/") {
next.ServeHTTP(w, r)
return
}
rec := &bodyCapture{ResponseWriter: w, code: http.StatusOK}
next.ServeHTTP(rec, r)
body := rec.buf.Bytes()
if strings.Contains(rec.Header().Get("Content-Type"), "image") {
cmnet.Debugf("本地 %s %s -> %d 图片 %d 字节", r.Method, r.URL.RequestURI(), rec.code, len(body))
return
}
const limit = 8000
text := string(body)
if len(text) > limit {
text = text[:limit]
}
cmnet.Debugf("本地 %s %s -> %d %s", r.Method, r.URL.RequestURI(), rec.code, strings.TrimSpace(text))
})
}
type bodyCapture struct {
http.ResponseWriter
code int
buf bytes.Buffer
}
func (c *bodyCapture) WriteHeader(code int) {
c.code = code
c.ResponseWriter.WriteHeader(code)
}
func (c *bodyCapture) Write(p []byte) (int, error) {
c.buf.Write(p)
return c.ResponseWriter.Write(p)
}
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 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
}
func newDeviceID() string {
var a, b [16]byte
_, _ = crand.Read(a[:])
_, _ = crand.Read(b[:])
return hex.EncodeToString(a[:]) + "_" + hex.EncodeToString(b[:])
}