feat: 提交广电个人中心只读面板

This commit is contained in:
2026-10-12 18:20:48 +08:00
commit 92b5621a51
12 changed files with 2998 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
data/
config.json
*.exe
*.chlz
*.zip
Temp/
+62
View File
@@ -0,0 +1,62 @@
# 广电账户
给自己的中国广电号码看余额、当月话费、流量和语音。页面只读,登录后按设定间隔自动刷新。适合号码插在不能收短信的设备上:会话还在就直接看;过期后把卡插回手机收验证码,在这个页面完成登录。
页面没有访问口令,只放在自己的机器上。
## 使用
在程序目录放 `config.json`,然后运行编译好的程序,浏览器打开它监听的地址。
```json
{
"listen": ":8787",
"pollInterval": "30m",
"phone": ""
}
```
| 字段 | 作用 |
| --- | --- |
| `listen` | 监听地址,默认 `:8787` |
| `pollInterval` | 登录后的刷新间隔,最短 1 分钟,例如 `30m`、`1h` |
| `phone` | 可选。写上后登录页会预先填好号码 |
环境变量 `CBN_LISTEN`、`CBN_POLL`、`CBN_PHONE` 会覆盖同名字段。
登录页输入号码。如果这个号码上次的会话还在,点登录会直接进入主页并开始倒计时。会话失效后才出现图形验证码和短信验证码。主页右上角「更多」里可以改刷新间隔、立刻刷新,或退出。退出只回到登录页,不向运营商注销,也不再自动刷新,让会话自己过期。运营商判定会话失效后,页面会回到登录页并提示重新登录。
会话、Cookie 和站点参数写在程序目录的 `data/`。不要把这个目录交给别人。
## 编译
需要 Go 1.26 或更高。
```bash
go build -trimpath -ldflags="-s -w" -o cbn-dashboard .
```
交叉编译到 Linux:
```bash
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o cbn-dashboard .
```
把二进制和 `config.json` 放在同一目录运行。程序会在该目录创建 `data/`。
## 流程
```mermaid
flowchart TD
open[打开页面] --> saved{这个号码还有上次的会话?}
saved -->|有| pull[用该会话拉取余额和余量]
pull -->|成功| home[进入主页并按间隔刷新]
pull -->|会话已失效| code[填写图形验证码和短信验证码]
saved -->|没有| code
code --> home
home --> tick[倒计时结束]
tick -->|会话仍有效| home
tick -->|运营商要求重新登录| code
home --> logout[退出]
logout --> hold[停在登录页且不再刷新]
```
+5
View File
@@ -0,0 +1,5 @@
{
"listen": ":8787",
"pollInterval": "30m",
"phone": ""
}
+12
View File
@@ -0,0 +1,12 @@
module cbnsmsinfo
go 1.26.0
require github.com/dop251/goja v0.0.0-20261011204819-0c9fae1b959d
require (
github.com/dlclark/regexp2/v2 v2.8.1 // indirect
github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect
golang.org/x/text v0.43.0 // indirect
)
+10
View File
@@ -0,0 +1,10 @@
github.com/dlclark/regexp2/v2 v2.8.1 h1:I1jbaCbXeOxdVN8z3fb55Mvtgb94/6+Dh0zjmXjKV/0=
github.com/dlclark/regexp2/v2 v2.8.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU=
github.com/dop251/goja v0.0.0-20261011204819-0c9fae1b959d h1:ONwCIvg9kcijZYa0B9SN/Fo/v7K0UW92HE5oyt3pFvo=
github.com/dop251/goja v0.0.0-20261011204819-0c9fae1b959d/go.mod h1:Cp9NYOLrEKg/ypIRkUWYXWLuKAyyFGkDmGeJ95Sw0zI=
github.com/go-sourcemap/sourcemap v2.1.3+incompatible h1:W1iEw64niKVGogNgBN3ePyLFfuisuzeidWPMPWmECqU=
github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg=
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 h1:4/hN5RUoecvl+RmJRE2YxKWtnnQls6rQjjW5oV7qg2U=
github.com/google/pprof v0.0.0-20230207041349-798e818bf904/go.mod h1:uglQLonpP8qtYCYyzA+8c/9qtqgA3qsXGYqCPKARAFg=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
+571
View File
@@ -0,0 +1,571 @@
package cbn
import (
"bytes"
"context"
"crypto/rsa"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"sync"
"time"
)
const (
origin = "https://www.10099.com.cn"
basePath = "/contact-web"
loginReferer = origin + "/login.html"
homeReferer = origin + "/personal-center-number-order.html"
userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36 Edg/155.0.0.0"
siteCachePath = "data/site.json"
PathBalance = "/api/busi/qryBalanceFee"
PathBill = "/api/busi/qryBillInfo"
PathResource = "/api/busi/qryUserRes"
PathSubscribe = "/api/busi/qrySubscribeBusiness"
)
var ErrNeedLogin = errors.New("会话已失效")
type APIError struct {
Status string
Message string
}
func (e *APIError) Error() string {
if e.Message != "" {
return e.Message
}
if e.Status != "" {
return e.Status
}
return "请求失败"
}
type Result struct {
Status string
Message string
Data json.RawMessage
}
type Cookie struct {
Name string `json:"name"`
Value string `json:"value"`
}
type LoginResult struct {
SessionID string
Phone string
Prov string
City string
}
type Client struct {
mu sync.Mutex
http *http.Client
jar *cookiejar.Jar
profile *siteProfile
}
func New() *Client {
jar, err := cookiejar.New(nil)
if err != nil {
panic(err)
}
return &Client{
jar: jar,
http: &http.Client{
Timeout: 30 * time.Second,
Jar: jar,
},
}
}
func (c *Client) ExportCookies() []Cookie {
c.mu.Lock()
defer c.mu.Unlock()
return c.exportLocked()
}
func (c *Client) ImportCookies(list []Cookie) {
c.mu.Lock()
defer c.mu.Unlock()
u, _ := url.Parse(origin + "/")
cs := make([]*http.Cookie, 0, len(list))
for _, item := range list {
if item.Name == "" {
continue
}
cs = append(cs, &http.Cookie{Name: item.Name, Value: item.Value, Path: "/"})
}
c.jar.SetCookies(u, cs)
}
func (c *Client) Reset() {
c.mu.Lock()
defer c.mu.Unlock()
c.resetLocked()
}
func (c *Client) Prepare(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.ensureProfile(ctx, false)
}
func (c *Client) Captcha(ctx context.Context) ([]byte, string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.ensureProfile(ctx, false); err != nil {
return nil, "", err
}
body, ctype, err := c.get(ctx, "/api/login/getImageCheckCode", loginReferer, "*/*")
if err != nil {
return nil, "", err
}
if !strings.Contains(strings.ToLower(ctype), "image/") && !isImage(body) {
snippet := strings.TrimSpace(string(body))
if len(snippet) > 160 {
snippet = snippet[:160]
}
if ctype == "" {
ctype = "unknown"
}
return nil, "", fmt.Errorf("没有拿到图形验证码(%s)%s", ctype, snippet)
}
if ctype == "" || !strings.Contains(strings.ToLower(ctype), "image/") {
ctype = sniffImage(body)
}
return body, ctype, nil
}
func isImage(body []byte) bool {
if len(body) >= 3 && body[0] == 0xff && body[1] == 0xd8 && body[2] == 0xff {
return true
}
if len(body) >= 8 && string(body[:8]) == "\x89PNG\r\n\x1a\n" {
return true
}
if len(body) >= 6 && (string(body[:6]) == "GIF87a" || string(body[:6]) == "GIF89a") {
return true
}
return false
}
func sniffImage(body []byte) string {
if len(body) >= 8 && string(body[:8]) == "\x89PNG\r\n\x1a\n" {
return "image/png"
}
if len(body) >= 6 && (string(body[:6]) == "GIF87a" || string(body[:6]) == "GIF89a") {
return "image/gif"
}
return "image/jpeg"
}
func (c *Client) SendSMS(ctx context.Context, phone string) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.ensureProfile(ctx, false); err != nil {
return "", err
}
res, err := c.post(ctx, "/api/login/getVerifyCode", map[string]any{
"recieveNum": phone,
"channelId": c.channelID(),
"type": 5,
}, loginReferer)
if err != nil {
return "", err
}
ok, desc := innerOK(res.Data)
if !ok {
return "", errors.New(desc)
}
if desc == "" {
desc = "短信验证码已发送"
}
return desc, nil
}
func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode string) (LoginResult, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.ensureProfile(ctx, false); err != nil {
return LoginResult{}, err
}
res, err := c.post(ctx, "/api/login/gwLogin", map[string]any{
"channelId": c.channelID(),
"loginPhone": phone,
"loginPassWord": smsCode,
"loginType": "5",
"channelType": "1",
"imageCheckCode": imageCode,
}, loginReferer)
if err != nil {
return LoginResult{}, err
}
var data struct {
SessionID string `json:"sessionId"`
LoginPhone string `json:"loginPhone"`
PhoneInfo struct {
MgmtProvName string `json:"mgmtProvName"`
MgmtDistrictName string `json:"mgmtDistrictName"`
AccessNumber string `json:"accessNumber"`
} `json:"phoneInfo"`
}
if err := json.Unmarshal(res.Data, &data); err != nil {
return LoginResult{}, errors.New("登录结果无法解析")
}
if data.SessionID == "" {
return LoginResult{}, errors.New("登录未返回会话")
}
gotPhone := data.LoginPhone
if gotPhone == "" {
gotPhone = data.PhoneInfo.AccessNumber
}
if gotPhone == "" {
gotPhone = phone
}
return LoginResult{
SessionID: data.SessionID,
Phone: gotPhone,
Prov: data.PhoneInfo.MgmtProvName,
City: data.PhoneInfo.MgmtDistrictName,
}, nil
}
func (c *Client) Logout(ctx context.Context, sessionID string) {
c.mu.Lock()
defer c.mu.Unlock()
if sessionID != "" {
u := origin + basePath + "/api/login/logOut?sessionId=" + url.QueryEscape(sessionID)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err == nil {
c.decorate(req, loginReferer, "")
_, _, _ = c.send(req, nil)
}
}
c.resetLocked()
}
func (c *Client) Query(ctx context.Context, path, phone, sessionID string) (json.RawMessage, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.ensureProfile(ctx, false); err != nil {
return nil, err
}
res, err := c.post(ctx, path, map[string]any{
"sessionId": sessionID,
"channelId": c.profile.ChannelID,
"accessNum": phone,
}, homeReferer)
if err != nil {
return nil, err
}
return res.Data, nil
}
func (c *Client) channelID() string {
if c.profile == nil {
return ""
}
return c.profile.ChannelID
}
func (c *Client) post(ctx context.Context, path string, payload map[string]any, referer string) (*Result, error) {
if err := c.ensureProfile(ctx, false); err != nil {
return nil, err
}
res, err := c.postOnce(ctx, path, payload, referer)
if errors.Is(err, errDecrypt) {
if err2 := c.ensureProfile(ctx, true); err2 != nil {
return nil, err
}
return c.postOnce(ctx, path, payload, referer)
}
return res, err
}
func (c *Client) postOnce(ctx context.Context, path string, payload map[string]any, referer string) (*Result, error) {
body := make(map[string]any, len(payload)+2)
for k, v := range payload {
body[k] = v
}
body["v"] = c.profile.Version
body["timestamp"] = time.Now().UnixMilli()
access := accessSign(body)
plain, err := marshalCompact(body)
if err != nil {
return nil, err
}
enc, err := encryptLong(c.profile.Public, encodeURIComponent(string(plain)))
if err != nil {
return nil, err
}
envelope, err := json.Marshal(struct {
Data string `json:"data"`
}{Data: enc})
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, origin+basePath+path, nil)
if err != nil {
return nil, err
}
c.decorate(req, referer, "application/json, text/javascript, */*; q=0.01")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Requested-With", "XMLHttpRequest")
req.Header.Set("Access", access)
buf, _, err := c.send(req, envelope)
if err != nil {
return nil, err
}
return parseBody(buf, c.profile.Private)
}
func (c *Client) get(ctx context.Context, path, referer, accept string) ([]byte, string, error) {
return c.getURL(ctx, origin+basePath+path, referer, accept)
}
func (c *Client) getURL(ctx context.Context, rawURL, referer, accept string) ([]byte, string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, "", err
}
c.decorate(req, referer, accept)
return c.send(req, nil)
}
func (c *Client) send(req *http.Request, body []byte) ([]byte, string, error) {
var last []byte
var lastType string
for attempt := 0; attempt < 2; attempt++ {
r := req.Clone(req.Context())
if body != nil {
r.Body = io.NopCloser(bytes.NewReader(body))
r.ContentLength = int64(len(body))
}
resp, err := c.http.Do(r)
if err != nil {
return nil, "", err
}
buf, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
resp.Body.Close()
if err != nil {
return nil, "", err
}
last, lastType = buf, resp.Header.Get("Content-Type")
if attempt == 0 && isWAF(buf) {
token, err := solveACW(string(buf))
if err != nil {
return nil, "", err
}
c.setCookie("acw_sc__v2", token)
continue
}
if resp.StatusCode >= 400 && !bytes.Contains(buf, []byte(`"status"`)) && !isImage(buf) {
return nil, "", fmt.Errorf("网站返回 %d", resp.StatusCode)
}
return buf, lastType, nil
}
if isWAF(last) {
return nil, "", errors.New("网站校验没有通过")
}
return last, lastType, nil
}
func (c *Client) ensureProfile(ctx context.Context, force bool) error {
if !force && c.profile != nil && time.Since(c.profile.FetchedAt) < siteCacheTTL {
return nil
}
p, err := c.fetchProfile(ctx)
if err != nil {
if c.profile != nil && !force {
return nil
}
if cached, err2 := loadSiteCache(siteCachePath); err2 == nil {
c.profile = cached
log.Printf("网页参数暂时拉不下来,继续用 %s 的缓存", cached.FetchedAt.Format("2006-01-02 15:04"))
return nil
}
return err
}
changed := c.profile == nil || c.profile.PublicB64 != p.PublicB64 || c.profile.Version != p.Version || c.profile.ChannelID != p.ChannelID
c.profile = p
if err := saveSiteCache(siteCachePath, p); err != nil {
log.Printf("页面参数已读取,但缓存没写成: %v", err)
}
if changed {
log.Printf("已同步页面参数 %s %s", p.ChannelID, p.Version)
}
return nil
}
func (c *Client) fetchProfile(ctx context.Context) (*siteProfile, error) {
page, _, err := c.getURL(ctx, loginReferer, loginReferer, "text/html,application/xhtml+xml")
if err != nil {
return nil, err
}
if isWAF(page) {
return nil, errors.New("登录页被校验拦住了")
}
urls := scriptURLs(string(page))
if len(urls) == 0 {
return nil, errors.New("登录页里没有脚本地址")
}
var last error
for _, ref := range urls {
body, _, err := c.getURL(ctx, resolveURL(ref), loginReferer, "*/*")
if err != nil {
last = err
continue
}
if isWAF(body) || !bytes.Contains(body, []byte("MII")) {
continue
}
p, err := parseSiteJS(string(body))
if err == nil {
return p, nil
}
last = err
if strings.Contains(ref, "common-") {
break
}
}
if last != nil {
return nil, last
}
return nil, errors.New("没有在页面脚本里找到加密参数")
}
func (c *Client) setCookie(name, value string) {
u, _ := url.Parse(origin + "/")
c.jar.SetCookies(u, []*http.Cookie{{Name: name, Value: value, Path: "/"}})
}
func isWAF(body []byte) bool {
return bytes.Contains(body, []byte("renderData")) && bytes.Contains(body, []byte("acw_sc__v2"))
}
func (c *Client) decorate(req *http.Request, referer, accept string) {
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
req.Header.Set("Referer", referer)
if accept != "" {
req.Header.Set("Accept", accept)
}
req.Header.Set("Sec-Fetch-Site", "same-origin")
req.Header.Set("Sec-Fetch-Mode", "cors")
req.Header.Set("Sec-Fetch-Dest", "empty")
}
func (c *Client) exportLocked() []Cookie {
u, _ := url.Parse(origin + "/")
got := c.jar.Cookies(u)
out := make([]Cookie, 0, len(got))
for _, ck := range got {
out = append(out, Cookie{Name: ck.Name, Value: ck.Value})
}
return out
}
func (c *Client) resetLocked() {
jar, err := cookiejar.New(nil)
if err != nil {
return
}
c.jar = jar
c.http.Jar = jar
}
func parseBody(buf []byte, priv *rsa.PrivateKey) (*Result, error) {
buf = bytes.TrimSpace(buf)
if len(buf) == 0 {
return nil, errors.New("网站返回空内容")
}
if buf[0] != '{' {
return nil, errors.New("网站没有返回账户数据")
}
var probe map[string]json.RawMessage
if err := json.Unmarshal(buf, &probe); err != nil {
return nil, errors.New("无法解析网站响应")
}
if len(probe) == 1 {
if raw, ok := probe["data"]; ok {
var s string
if json.Unmarshal(raw, &s) == nil && s != "" {
plain, err := decryptLong(priv, s)
if err != nil {
return nil, errors.New("无法解密网站响应")
}
decoded, err := decodeURIComponent(plain)
if err != nil {
return nil, err
}
buf = bytes.TrimSpace([]byte(decoded))
}
}
}
var wrap struct {
Status string `json:"status"`
Message string `json:"message"`
Data json.RawMessage `json:"data"`
}
if err := json.Unmarshal(buf, &wrap); err != nil {
return nil, errors.New("无法解析网站响应")
}
res := &Result{Status: wrap.Status, Message: wrap.Message, Data: wrap.Data}
if needLogin(wrap.Status, wrap.Message) {
if res.Message == "" {
res.Message = ErrNeedLogin.Error()
}
return res, ErrNeedLogin
}
if wrap.Status != "000000" {
return res, &APIError{Status: wrap.Status, Message: wrap.Message}
}
return res, nil
}
func needLogin(status, message string) bool {
if status == "701" {
return true
}
for _, part := range []string{"未登录", "请重新登录", "请重新登陆", "会话失效", "登录超时", "登陆超时"} {
if strings.Contains(message, part) {
return true
}
}
return false
}
func innerOK(data json.RawMessage) (bool, string) {
var m map[string]any
if err := json.Unmarshal(data, &m); err != nil {
return true, ""
}
code := asString(m["respCode"])
desc := asString(m["respDesc"])
if code == "" || code == "0000" || code == "000000" {
return true, desc
}
if desc == "" {
desc = "请求失败"
}
return false, desc
}
func marshalCompact(v any) ([]byte, error) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return nil, err
}
return bytes.TrimRight(buf.Bytes(), "\n"), nil
}
+184
View File
@@ -0,0 +1,184 @@
package cbn
import (
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math"
"net/url"
"sort"
"strconv"
"strings"
)
var errDecrypt = errors.New("无法用当前密钥解密")
func encryptLong(pub *rsa.PublicKey, plain string) (string, error) {
if pub == nil {
return "", errors.New("缺少加密公钥")
}
keyBytes := pub.Size()
maxChunk := keyBytes - 12
runes := []rune(plain)
var blocks []byte
o, a, s, c := 0, 0, 0, 0
for f, h := range runes {
add := 1
switch {
case h > 65535:
add = 4
case h > 2047:
add = 3
case h > 127:
add = 2
}
s += add
if maxChunk < s {
ct, err := rsa.EncryptPKCS1v15(rand.Reader, pub, []byte(string(runes[o:a])))
if err != nil {
return "", err
}
blocks = append(blocks, ct...)
o = a
s -= c
} else {
a = f
c = s
}
}
ct, err := rsa.EncryptPKCS1v15(rand.Reader, pub, []byte(string(runes[o:])))
if err != nil {
return "", err
}
blocks = append(blocks, ct...)
return base64.StdEncoding.EncodeToString(blocks), nil
}
func decryptLong(priv *rsa.PrivateKey, b64 string) (string, error) {
if priv == nil {
return "", errDecrypt
}
raw, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
return "", err
}
k := priv.Size()
if k == 0 || len(raw)%k != 0 {
return "", errDecrypt
}
var out []byte
for i := 0; i < len(raw); i += k {
pt, err := rsa.DecryptPKCS1v15(rand.Reader, priv, raw[i:i+k])
if err != nil {
return "", errDecrypt
}
out = append(out, pt...)
}
return string(out), nil
}
func encodeURIComponent(s string) string {
var b strings.Builder
b.Grow(len(s))
for i := 0; i < len(s); i++ {
c := s[i]
if isURIUnreserved(c) {
b.WriteByte(c)
continue
}
fmt.Fprintf(&b, "%%%02X", c)
}
return b.String()
}
func isURIUnreserved(c byte) bool {
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') {
return true
}
switch c {
case '-', '_', '.', '!', '~', '*', '\'', '(', ')':
return true
default:
return false
}
}
func decodeURIComponent(s string) (string, error) {
return url.PathUnescape(s)
}
func accessSign(payload map[string]any) string {
sum := md5.Sum([]byte(canonical(payload, false)))
return hex.EncodeToString(sum[:])
}
func canonical(v any, nested bool) string {
m, ok := asMap(v)
if !ok {
return ""
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, k := range keys {
val := m[k]
if child, ok := asMap(val); ok && !nested {
parts = append(parts, k+"="+canonical(child, true))
continue
}
if s, ok := primitive(val); ok {
parts = append(parts, k+"="+s)
}
}
return strings.Join(parts, "&")
}
func asMap(v any) (map[string]any, bool) {
m, ok := v.(map[string]any)
return m, ok
}
func primitive(v any) (string, bool) {
switch t := v.(type) {
case nil:
return "", false
case string:
if t == "" {
return "", false
}
return t, true
case bool:
if t {
return "true", true
}
return "false", true
case int:
return strconv.Itoa(t), true
case int64:
return strconv.FormatInt(t, 10), true
case float64:
if math.IsNaN(t) || math.IsInf(t, 0) {
return "", false
}
if t == math.Trunc(t) && math.Abs(t) < 1e16 {
return strconv.FormatInt(int64(t), 10), true
}
return strconv.FormatFloat(t, 'f', -1, 64), true
case json.Number:
s := t.String()
if s == "" {
return "", false
}
return s, true
default:
return "", false
}
}
+425
View File
@@ -0,0 +1,425 @@
package cbn
import (
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
)
type Snapshot struct {
Phone string `json:"phone,omitempty"`
PhoneMasked string `json:"phoneMasked,omitempty"`
Region string `json:"region,omitempty"`
PackageName string `json:"packageName,omitempty"`
OpenedAt string `json:"openedAt,omitempty"`
Cycle string `json:"cycle,omitempty"`
Balance string `json:"balance,omitempty"`
BalanceNegative bool `json:"balanceNegative,omitempty"`
MonthFee string `json:"monthFee,omitempty"`
DataTotal string `json:"dataTotal,omitempty"`
DataUsed string `json:"dataUsed,omitempty"`
DataRemain string `json:"dataRemain,omitempty"`
DataExtra string `json:"dataExtra,omitempty"`
VoiceTotal string `json:"voiceTotal,omitempty"`
VoiceRemain string `json:"voiceRemain,omitempty"`
Resources []Resource `json:"resources"`
Extras []Extra `json:"extras"`
Bills []Bill `json:"bills"`
}
type Resource struct {
Name string `json:"name"`
Used string `json:"used"`
Remain string `json:"remain"`
Total string `json:"total"`
Unit string `json:"unit"`
Percent float64 `json:"percent"`
}
type Extra struct {
Name string `json:"name"`
Used string `json:"used"`
Fee string `json:"fee"`
}
type Bill struct {
Title string `json:"title"`
Items []BillItem `json:"items"`
}
type BillItem struct {
Name string `json:"name"`
Value string `json:"value"`
}
func BuildSnapshot(phone, prov, city string, balance, bill, resource, subscribe json.RawMessage) Snapshot {
snap := Snapshot{
Resources: []Resource{},
Extras: []Extra{},
Bills: []Bill{},
}
if sub := beanOf(subscribe); sub != nil {
if phone == "" {
phone = asString(sub["accessNum"])
}
if opened := asString(sub["openDate"]); len(opened) >= 10 {
snap.OpenedAt = opened[:10]
}
if offers, ok := sub["offerList"].([]any); ok {
for _, item := range offers {
m, ok := item.(map[string]any)
if !ok {
continue
}
if asString(m["isMain"]) == "1" {
snap.PackageName = asString(m["offerName"])
break
}
}
}
}
if res := beanOf(resource); res != nil {
if list, ok := res["userResList"].([]any); ok {
for _, item := range list {
m, ok := item.(map[string]any)
if !ok {
continue
}
snap.Resources = append(snap.Resources, formatResource(m))
}
}
if list, ok := res["userExtResList"].([]any); ok {
for _, item := range list {
m, ok := item.(map[string]any)
if !ok {
continue
}
used := getFloatNumber(jsNumber(atof(asString(m["extTotalValue"])) / 1024 / 1024))
fee := toFixed2(atof(asString(m["extDiscntFee"])) / 100)
snap.Extras = append(snap.Extras, Extra{Name: "套外国内流量", Used: used, Fee: fee})
}
}
}
if bal := beanOf(balance); bal != nil {
snap.Cycle = formatCycle(asString(bal["curCycleId"]))
spay := asString(bal["spayFee"])
if spay != "" && spay != "0" {
snap.Balance = "-" + fenToYuan(spay)
snap.BalanceNegative = true
} else if asString(bal["balance"]) != "" {
snap.Balance = fenToYuan(asString(bal["balance"]))
}
if asString(bal["currealFee"]) != "" {
snap.MonthFee = fenToYuan(asString(bal["currealFee"]))
}
}
snap.Bills = formatBills(bill)
snap.DataTotal, snap.DataUsed, snap.DataRemain, snap.DataExtra = SummarizeTraffic(snap.Resources, snap.Extras)
snap.VoiceTotal, snap.VoiceRemain = SummarizeVoice(snap.Resources)
snap.Phone = strings.TrimSpace(phone)
snap.PhoneMasked = MaskPhone(snap.Phone)
snap.Region = joinRegion(prov, city)
if snap.PackageName == "" {
for _, item := range snap.Resources {
if item.Name != "" {
snap.PackageName = item.Name
break
}
}
}
return snap
}
func SummarizeTraffic(resources []Resource, extras []Extra) (total, used, remain, extra string) {
var totalN, usedN, remainN, extraN float64
var hasData bool
for _, item := range resources {
if item.Unit != "G" {
continue
}
hasData = true
totalN += atof(item.Total)
usedN += atof(item.Used)
remainN += atof(item.Remain)
}
for _, item := range extras {
extraN += atof(item.Used)
}
if !hasData && len(extras) == 0 {
return "", "", "", ""
}
return getFloatNumber(toFixed2(totalN)), getFloatNumber(toFixed2(usedN)), getFloatNumber(toFixed2(remainN)), getFloatNumber(toFixed2(extraN))
}
func SummarizeVoice(resources []Resource) (total, remain string) {
var totalN, remainN float64
var has bool
for _, item := range resources {
if item.Unit != "分钟" {
continue
}
has = true
totalN += atof(item.Total)
remainN += atof(item.Remain)
}
if !has {
return "", ""
}
return formatCount(totalN), formatCount(remainN)
}
func formatCount(n float64) string {
if n == math.Trunc(n) {
return strconv.FormatInt(int64(n), 10)
}
return getFloatNumber(toFixed2(n))
}
func formatResource(m map[string]any) Resource {
busi := asString(m["busiType"])
name := asString(m["discntName"])
high := asString(m["highFee"])
remainRaw := asString(m["balance"])
addup := asString(m["addupValue"])
if addup == "" {
addup = "0"
}
item := Resource{Name: name}
if busi == "5" {
item.Unit = "G"
item.Total = getFloatNumber(toFixed2(atof(high) / 1024 / 1024))
item.Remain = getFloatNumber(toFixed2(atof(remainRaw) / 1024 / 1024))
item.Used = subFloatToInt(item.Total, item.Remain)
} else {
if busi == "1" {
item.Unit = "分钟"
} else {
item.Unit = "条"
}
item.Total = zero(high)
item.Remain = zero(remainRaw)
item.Used = zero(addup)
}
item.Percent = percent(item.Used, item.Total)
return item
}
func formatBills(raw json.RawMessage) []Bill {
root := object(raw)
if root == nil {
return []Bill{}
}
list, ok := root["contentList"].([]any)
if !ok {
if data, ok := root["data"].(map[string]any); ok {
list, _ = data["contentList"].([]any)
}
}
if len(list) == 0 {
return []Bill{}
}
out := make([]Bill, 0, len(list))
for _, item := range list {
m, ok := item.(map[string]any)
if !ok {
continue
}
group := Bill{Title: asString(m["title"]), Items: []BillItem{}}
if rows, ok := m["list"].([]any); ok {
for _, row := range rows {
rm, ok := row.(map[string]any)
if !ok {
continue
}
group.Items = append(group.Items, BillItem{Name: asString(rm["name"]), Value: asString(rm["value"])})
}
}
out = append(out, group)
}
return out
}
func MaskPhone(phone string) string {
if len(phone) == 11 {
return phone[:3] + "****" + phone[7:]
}
return phone
}
func joinRegion(prov, city string) string {
prov = strings.TrimSpace(prov)
city = strings.TrimSpace(city)
switch {
case prov != "" && city != "":
return prov + " " + city
case prov != "":
return prov
default:
return city
}
}
func formatCycle(v string) string {
if len(v) == 6 {
return v[:4] + "-" + v[4:]
}
return v
}
func fenToYuan(s string) string {
neg := strings.HasPrefix(s, "-")
if neg {
s = strings.TrimPrefix(s, "-")
}
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return getFloatNumber(toFixed2(atof(s) / 100))
}
sign := ""
if neg {
sign = "-"
}
return fmt.Sprintf("%s%d.%02d", sign, n/100, n%100)
}
func beanOf(raw json.RawMessage) map[string]any {
root := object(raw)
if root == nil {
return nil
}
if bean, ok := root["intfResultBean"].(map[string]any); ok {
return bean
}
if data, ok := root["data"].(map[string]any); ok {
if bean, ok := data["intfResultBean"].(map[string]any); ok {
return bean
}
}
return nil
}
func object(raw json.RawMessage) map[string]any {
if len(bytesTrim(raw)) == 0 {
return nil
}
var m map[string]any
if err := json.Unmarshal(raw, &m); err != nil {
return nil
}
return m
}
func bytesTrim(raw json.RawMessage) []byte {
return []byte(strings.TrimSpace(string(raw)))
}
func asString(v any) string {
switch t := v.(type) {
case string:
return t
case float64:
if math.IsNaN(t) || math.IsInf(t, 0) {
return ""
}
if t == math.Trunc(t) && math.Abs(t) < 1e16 {
return strconv.FormatInt(int64(t), 10)
}
return strconv.FormatFloat(t, 'f', -1, 64)
case json.Number:
return t.String()
default:
return ""
}
}
func atof(s string) float64 {
f, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
if err != nil {
return 0
}
return f
}
func zero(s string) string {
if strings.TrimSpace(s) == "" {
return "0"
}
return s
}
func jsNumber(f float64) string {
return strconv.FormatFloat(f, 'f', -1, 64)
}
func toFixed2(f float64) string {
return strconv.FormatFloat(f, 'f', 2, 64)
}
func getFloatNumber(v string) string {
var b strings.Builder
for _, r := range v {
if (r >= '0' && r <= '9') || r == '.' || r == '|' {
b.WriteRune(r)
}
}
t := strings.TrimLeft(b.String(), "0")
if !strings.Contains(t, ".") {
t += ".00"
}
if strings.HasPrefix(t, ".") {
t = "0" + t
}
t += "00"
for i := 0; i < len(t); i++ {
if t[i] != '.' || i+3 > len(t) {
continue
}
j := i
for j > 0 && t[j-1] >= '0' && t[j-1] <= '9' {
j--
}
if j < i {
return t[j : i+3]
}
}
return "0.00"
}
func subFloatToInt(a, b string) string {
ra := decimalPlaces(a)
rb := decimalPlaces(b)
r := ra
if rb > r {
r = rb
}
scale := math.Pow10(r)
af := atof(a)
bf := atof(b)
return strconv.FormatFloat((af*scale-bf*scale)/scale, 'f', r, 64)
}
func decimalPlaces(s string) int {
i := strings.IndexByte(s, '.')
if i < 0 {
return 0
}
return len(s) - i - 1
}
func percent(used, total string) float64 {
u := atof(used)
t := atof(total)
if t <= 0 {
return 0
}
p := u / t * 100
if p < 0 {
return 0
}
if p > 100 {
return 100
}
return math.Round(p*10) / 10
}
+162
View File
@@ -0,0 +1,162 @@
package cbn
import (
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"os"
"regexp"
"strings"
"time"
)
const siteCacheTTL = 6 * time.Hour
var (
keyRE = regexp.MustCompile(`MII[A-Za-z0-9+/]{200,}={0,2}`)
versionRE = regexp.MustCompile(`\d+\.\d+\.\d+\.\d+_[A-Za-z0-9]+`)
channelRE = regexp.MustCompile(`channelId:"(cd_[0-9_]+)"`)
scriptRE = regexp.MustCompile(`(?i)src=["']([^"']+\.js)["']`)
)
type siteProfile struct {
ChannelID string
Version string
PublicB64 string
PrivateB64 string
Public *rsa.PublicKey
Private *rsa.PrivateKey
FetchedAt time.Time
}
type siteFile struct {
ChannelID string `json:"channelId"`
Version string `json:"version"`
PublicB64 string `json:"publicKey"`
PrivateB64 string `json:"privateKey"`
FetchedAt time.Time `json:"fetchedAt"`
}
func parseSiteJS(src string) (*siteProfile, error) {
var pub *rsa.PublicKey
var priv *rsa.PrivateKey
var pubB64, privB64 string
for _, b64 := range keyRE.FindAllString(src, -1) {
der, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
continue
}
if pub == nil {
if parsed, err := x509.ParsePKIXPublicKey(der); err == nil {
if rk, ok := parsed.(*rsa.PublicKey); ok {
pub = rk
pubB64 = b64
continue
}
}
}
if priv == nil {
if parsed, err := x509.ParsePKCS8PrivateKey(der); err == nil {
if rk, ok := parsed.(*rsa.PrivateKey); ok {
priv = rk
privB64 = b64
continue
}
}
if rk, err := x509.ParsePKCS1PrivateKey(der); err == nil {
priv = rk
privB64 = b64
}
}
}
if pub == nil || priv == nil {
return nil, errors.New("页面脚本里没有找到加密密钥")
}
ver := versionRE.FindString(src)
ch := channelRE.FindStringSubmatch(src)
if ver == "" || ch == nil {
return nil, errors.New("页面脚本里没有找到渠道或版本号")
}
return &siteProfile{
ChannelID: ch[1],
Version: ver,
PublicB64: pubB64,
PrivateB64: privB64,
Public: pub,
Private: priv,
FetchedAt: time.Now(),
}, nil
}
func scriptURLs(html string) []string {
matches := scriptRE.FindAllStringSubmatch(html, -1)
var common, rest []string
seen := map[string]bool{}
for _, m := range matches {
u := m[1]
if seen[u] {
continue
}
seen[u] = true
if strings.Contains(u, "common-") {
common = append(common, u)
continue
}
rest = append(rest, u)
}
return append(common, rest...)
}
func resolveURL(ref string) string {
if strings.HasPrefix(ref, "https://") || strings.HasPrefix(ref, "http://") {
return ref
}
if strings.HasPrefix(ref, "//") {
return "https:" + ref
}
if strings.HasPrefix(ref, "/") {
return origin + ref
}
return origin + "/" + ref
}
func loadSiteCache(path string) (*siteProfile, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var file siteFile
if err := json.Unmarshal(b, &file); err != nil {
return nil, err
}
p, err := parseSiteJS(`channelId:"` + file.ChannelID + `" v="` + file.Version + `" "` + file.PublicB64 + `" "` + file.PrivateB64 + `"`)
if err != nil {
return nil, err
}
p.FetchedAt = file.FetchedAt
return p, nil
}
func saveSiteCache(path string, p *siteProfile) error {
buf, err := json.MarshalIndent(siteFile{
ChannelID: p.ChannelID,
Version: p.Version,
PublicB64: p.PublicB64,
PrivateB64: p.PrivateB64,
FetchedAt: p.FetchedAt,
}, "", " ")
if err != nil {
return err
}
buf = append(buf, '\n')
if err := os.MkdirAll("data", 0755); err != nil {
return err
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, buf, 0600); err != nil {
return err
}
return os.Rename(tmp, path)
}
+112
View File
@@ -0,0 +1,112 @@
package cbn
import (
"errors"
"strings"
"time"
"github.com/dop251/goja"
)
// 只在返回人机校验页时执行官网自己的脚本,平时的查询走 Go,不常驻解释器。
func solveACW(html string) (string, error) {
parts := extractScripts(html)
if len(parts) < 2 {
return "", errors.New("校验脚本不完整")
}
render := extractTextarea(html, "renderData")
if render == "" {
return "", errors.New("校验页面缺少参数")
}
vm := goja.New()
timer := time.AfterFunc(3*time.Second, func() { vm.Interrupt("timeout") })
defer timer.Stop()
if err := vm.Set("RENDER_HTML", render); err != nil {
return "", err
}
if err := vm.Set("UA", userAgent); err != nil {
return "", err
}
if _, err := vm.RunString(wafPrelude); err != nil {
return "", err
}
if _, err := vm.RunString(parts[0]); err != nil {
return "", errors.New("校验脚本无法执行")
}
if _, err := vm.RunString(`window.arg1 = arg1; var __old = reload; reload = function(v){ __token = String(v); try { __old(v); } catch (e) {} }; window.reload = reload;`); err != nil {
return "", errors.New("校验脚本无法执行")
}
if _, err := vm.RunString(parts[1]); err != nil {
return "", errors.New("校验计算失败")
}
v := vm.Get("__token")
if v == nil || goja.IsUndefined(v) || goja.IsNull(v) {
return "", errors.New("校验脚本没有给出凭证")
}
token := v.String()
if token == "" || token == "undefined" || !strings.Contains(token, "-") {
return "", errors.New("校验脚本没有给出凭证")
}
return token, nil
}
const wafPrelude = `
var __token = "";
var document = {
referrer: "https://www.10099.com.cn/login.html",
getElementById: function() { return { innerHTML: RENDER_HTML }; },
location: { href: "https://www.10099.com.cn/login.html", reload: function() {} }
};
var location = document.location;
var navigator = {
userAgent: UA,
webdriver: false,
language: "zh-CN",
languages: ["zh-CN", "zh"],
platform: "Win32",
hardwareConcurrency: 8,
plugins: { length: 0 }
};
var window = { document: document, location: location, navigator: navigator };
`
func extractScripts(html string) []string {
var out []string
rest := html
for {
i := strings.Index(rest, "<script")
if i < 0 {
break
}
rest = rest[i:]
j := strings.Index(rest, ">")
k := strings.Index(rest, "</script>")
if j < 0 || k < 0 || k < j {
break
}
body := strings.TrimSpace(rest[j+1 : k])
if body != "" {
out = append(out, body)
}
rest = rest[k+9:]
}
return out
}
func extractTextarea(html, id string) string {
marker := `id="` + id + `"`
i := strings.Index(html, marker)
if i < 0 {
marker = `id='` + id + `'`
i = strings.Index(html, marker)
}
if i < 0 {
return ""
}
gt := strings.Index(html[i:], ">")
end := strings.Index(html[i:], "</textarea>")
if gt < 0 || end < 0 || end < gt {
return ""
}
return html[i+gt+1 : i+end]
}
+692
View File
@@ -0,0 +1,692 @@
package main
import (
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
_ "time/tzdata"
"cbnsmsinfo/internal/cbn"
)
//go:embed web/index.html
var indexPage []byte
const statePath = "data/state.json"
type Config struct {
Listen string `json:"listen"`
PollInterval string `json:"pollInterval"`
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"`
}
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"`
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
pollText string
cfgPhone string
kick chan struct{}
mu sync.Mutex
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
}
app := newApp(cbn.New(), strings.TrimSpace(cfg.Phone), interval)
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 /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 time.Duration) *App {
return &App{
client: client,
interval: interval,
pollText: humanInterval(interval),
cfgPhone: phone,
kick: make(chan struct{}, 1),
snap: cbn.Snapshot{
Resources: []cbn.Resource{},
Extras: []cbn.Extra{},
Bills: []cbn.Bill{},
},
}
}
func (a *App) loop(ctx context.Context) {
timer := time.NewTimer(a.currentInterval())
stopTimer(timer)
if a.isLoggedIn() {
a.stampNext()
a.refresh()
timer.Reset(a.currentInterval())
}
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-a.kick:
stopTimer(timer)
if a.isLoggedIn() {
timer.Reset(a.currentInterval())
}
case <-timer.C:
if !a.isLoggedIn() {
continue
}
a.stampNext()
a.refresh()
if a.isLoggedIn() {
timer.Reset(a.currentInterval())
}
}
}
}
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() {
a.mu.Lock()
if !a.loggedIn || a.sessionID == "" || a.phone == "" {
a.mu.Unlock()
return
}
if a.refreshing {
a.mu.Unlock()
return
}
a.refreshing = true
phone, sid, prov, city := a.phone, a.sessionID, a.prov, a.city
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()
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},
}
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
}
if err != nil {
errs = append(errs, item.name+":"+err.Error())
continue
}
*item.raw = 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 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(errs) == 0 {
a.refreshedAt = time.Now()
log.Printf("同步完成 %s", snap.PhoneMasked)
}
}
func (a *App) markLoggedOut(msg string) {
a.client.Reset()
a.mu.Lock()
a.loggedIn = false
a.sessionID = ""
a.snap = emptySnap()
a.stale = false
a.refreshedAt = time.Time{}
a.lastError = msg
a.nextAt = time.Time{}
a.mu.Unlock()
}
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()
}
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
}
a.mu.Lock()
a.phone = phone
a.mu.Unlock()
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.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"`
}
if err := decode(r, &req); err != nil || req.Minutes < 1 || req.Minutes > 1440 {
writeErr(w, "间隔需在 1 到 1440 分钟之间")
return
}
a.mu.Lock()
a.interval = time.Duration(req.Minutes) * time.Minute
a.pollText = humanInterval(a.interval)
if a.loggedIn {
a.nextAt = time.Now().Add(a.interval)
}
a.mu.Unlock()
select {
case a.kick <- struct{}{}:
default:
}
a.save()
writeJSON(w, http.StatusOK, a.view())
}
func (a *App) currentInterval() time.Duration {
a.mu.Lock()
defer a.mu.Unlock()
if a.interval < time.Minute {
return 30 * time.Minute
}
return a.interval
}
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),
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
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)
}
a.client.ImportCookies(st.Cookies)
if a.loggedIn {
log.Printf("已恢复会话 %s", cbn.MaskPhone(a.phone))
}
}
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),
}
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.nextAt = time.Now().Add(a.interval)
a.mu.Unlock()
}
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_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
}
+757
View File
@@ -0,0 +1,757 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>广电账户</title>
<style>
:root {
--bg: #eef1f6;
--card: #fff;
--ink: #1b2433;
--muted: #6b7585;
--line: #e4e9f0;
--accent: #1d4f91;
--ok: #0f7b4c;
--ok-bg: #e7f6ee;
--warn: #9a6700;
--warn-bg: #fff4d6;
--busy-bg: #e7f0fb;
--danger: #b42318;
--danger-bg: #fdeceb;
--shadow: 0 8px 24px rgba(23, 32, 51, 0.06);
}
* { box-sizing: border-box; }
html, body { margin: 0; }
body {
min-height: 100vh;
background: var(--bg);
color: var(--ink);
font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
}
main {
width: min(880px, calc(100% - 24px));
margin: 0 auto;
padding: 20px 0 28px;
}
body.guest {
display: flex;
align-items: center;
}
body.guest main {
width: min(340px, calc(100% - 24px));
padding: 24px 0;
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
h1 { margin: 0; font-size: 22px; font-weight: 650; letter-spacing: -0.03em; }
.menu { position: relative; }
body.guest #menu { display: none; }
.menu-list {
position: absolute;
right: 0;
top: calc(100% + 6px);
min-width: 112px;
padding: 6px;
background: #fff;
border: 1px solid var(--line);
border-radius: 10px;
box-shadow: var(--shadow);
display: flex;
flex-direction: column;
z-index: 5;
}
.menu-list[hidden] { display: none; }
.menu-list button {
width: 100%;
height: 34px;
border: 0;
background: transparent;
text-align: left;
}
.menu-list button:hover { background: #f3f6fa; }
.brand-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.countdown[hidden] { display: none !important; }
.countdown {
color: rgba(255, 255, 255, 0.92);
font-size: 13px;
font-variant-numeric: tabular-nums;
letter-spacing: 0.04em;
}
.mask {
position: fixed;
inset: 0;
z-index: 20;
display: flex;
align-items: center;
justify-content: center;
background: rgba(20, 28, 40, 0.35);
}
.mask[hidden] { display: none; }
.dialog { width: min(320px, calc(100% - 32px)); padding: 16px; }
.dialog h2 { margin: 0 0 12px; font-size: 16px; }
.dialog-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; }
.dialog .primary { width: auto; margin: 0; height: 32px; }
#settingsMsg { min-height: 18px; margin: 8px 0 0; font-size: 12px; color: var(--danger); }
.ask { margin: 0; color: var(--muted); font-size: 14px; }
#verify[hidden] { display: none; }
button {
height: 32px;
padding: 0 12px;
border-radius: 8px;
border: 1px solid var(--line);
background: #fff;
color: var(--ink);
font: inherit;
font-size: 13px;
cursor: pointer;
}
button:hover { border-color: #c5d0de; }
button:disabled { opacity: 0.55; cursor: default; }
button.primary {
width: 100%;
height: 38px;
margin-top: 4px;
border-color: var(--accent);
background: var(--accent);
color: #fff;
font-weight: 650;
}
button.primary:hover { background: #163f78; }
.banner {
margin: 0 0 10px;
padding: 8px 10px;
border-radius: 8px;
background: var(--danger-bg);
color: var(--danger);
font-size: 13px;
}
.card { background: var(--card); border-radius: 12px; box-shadow: var(--shadow); }
#login { width: min(340px, 100%); margin: 0 auto; padding: 16px 14px 14px; }
#login h2 { margin: 0 0 12px; font-size: 16px; font-weight: 650; }
.field { margin-bottom: 10px; }
label { display: block; margin-bottom: 4px; color: var(--muted); font-size: 12px; }
.login-row {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
}
.login-row > label {
width: 72px;
flex: none;
margin: 0;
text-align: right;
line-height: 1.2;
}
.login-row .control { flex: 1; min-width: 0; display: flex; gap: 6px; align-items: center; }
.login-row .control input { width: auto; flex: 1; min-width: 0; height: 32px; }
input[type="text"], input[type="tel"], input[type="number"], input:not([type]) {
width: 100%;
height: 36px;
padding: 0 10px;
border: 1px solid #d7dee8;
border-radius: 8px;
background: #fff;
color: var(--ink);
font: inherit;
font-size: 14px;
}
input:focus { outline: 2px solid rgba(29, 79, 145, 0.16); border-color: #8eadd4; }
#captcha {
width: 86px;
height: 32px;
flex: none;
border-radius: 8px;
border: 1px solid #d7dee8;
background: #f6f8fb;
object-fit: contain;
cursor: pointer;
}
#smsBtn { flex: none; height: 32px; padding: 0 8px; }
#loginMsg { min-height: 18px; margin: 8px 0 0; font-size: 12px; color: var(--danger); }
#loginMsg.ok { color: var(--ok); }
.hero { display: grid; grid-template-columns: 220px 1fr; overflow: hidden; margin-bottom: 10px; }
.identity { padding: 16px 18px; background: #173a6b; color: #fff; }
.brand { font-size: 12px; letter-spacing: 0.06em; opacity: 0.85; }
.phone { margin-top: 8px; font-size: 26px; font-weight: 650; font-variant-numeric: tabular-nums; }
.pkg { margin-top: 6px; font-size: 13px; }
.region { margin-top: 4px; font-size: 12px; opacity: 0.75; }
.figures { display: flex; flex-direction: column; min-width: 0; }
.money {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
.figure { padding: 12px 16px; }
.figure + .figure { border-left: 1px solid var(--line); }
.figure span, .metric span { display: block; color: var(--muted); font-size: 12px; }
.figure strong, .metric strong {
display: inline;
font-size: 26px;
font-weight: 650;
letter-spacing: -0.03em;
font-variant-numeric: tabular-nums;
}
.figure em, .metric em { margin-left: 2px; font-style: normal; font-size: 12px; color: var(--muted); }
.figure.negative strong { color: var(--danger); }
.traffic {
display: grid;
grid-template-columns: repeat(4, 1fr);
border-top: 1px solid var(--line);
}
.metric { padding: 10px 16px; }
.metric + .metric { border-left: 1px solid var(--line); }
.metric strong { font-size: 18px; }
.block { padding: 12px 14px 4px; margin-bottom: 10px; }
.block h2 { margin: 0 0 2px; font-size: 14px; font-weight: 650; }
.row {
display: grid;
grid-template-columns: minmax(96px, 1fr) auto minmax(72px, 120px) auto;
gap: 10px;
align-items: center;
padding: 9px 0;
border-top: 1px solid var(--line);
font-size: 13px;
}
.name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.used, .remain { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; }
.remain { text-align: right; }
.bar { height: 5px; border-radius: 99px; background: #e7edf5; overflow: hidden; }
.bar i { display: block; height: 100%; border-radius: inherit; background: #2f6fed; }
.bar i.hot { background: #d97706; }
.extra, .bill-row {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 8px 0;
border-top: 1px solid var(--line);
font-size: 13px;
}
.extra span, .bill-row span { color: var(--muted); }
.bill-title { margin: 10px 0 0; font-size: 12px; color: var(--muted); }
#pending { padding: 16px; margin-bottom: 10px; color: var(--muted); font-size: 13px; }
#dash.stale { opacity: 0.72; }
@media (max-width: 720px) {
header { align-items: flex-start; flex-direction: column; }
.hero { grid-template-columns: 1fr; }
.money, .traffic { grid-template-columns: 1fr 1fr; }
.figure + .figure { border-left: 0; border-top: 1px solid var(--line); }
.traffic .metric { border-left: 0; border-top: 0; }
.traffic .metric:nth-child(even) { border-left: 1px solid var(--line); }
.traffic .metric:nth-child(n + 3) { border-top: 1px solid var(--line); }
.row { grid-template-columns: 1fr auto; }
.bar, .remain { grid-column: 1 / -1; }
.remain { text-align: left; }
}
</style>
</head>
<body class="guest">
<main>
<header>
<h1>广电账户</h1>
<div class="menu" id="menu" hidden>
<button id="menuBtn" type="button" aria-expanded="false" aria-controls="menuList">更多</button>
<div id="menuList" class="menu-list" hidden>
<button id="settingsBtn" type="button">设置</button>
<button id="refresh" type="button">刷新</button>
<button id="logout" type="button">退出</button>
</div>
</div>
</header>
<p id="error" class="banner" hidden></p>
<section id="login" class="card">
<h2>登录</h2>
<form id="form">
<div class="login-row">
<label for="phone">手机号</label>
<div class="control">
<input id="phone" type="tel" inputmode="numeric" autocomplete="tel" maxlength="11">
</div>
</div>
<div id="verify">
<div class="login-row">
<label for="imageCode">图形验证码</label>
<div class="control">
<input id="imageCode" autocomplete="off" maxlength="8">
<img id="captcha" alt="图形验证码" title="点击更换">
</div>
</div>
<div class="login-row">
<label for="sms">短信验证码</label>
<div class="control">
<input id="sms" inputmode="numeric" autocomplete="one-time-code" maxlength="8">
<button id="smsBtn" type="button">获取</button>
</div>
</div>
</div>
<p id="loginMsg"></p>
<button id="submit" class="primary" type="submit">登录</button>
</form>
</section>
<section id="pending" class="card" hidden>读取中</section>
<section id="dash" hidden>
<article class="hero card">
<div class="identity">
<div class="brand-row">
<div class="brand">广电 5G</div>
<span id="countdown" class="countdown" hidden></span>
</div>
<div id="phoneText" class="phone">—</div>
<div id="pkgText" class="pkg"></div>
<div id="regionText" class="region"></div>
</div>
<div class="figures">
<div class="money">
<div id="balanceBox" class="figure">
<span id="cycleText">话费余额</span>
<div><strong id="balanceText">—</strong><em>元</em></div>
</div>
<div class="figure">
<span>当月消费</span>
<div><strong id="feeText">—</strong><em>元</em></div>
</div>
<div class="figure">
<span>语音总量</span>
<div><strong id="voiceTotal">—</strong><em>分钟</em></div>
</div>
<div class="figure">
<span>语音剩余</span>
<div><strong id="voiceRemain">—</strong><em>分钟</em></div>
</div>
</div>
<div class="traffic">
<div class="metric"><span>总流量</span><div><strong id="dataTotal">—</strong><em>G</em></div></div>
<div class="metric"><span>已用流量</span><div><strong id="dataUsed">—</strong><em>G</em></div></div>
<div class="metric"><span>剩余流量</span><div><strong id="dataRemain">—</strong><em>G</em></div></div>
<div class="metric"><span>套外流量</span><div><strong id="dataExtra">—</strong><em>G</em></div></div>
</div>
</div>
</article>
<section id="usageCard" class="block card">
<h2>套餐余量</h2>
<div id="usage"></div>
</section>
<section id="extraCard" class="block card" hidden>
<h2>套餐外</h2>
<div id="extras"></div>
</section>
<section id="billCard" class="block card" hidden>
<h2>账单</h2>
<div id="bills"></div>
</section>
</section>
<div id="logoutAsk" class="mask" hidden>
<div class="dialog card" role="dialog" aria-labelledby="logoutTitle">
<h2 id="logoutTitle">退出账号</h2>
<p class="ask">是否退出当前账号?</p>
<div class="dialog-actions">
<button id="logoutCancel" type="button">取消</button>
<button id="logoutConfirm" class="primary" type="button">退出</button>
</div>
</div>
</div>
<div id="settings" class="mask" hidden>
<div class="dialog card" role="dialog" aria-labelledby="settingsTitle">
<h2 id="settingsTitle">同步间隔</h2>
<div class="field">
<label for="pollMinutes">分钟</label>
<input id="pollMinutes" type="number" min="1" max="1440" inputmode="numeric" value="30">
</div>
<p id="settingsMsg"></p>
<div class="dialog-actions">
<button id="settingsCancel" type="button">取消</button>
<button id="settingsSave" class="primary" type="button">保存</button>
</div>
</div>
</div>
</main>
<script>
const $ = (id) => document.getElementById(id);
let lastKey = "";
let captchaReady = false;
let smsLeft = 0;
let smsTimer = 0;
let deadline = 0;
let loggedIn = false;
let canResume = false;
let savedPhone = "";
function textOrDash(v) {
return v === undefined || v === null || v === "" ? "—" : v;
}
function loadCaptcha() {
$("captcha").src = "/api/captcha?t=" + Date.now();
}
function setLoginMsg(text, ok) {
const el = $("loginMsg");
el.textContent = text || "";
el.className = ok ? "ok" : "";
}
function render(data) {
const key = JSON.stringify(data);
if (key === lastKey) return;
lastKey = key;
loggedIn = !!data.loggedIn;
$("menu").hidden = !data.loggedIn;
$("countdown").hidden = !data.loggedIn;
$("refresh").disabled = !!data.refreshing;
if (!data.loggedIn) $("menuList").hidden = true;
$("login").hidden = !data.needLogin;
document.body.classList.toggle("guest", !data.loggedIn);
$("pending").hidden = !(data.loggedIn && !data.hasData);
$("dash").hidden = !data.loggedIn || !data.hasData;
if (data.loggedIn) {
deadline = Date.now() + Math.max(0, Number(data.secondsLeft) || 0) * 1000;
} else {
deadline = 0;
}
paintCountdown();
syncPoll(!!data.loggedIn);
$("dash").classList.toggle("stale", !!(data.stale && data.hasData && !data.loggedIn));
$("error").hidden = !data.error;
$("error").textContent = data.error || "";
if ($("settings").hidden && data.pollMinutes) {
$("pollMinutes").value = data.pollMinutes;
}
canResume = !!data.canResume;
if (data.phone) savedPhone = data.phone;
if (!$("phone").value && data.phone) $("phone").value = data.phone;
const reuse = canResume && $("phone").value.trim() === savedPhone;
$("verify").hidden = !data.needLogin || reuse;
if (data.needLogin && !reuse && !captchaReady) {
loadCaptcha();
captchaReady = true;
}
if (!data.needLogin) captchaReady = false;
$("phoneText").textContent = data.phoneMasked || "—";
$("pkgText").textContent = data.packageName || "";
const regionBits = [];
if (data.region) regionBits.push(data.region);
if (data.openedAt) regionBits.push(data.openedAt);
$("regionText").textContent = regionBits.join(" · ");
$("cycleText").textContent = data.cycle ? "话费余额 · " + data.cycle : "话费余额";
$("balanceText").textContent = textOrDash(data.balance);
$("balanceBox").classList.toggle("negative", !!data.balanceNegative);
$("feeText").textContent = textOrDash(data.monthFee);
$("voiceTotal").textContent = textOrDash(data.voiceTotal);
$("voiceRemain").textContent = textOrDash(data.voiceRemain);
$("dataTotal").textContent = textOrDash(data.dataTotal);
$("dataUsed").textContent = textOrDash(data.dataUsed);
$("dataRemain").textContent = textOrDash(data.dataRemain);
$("dataExtra").textContent = textOrDash(data.dataExtra);
const usage = $("usage");
usage.replaceChildren();
(data.resources || []).forEach((item) => {
const row = document.createElement("div");
row.className = "row";
const name = document.createElement("div");
name.className = "name";
name.title = item.name || "";
name.textContent = item.name || "";
const used = document.createElement("div");
used.className = "used";
used.textContent = item.used + " " + item.unit;
const bar = document.createElement("div");
bar.className = "bar";
const fill = document.createElement("i");
const pct = Math.max(0, Math.min(100, Number(item.percent) || 0));
fill.style.width = pct + "%";
if (pct >= 85) fill.className = "hot";
bar.appendChild(fill);
const remain = document.createElement("div");
remain.className = "remain";
remain.textContent = item.remain + " / " + item.total + " " + item.unit;
row.append(name, used, bar, remain);
usage.appendChild(row);
});
$("usageCard").hidden = !(data.resources || []).length;
const extras = $("extras");
extras.replaceChildren();
(data.extras || []).forEach((item) => {
const row = document.createElement("div");
row.className = "extra";
const left = document.createElement("span");
left.textContent = item.used + " G";
const right = document.createElement("strong");
right.textContent = item.fee + " 元";
row.append(left, right);
extras.appendChild(row);
});
$("extraCard").hidden = !(data.extras || []).length;
const bills = $("bills");
bills.replaceChildren();
(data.bills || []).forEach((group) => {
const title = document.createElement("div");
title.className = "bill-title";
title.textContent = group.title || "";
bills.appendChild(title);
(group.items || []).forEach((item) => {
const row = document.createElement("div");
row.className = "bill-row";
const left = document.createElement("span");
left.textContent = item.name || "";
const right = document.createElement("strong");
right.textContent = item.value == null ? "" : String(item.value);
row.append(left, right);
bills.appendChild(row);
});
});
$("billCard").hidden = !(data.bills || []).length;
}
let pollTimer = 0;
function syncPoll(on) {
if (on && !pollTimer) {
pollTimer = setInterval(pull, 8000);
return;
}
if (!on && pollTimer) {
clearInterval(pollTimer);
pollTimer = 0;
}
}
async function pull() {
try {
const res = await fetch("/api/overview", { cache: "no-store" });
render(await res.json());
} catch (err) {
$("error").hidden = false;
$("error").textContent = "连接失败";
}
}
async function saveInterval() {
const minutes = Number($("pollMinutes").value);
if (!Number.isInteger(minutes) || minutes < 1 || minutes > 1440) {
$("settingsMsg").textContent = "需在 1 到 1440 之间";
return;
}
const res = await fetch("/api/interval", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ minutes })
});
const data = await res.json();
if (!res.ok) {
$("settingsMsg").textContent = data.message || "未保存";
return;
}
$("settings").hidden = true;
lastKey = "";
render(data);
}
function paintCountdown() {
const el = $("countdown");
if (!loggedIn || !deadline) {
el.hidden = true;
return;
}
const left = Math.max(0, Math.round((deadline - Date.now()) / 1000));
const m = String(Math.floor(left / 60)).padStart(2, "0");
const s = String(left % 60).padStart(2, "0");
el.hidden = false;
el.textContent = m + ":" + s;
}
function closeMenu() {
$("menuList").hidden = true;
$("menuBtn").setAttribute("aria-expanded", "false");
}
$("menuBtn").addEventListener("click", (event) => {
event.stopPropagation();
const open = $("menuList").hidden;
$("menuList").hidden = !open;
$("menuBtn").setAttribute("aria-expanded", open ? "true" : "false");
});
document.addEventListener("click", () => closeMenu());
$("menuList").addEventListener("click", (event) => event.stopPropagation());
$("settingsBtn").addEventListener("click", () => {
closeMenu();
$("settingsMsg").textContent = "";
$("settings").hidden = false;
$("pollMinutes").focus();
});
$("settingsCancel").addEventListener("click", () => { $("settings").hidden = true; });
$("settings").addEventListener("click", (event) => {
if (event.target === $("settings")) $("settings").hidden = true;
});
$("settingsSave").addEventListener("click", () => { saveInterval().catch(() => {}); });
$("captcha").addEventListener("click", () => { loadCaptcha(); captchaReady = true; });
$("captcha").addEventListener("error", () => { setLoginMsg("验证码加载失败"); });
$("smsBtn").addEventListener("click", async () => {
const phone = $("phone").value.trim();
if (!/^1\d{10}$/.test(phone)) { setLoginMsg("手机号不正确"); return; }
$("smsBtn").disabled = true;
setLoginMsg("");
try {
const res = await fetch("/api/sms", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ phone })
});
const data = await res.json();
if (!res.ok || data.ok === false) {
setLoginMsg(data.message || "发送失败");
$("smsBtn").disabled = false;
return;
}
setLoginMsg("已发送", true);
smsLeft = 60;
$("smsBtn").textContent = smsLeft + "s";
clearInterval(smsTimer);
smsTimer = setInterval(() => {
smsLeft -= 1;
if (smsLeft <= 0) {
clearInterval(smsTimer);
$("smsBtn").disabled = false;
$("smsBtn").textContent = "获取";
return;
}
$("smsBtn").textContent = smsLeft + "s";
}, 1000);
} catch (err) {
setLoginMsg("发送失败");
$("smsBtn").disabled = false;
}
});
$("phone").addEventListener("input", () => {
const reuse = canResume && $("phone").value.trim() === savedPhone;
$("verify").hidden = reuse;
if (!reuse && !captchaReady) {
loadCaptcha();
captchaReady = true;
}
});
$("form").addEventListener("submit", async (event) => {
event.preventDefault();
const phone = $("phone").value.trim();
const imageCode = $("imageCode").value.trim();
const smsCode = $("sms").value.trim();
if (!/^1\d{10}$/.test(phone)) return setLoginMsg("手机号不正确");
if ($("verify").hidden) {
$("submit").disabled = true;
$("submit").textContent = "登录中";
setLoginMsg("");
try {
const res = await fetch("/api/resume", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ phone })
});
const data = await res.json();
if (data.ok) {
lastKey = "";
await pull();
return;
}
$("verify").hidden = false;
loadCaptcha();
captchaReady = true;
canResume = false;
setLoginMsg(data.message || "需要重新登录");
} catch (err) {
setLoginMsg("登录失败");
} finally {
$("submit").disabled = false;
$("submit").textContent = "登录";
}
return;
}
if (!imageCode) return setLoginMsg("请填写图形验证码");
if (!smsCode) return setLoginMsg("请填写短信验证码");
$("submit").disabled = true;
$("submit").textContent = "登录中";
setLoginMsg("");
try {
const res = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ phone, imageCode, smsCode })
});
const data = await res.json();
if (!res.ok || data.ok === false) {
setLoginMsg(data.message || "登录失败");
loadCaptcha();
return;
}
$("imageCode").value = "";
$("sms").value = "";
lastKey = "";
await pull();
} catch (err) {
setLoginMsg("登录失败");
} finally {
$("submit").disabled = false;
$("submit").textContent = "登录";
}
});
$("refresh").addEventListener("click", async () => {
closeMenu();
$("refresh").disabled = true;
try {
const res = await fetch("/api/refresh", { method: "POST" });
lastKey = "";
render(await res.json());
} catch (err) {
$("error").hidden = false;
$("error").textContent = "刷新失败";
} finally {
$("refresh").disabled = false;
}
});
$("logout").addEventListener("click", () => {
closeMenu();
$("logoutAsk").hidden = false;
});
$("logoutCancel").addEventListener("click", () => { $("logoutAsk").hidden = true; });
$("logoutAsk").addEventListener("click", (event) => {
if (event.target === $("logoutAsk")) $("logoutAsk").hidden = true;
});
$("logoutConfirm").addEventListener("click", async () => {
$("logoutConfirm").disabled = true;
try {
const res = await fetch("/api/logout", { method: "POST" });
$("logoutAsk").hidden = true;
lastKey = "";
$("imageCode").value = "";
$("sms").value = "";
setLoginMsg("");
render(await res.json());
} finally {
$("logoutConfirm").disabled = false;
}
});
pull();
setInterval(paintCountdown, 1000);
</script>
</body>
</html>