feat: 实现联通话费余量只读面板

This commit is contained in:
Nixevol
2026-10-16 16:12:52 +08:00
commit a67e19d333
18 changed files with 2401 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
data/
config.json
*.exe
*.chlz
Temp/
+39
View File
@@ -0,0 +1,39 @@
# 联通账户
给自己的中国联通号码看可用余额、实时话费和套餐余量。页面只读,登录后按设定间隔自动刷新。登录可以用短信验证码,也可以用中国联通 App 扫页面上的二维码。
页面没有访问口令,只放在自己的机器上。
## 使用
程序从当前工作目录读取 `config.json` 并写入 `data/`。先进入程序所在目录再启动,浏览器打开它监听的地址。
```json
{
"listen": ":8786",
"pollInterval": "30m",
"jitterMinutes": 0,
"phone": ""
}
```
| 字段 | 作用 |
| --- | --- |
| `listen` | 监听地址,默认 `:8786` |
| `pollInterval` | 登录后的基础刷新间隔,最短 1 分钟 |
| `jitterMinutes` | 每次额外随机增加 0 到这个分钟数。0 表示不加 |
| `phone` | 可选。写上后登录页会预先填好号码 |
环境变量 `CU_LISTEN`、`CU_POLL`、`CU_JITTER`、`CU_PHONE` 会覆盖同名字段。
短信登录先填手机号,点获取短信并完成验证码,再填写短信验证码。扫码登录点「扫码」,用中国联通 App 扫二维码并在手机上确认。退出后立即清除本次登录状态。重新打开程序不会恢复上次登录。
登录公钥、验证码应用编号、扫码地址,以及话费和余量接口,都从网站当前页面和脚本里读取。
## 编译
需要 Go 1.26 或更高。
```bash
go build -trimpath -ldflags="-s -w" -o cu-dashboard .
```
+6
View File
@@ -0,0 +1,6 @@
{
"listen": ":8786",
"pollInterval": "30m",
"jitterMinutes": 0,
"phone": ""
}
+3
View File
@@ -0,0 +1,3 @@
module cusiminfo
go 1.26.0
+747
View File
@@ -0,0 +1,747 @@
package unicom
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"sort"
"strings"
"sync"
"time"
)
const (
uacOrigin = "https://uac.10010.com"
servicePage = "https://iservice.10010.com/e5/query.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"
feeMarker = "/balancenew/accountBalancenew.htm"
planMarker = "/operationservice/queryOcsPackageFlowLeftContentRevisedInJune"
)
var ErrNeedLogin = errors.New("会话已失效")
type LoginResult struct {
Phone string
}
type QRStatus struct {
Waiting bool
Scanned bool
Expired bool
Message string
Result LoginResult
}
type Client struct {
mu sync.Mutex
http *http.Client
jar *cookiejar.Jar
spec loginScript
captchaScript string
loginReferer string
fee billAPI
plan billAPI
qrSec string
loginReady bool
}
func New() (*Client, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
return &Client{
jar: jar,
http: &http.Client{
Jar: jar,
Timeout: 30 * time.Second,
},
}, nil
}
func (c *Client) Prepare(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.prepareLogin(ctx)
}
func (c *Client) Captcha() (script, appID string) {
c.mu.Lock()
defer c.mu.Unlock()
return c.captchaScript, c.spec.captchaAppID
}
func (c *Client) Reset() {
c.mu.Lock()
defer c.mu.Unlock()
jar, err := cookiejar.New(nil)
if err != nil {
return
}
c.jar = jar
c.http.Jar = jar
c.qrSec = ""
c.loginReady = false
}
func (c *Client) SendSMS(ctx context.Context, phone, ticket, randstr string) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.prepareLogin(ctx); err != nil {
return "", err
}
c.dropAccount()
debugf("发送短信 phone=%s randstr=%s ticket=%s", phone, randstr, ticket)
body, err := c.get(ctx, c.loginURL(c.spec.sendPath, url.Values{
"req_time": {milli()},
"mobile": {phone},
"uvc": {ticket},
"verifyCode": {randstr},
}), c.loginReferer)
if err != nil {
return "", err
}
return smsMessage(body)
}
func (c *Client) Login(ctx context.Context, phone, smsCode, ticket, randstr string) (LoginResult, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.prepareLogin(ctx); err != nil {
return LoginResult{}, err
}
c.dropAccount()
password, err := encryptPassword(c.spec.exponent, c.spec.modulus, smsCode)
if err != nil {
return LoginResult{}, err
}
debugf("短信登录 phone=%s sms=%s", phone, smsCode)
q := url.Values{
"req_time": {milli()},
"redirectURL": {servicePage},
"userName": {phone},
"password": {password},
"pwdType": {c.spec.pwdType},
"productType": {c.spec.userType},
"uvc": {ticket},
"verifyCode": {randstr},
"redirectType": {c.spec.redirectType},
"rememberMe": {"1"},
}
body, err := c.get(ctx, c.loginURL(c.spec.loginPath, q), c.loginReferer)
if err != nil {
return LoginResult{}, err
}
data, err := parseJSONP(string(body))
if err != nil {
return LoginResult{}, err
}
code := asString(data["resultCode"])
if code != "0000" && code != "0301" {
return LoginResult{}, bizError(code, data, "登录失败")
}
if err := c.land(ctx, asString(data["redirectURL"])); err != nil {
return LoginResult{}, err
}
return LoginResult{Phone: phone}, nil
}
func (c *Client) QRCode(ctx context.Context) ([]byte, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.prepareLogin(ctx); err != nil {
return nil, err
}
if c.spec.genQRPath == "" {
return nil, errors.New("登录脚本里没有扫码地址")
}
raw := uacOrigin + c.spec.genQRPath + "?timestamp=" + milli()
body, ctype, err := c.do(ctx, http.MethodGet, raw, c.loginReferer, nil, nil)
if err != nil {
return nil, err
}
if !strings.Contains(ctype, "image") && !(len(body) > 2 && body[0] == 0xff && body[1] == 0xd8) {
return nil, errors.New("没有拿到登录二维码")
}
c.qrSec = c.cookie("uac.10010.com", c.spec.secCookie)
if c.qrSec == "" {
return nil, errors.New("没有拿到扫码凭证")
}
debugf("扫码凭证 %s=%s", c.spec.secCookie, c.qrSec)
return body, nil
}
func (c *Client) PollQR(ctx context.Context) (QRStatus, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.qrSec == "" || c.spec.heartPath == "" {
return QRStatus{}, errors.New("请先获取二维码")
}
body, err := c.get(ctx, c.loginURL(c.spec.heartPath, url.Values{
"secsnid": {c.qrSec},
}), c.loginReferer)
if err != nil {
return QRStatus{}, err
}
data, err := parseJSONP(string(body))
if err != nil {
return QRStatus{}, err
}
switch asString(data["resultcode"]) {
case "00", "":
return QRStatus{Waiting: true}, nil
case "10":
return QRStatus{Waiting: true, Scanned: true, Message: "已扫码,请在 App 里确认登录"}, nil
case "11":
return c.finishQR(ctx)
case "02", "-1":
return QRStatus{Expired: true, Message: "二维码已失效,请刷新"}, nil
default:
return QRStatus{Waiting: true}, nil
}
}
func (c *Client) Query(ctx context.Context, phone string) (Snapshot, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.prepareBill(ctx); err != nil {
return Snapshot{}, err
}
balance, err := c.postBill(ctx, c.fee, nil)
if err != nil {
return Snapshot{}, err
}
extra := url.Values{
"ticket": {""},
"ticketPhone": {""},
"ticketChannel": {""},
"userNumber": {""},
}
if c.plan.Language != "" {
extra.Set("language", c.plan.Language)
}
plan, err := c.postBill(ctx, c.plan, extra)
if err != nil {
return BuildSnapshot(phone, balance, nil), err
}
return BuildSnapshot(phone, balance, plan), nil
}
func (c *Client) finishQR(ctx context.Context) (QRStatus, error) {
body, err := c.get(ctx, c.loginURL(c.spec.logonPath, url.Values{
"secsnid": {c.qrSec},
}), c.loginReferer)
if err != nil {
return QRStatus{}, err
}
data, err := parseJSONP(string(body))
if err != nil {
return QRStatus{}, err
}
if asString(data["resultcode"]) != "01" {
return QRStatus{Expired: true, Message: "扫码登录失败"}, nil
}
if name := c.spec.piwCookie; name != "" {
if piw := asString(data["piw"]); piw != "" {
c.setDomainCookie(name, piw)
}
}
if err := c.land(ctx, servicePage); err != nil {
return QRStatus{}, err
}
return QRStatus{Message: "登录成功"}, nil
}
func (c *Client) prepareLogin(ctx context.Context) error {
if c.loginReady {
return nil
}
page := uacOrigin + "/portal/mallLogin.jsp?redirectURL=" + url.QueryEscape(servicePage)
c.loginReferer = page
html, err := c.getText(ctx, page, page)
if err != nil {
return err
}
next := findQuotedContaining(html, "homeLoginNew")
if next == "" {
for _, src := range scriptSrcs(html) {
js, err := c.getText(ctx, absURL(page, src), page)
if err != nil {
continue
}
if path := findQuotedContaining(js, "homeLoginNew"); path != "" {
next = path
break
}
if strings.Contains(js, "getKeyPair") {
return c.useBundle(html, js)
}
}
}
html2 := ""
if next != "" {
html2, err = c.getText(ctx, absURL(page, next), page)
if err != nil {
return err
}
}
combined := html + "\n" + html2
var bundle string
for _, src := range scriptSrcs(combined) {
js, err := c.getText(ctx, absURL(page, src), page)
if err != nil {
continue
}
if strings.Contains(js, "RSAUtils.getKeyPair") {
bundle = js
break
}
}
if bundle == "" {
return errors.New("登录脚本无法识别")
}
return c.useBundle(combined, bundle)
}
func (c *Client) useBundle(html, bundle string) error {
spec, err := parseLoginBundle(bundle)
if err != nil {
return err
}
if from := parseLoginFrom(html); from != "" {
spec.redirectType = from
}
if spec.redirectType == "" {
return errors.New("登录页没有跳转类型")
}
if spec.pwdType == "" || spec.userType == "" {
return errors.New("登录脚本里没有短信登录类型")
}
script := parseCaptchaScript(html)
if script == "" {
return errors.New("登录页没有验证码脚本")
}
c.spec = spec
c.captchaScript = absURL(c.loginReferer, script)
c.loginReady = true
debugf("登录脚本已识别 captcha=%s app=%s", c.captchaScript, spec.captchaAppID)
return nil
}
func (c *Client) prepareBill(ctx context.Context) error {
if c.fee.URL != "" && c.plan.URL != "" {
return nil
}
html, err := c.getText(ctx, servicePage, servicePage)
if err != nil {
return err
}
texts := []string{html}
for _, src := range scriptSrcs(html) {
js, err := c.getText(ctx, absURL(servicePage, src), servicePage)
if err != nil {
continue
}
texts = append(texts, js)
}
nav := resolveNav(texts)
if nav == "" {
return errors.New("查询页没有导航接口")
}
body, err := c.postForm(ctx, nav, servicePage, url.Values{
"jutThird": {""},
"_uop_id": {""},
"procode": {""},
})
if err != nil {
return err
}
feePages, planPages := menuPages(body)
fee, _, err := c.firstBill(ctx, feePages, feeMarker)
if err != nil {
return err
}
if fee.Version == "" {
return errors.New("话费页面脚本无法识别")
}
plan, _, err := c.firstBill(ctx, planPages, planMarker)
if err != nil {
return err
}
if plan.Version == "" {
plan.Version = fee.Version
}
c.fee = fee
c.plan = plan
debugf("话费接口 %s 余量接口 %s", fee.URL, plan.URL)
return nil
}
func (c *Client) firstBill(ctx context.Context, pages []string, marker string) (billAPI, string, error) {
if len(pages) == 0 {
return billAPI{}, "", errors.New("导航里没有话费或余量页面")
}
var last error
for _, page := range pages {
js, err := c.findScript(ctx, page, marker)
if err != nil {
last = err
continue
}
api, ok := parseBillAPI(js, page, marker)
if !ok {
last = errors.New("账单页面脚本无法识别")
continue
}
return api, js, nil
}
if last == nil {
last = errors.New("账单页面脚本无法识别")
}
return billAPI{}, "", last
}
func (c *Client) findScript(ctx context.Context, pageURL, marker string) (string, error) {
page, err := c.getText(ctx, pageURL, pageURL)
if err != nil {
return "", err
}
if strings.Contains(page, marker) {
return page, nil
}
seen := map[string]bool{}
queue := scriptSrcs(page)
for len(queue) > 0 && len(seen) < 30 {
ref := queue[0]
queue = queue[1:]
abs := absURL(pageURL, ref)
if abs == "" || seen[abs] || !strings.Contains(abs, "10010.com") {
continue
}
if !strings.Contains(strings.ToLower(abs), ".js") {
continue
}
seen[abs] = true
js, err := c.getText(ctx, abs, pageURL)
if err != nil {
continue
}
if strings.Contains(js, marker) {
return js, nil
}
for _, ref := range jsRefs(js) {
queue = append(queue, ref)
}
}
return "", errors.New("页面脚本里没有找到查询接口")
}
func (c *Client) postBill(ctx context.Context, api billAPI, extra url.Values) (json.RawMessage, error) {
form := url.Values{
"duanlianjieabc": {""},
"channelCode": {""},
"serviceType": {""},
"saleChannel": {""},
"externalSources": {""},
"contactCode": {""},
"version": {api.Version},
}
for k, vs := range extra {
form[k] = vs
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, api.URL, strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
c.decorate(req, api.Referer)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Origin", api.Origin)
body, ctype, err := c.doRequest(req)
if err != nil {
return nil, err
}
text := strings.TrimSpace(string(body))
if text == "999999" || text == `"999999"` {
return nil, ErrNeedLogin
}
if !strings.Contains(ctype, "json") && !strings.HasPrefix(text, "{") {
return nil, errors.New("账单接口没有返回数据")
}
var probe struct {
Code string `json:"code"`
Msg string `json:"msg"`
}
_ = json.Unmarshal(body, &probe)
if probe.Code == "1001" || probe.Code == "999999" {
return nil, ErrNeedLogin
}
if probe.Code != "" && probe.Code != "0000" {
if probe.Msg != "" {
return nil, errors.New(probe.Msg)
}
return nil, fmt.Errorf("查询失败 %s", probe.Code)
}
return json.RawMessage(body), nil
}
func (c *Client) land(ctx context.Context, raw string) error {
if raw == "" || raw == "null" {
raw = servicePage
}
_, err := c.getText(ctx, raw, c.loginReferer)
return err
}
func (c *Client) loginURL(path string, q url.Values) string {
q.Set("callback", "cb")
q.Set("_", milli())
return uacOrigin + path + "?" + q.Encode()
}
func (c *Client) get(ctx context.Context, rawURL, referer string) ([]byte, error) {
body, _, err := c.do(ctx, http.MethodGet, rawURL, referer, nil, nil)
return body, err
}
func (c *Client) getText(ctx context.Context, rawURL, referer string) (string, error) {
body, _, err := c.do(ctx, http.MethodGet, rawURL, referer, nil, nil)
if err != nil {
return "", err
}
return string(body), nil
}
func (c *Client) postForm(ctx context.Context, rawURL, referer string, form url.Values) ([]byte, error) {
body, _, err := c.do(ctx, http.MethodPost, rawURL, referer, strings.NewReader(form.Encode()), map[string]string{
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
})
return body, err
}
func (c *Client) do(ctx context.Context, method, rawURL, referer string, body io.Reader, header map[string]string) ([]byte, string, error) {
req, err := http.NewRequestWithContext(ctx, method, rawURL, body)
if err != nil {
return nil, "", err
}
c.decorate(req, referer)
for k, v := range header {
req.Header.Set(k, v)
}
return c.doRequest(req)
}
func (c *Client) doRequest(req *http.Request) ([]byte, string, error) {
resp, err := c.http.Do(req)
if err != nil {
debugHTTP(req, nil, nil, err)
return nil, "", err
}
defer resp.Body.Close()
buf, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
debugHTTP(req, resp, nil, err)
return nil, "", err
}
debugHTTP(req, resp, buf, nil)
if resp.StatusCode >= 400 && !strings.Contains(resp.Header.Get("Content-Type"), "json") {
return nil, "", fmt.Errorf("网站返回 %d", resp.StatusCode)
}
return buf, resp.Header.Get("Content-Type"), nil
}
func (c *Client) decorate(req *http.Request, referer string) {
req.Header.Set("User-Agent", userAgent)
if req.Method == http.MethodPost {
req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
req.Header.Set("X-Requested-With", "XMLHttpRequest")
} else {
req.Header.Set("Accept", "*/*")
}
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
if referer != "" {
req.Header.Set("Referer", referer)
if req.Method == http.MethodPost {
if u, err := url.Parse(referer); err == nil && u.Scheme != "" && u.Host != "" {
req.Header.Set("Origin", u.Scheme+"://"+u.Host)
}
}
}
if req.URL != nil && strings.Contains(req.URL.Host, "uac.10010.com") {
req.Header.Set("Origin", uacOrigin)
req.Header.Set("X-Requested-With", "XMLHttpRequest")
}
}
func (c *Client) cookie(host, name string) string {
if name == "" {
return ""
}
u, err := url.Parse("https://" + host + "/")
if err != nil {
return ""
}
for _, ck := range c.jar.Cookies(u) {
if ck.Name == name {
return ck.Value
}
}
return ""
}
func (c *Client) setDomainCookie(name, value string) {
u, err := url.Parse(uacOrigin + "/")
if err != nil {
return
}
c.jar.SetCookies(u, []*http.Cookie{{
Name: name, Value: value, Path: "/", Domain: "10010.com",
}})
}
func (c *Client) dropAccount() {
u, err := url.Parse(uacOrigin + "/")
if err != nil {
return
}
var cookies []*http.Cookie
for _, name := range []string{"JUT", "_uop_id", c.spec.piwCookie} {
if name == "" {
continue
}
cookies = append(cookies, &http.Cookie{Name: name, Value: "", Path: "/", Domain: "10010.com", MaxAge: -1})
}
c.jar.SetCookies(u, cookies)
}
func menuPages(body []byte) (fees, plans []string) {
var data any
if json.Unmarshal(body, &data) != nil {
return nil, nil
}
seenFee := map[string]bool{}
seenPlan := map[string]bool{}
var walk func(any)
walk = func(v any) {
switch t := v.(type) {
case map[string]any:
title := asString(t["title"])
raw := asString(t["url"])
if raw == "" {
raw = asString(t["titleUrl"])
}
if strings.HasPrefix(raw, "https://") {
if title == "剩余话费" && !seenFee[raw] {
seenFee[raw] = true
fees = append(fees, raw)
}
if title == "余量查询" && !seenPlan[raw] {
seenPlan[raw] = true
plans = append(plans, raw)
}
}
for _, child := range t {
walk(child)
}
case []any:
for _, child := range t {
walk(child)
}
}
}
walk(data)
preferIndex := func(list []string) []string {
sort.SliceStable(list, func(i, j int) bool {
return strings.Contains(list[i], "index.html") && !strings.Contains(list[j], "index.html")
})
return list
}
return preferIndex(fees), preferIndex(plans)
}
func smsMessage(body []byte) (string, error) {
data, err := parseJSONP(string(body))
if err != nil {
return "", err
}
code := asString(data["resultCode"])
if code == "0000" {
return "短信验证码已发送", nil
}
return "", bizError(code, data, "发送短信验证码失败")
}
func bizError(code string, data map[string]any, fallback string) error {
for _, key := range []string{"resultDesc", "rsp_desc", "msg", "message"} {
if text := asString(data[key]); text != "" && text != "null" {
return errors.New(text)
}
}
switch code {
case "7001":
return errors.New("验证码错误,请重新验证")
case "7096":
return errors.New("短信发送太频繁,请稍后再试")
case "7098":
return errors.New("今日短信次数已达上限")
case "7458":
return errors.New("请改用中国联通 App 扫码登录")
case "":
return errors.New(fallback)
default:
return fmt.Errorf("%s %s", fallback, code)
}
}
func findQuotedContaining(text, marker string) string {
for _, quote := range []string{`"`, `'`} {
start := 0
for {
i := strings.Index(text[start:], marker)
if i < 0 {
break
}
i += start
left := strings.LastIndex(text[:i], quote)
right := strings.Index(text[i:], quote)
if left >= 0 && right >= 0 {
value := text[left+1 : i+right]
if !strings.Contains(value, " ") && !strings.Contains(value, "<") {
return value
}
}
start = i + len(marker)
}
}
return ""
}
func absURL(base, ref string) string {
ref = strings.TrimSpace(ref)
if ref == "" {
return ""
}
if strings.HasPrefix(ref, "//") {
return "https:" + ref
}
u, err := url.Parse(ref)
if err != nil {
return ""
}
if u.IsAbs() {
return u.String()
}
b, err := url.Parse(base)
if err != nil {
return ""
}
return b.ResolveReference(u).String()
}
func milli() string {
return fmt.Sprintf("%d", time.Now().UnixMilli())
}
+63
View File
@@ -0,0 +1,63 @@
package unicom
import (
"log"
"net/http"
"strings"
)
// debugEnabled 为调试总开关。关闭后调试函数直接返回。
const debugEnabled = false
func DebugOn() bool { return debugEnabled }
func Debugf(format string, args ...any) {
debugf(format, args...)
}
func debugf(format string, args ...any) {
if !debugEnabled {
return
}
log.Printf("调试 "+format, args...)
}
func debugHTTP(req *http.Request, resp *http.Response, buf []byte, reqErr error) {
if !debugEnabled || req == nil || req.URL == nil {
return
}
if reqErr != nil {
debugf("%s %s 请求失败 %v", req.Method, req.URL.String(), reqErr)
return
}
if resp == nil {
return
}
debugf("%s %s -> %d %s", req.Method, req.URL.String(), resp.StatusCode, resp.Header.Get("Content-Type"))
if debugSkipBody(req, resp.Header.Get("Content-Type"), buf) {
debugf("%s 响应 %d 字节", req.URL.Path, len(buf))
return
}
const limit = 8000
if len(buf) > limit {
debugf("%s 响应 %d 字节 %s", req.URL.RequestURI(), len(buf), string(buf[:limit]))
return
}
debugf("%s 响应 %s", req.URL.RequestURI(), string(buf))
}
func debugSkipBody(req *http.Request, ctype string, buf []byte) bool {
ct := strings.ToLower(ctype)
path := strings.ToLower(req.URL.Path)
if strings.Contains(ct, "image") || strings.Contains(ct, "javascript") || strings.Contains(ct, "text/css") {
return true
}
switch {
case strings.HasSuffix(path, ".js"), strings.HasSuffix(path, ".css"), strings.HasSuffix(path, ".png"),
strings.HasSuffix(path, ".jpg"), strings.HasSuffix(path, ".jpeg"), strings.HasSuffix(path, ".gif"),
strings.HasSuffix(path, ".html"):
return true
}
trim := strings.TrimSpace(string(buf))
return strings.HasPrefix(trim, "<")
}
+5
View File
@@ -0,0 +1,5 @@
package unicom
import "errors"
var errBadKey = errors.New("登录公钥无法使用")
+211
View File
@@ -0,0 +1,211 @@
package unicom
import (
"encoding/json"
"strconv"
"strings"
)
type Snapshot struct {
Phone string `json:"phone,omitempty"`
PhoneMasked string `json:"phoneMasked,omitempty"`
PackageName string `json:"packageName,omitempty"`
Balance string `json:"balance,omitempty"`
BalanceNegative bool `json:"balanceNegative,omitempty"`
MonthFee string `json:"monthFee,omitempty"`
DataRemain string `json:"dataRemain,omitempty"`
DataUsed string `json:"dataUsed,omitempty"`
VoiceTotal string `json:"voiceTotal,omitempty"`
VoiceRemain string `json:"voiceRemain,omitempty"`
Resources []Resource `json:"resources"`
Extras []Extra `json:"extras"`
}
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"`
}
func BuildSnapshot(phone string, balanceRaw, planRaw json.RawMessage) Snapshot {
snap := Snapshot{Phone: strings.TrimSpace(phone), PhoneMasked: MaskPhone(phone), Resources: []Resource{}}
var balance map[string]any
_ = json.Unmarshal(balanceRaw, &balance)
if balance != nil {
snap.Balance = textOf(balance["canusefeecust"])
if snap.Balance == "" {
snap.Balance = textOf(balance["curntbalancecust"])
}
snap.BalanceNegative = strings.HasPrefix(snap.Balance, "-")
snap.MonthFee = textOf(balance["realfeecust"])
if owe := textOf(balance["allbowefeecust"]); owe != "" && owe != "0" && owe != "0.00" {
snap.Extras = append(snap.Extras, Extra{Name: "欠费", Used: owe, Fee: owe})
}
}
var plan map[string]any
_ = json.Unmarshal(planRaw, &plan)
if plan != nil {
snap.PackageName = textOf(plan["packageName"])
if snap.Phone == "" {
snap.Phone = textOf(plan["mobile"])
snap.PhoneMasked = MaskPhone(snap.Phone)
}
if remain := textOf(plan["canUseFlowAll"]); remain != "" {
snap.DataRemain = remain + unitSuffix(textOf(plan["canuseFlowAllUnit"]))
}
snap.Resources = resourcesFromPlan(plan)
snap.VoiceTotal, snap.VoiceRemain = voiceHeadline(snap.Resources)
}
return snap
}
func resourcesFromPlan(plan map[string]any) []Resource {
blocks, _ := plan["resources"].([]any)
out := []Resource{}
for _, block := range blocks {
item, _ := block.(map[string]any)
if item == nil {
continue
}
details, _ := item["details"].([]any)
for _, raw := range details {
detail, _ := raw.(map[string]any)
if detail == nil || textOf(detail["hide"]) == "true" {
continue
}
unit := unitFor(textOf(detail["elemType"]))
total := textOf(detail["total"])
used := textOf(detail["use"])
remain := textOf(detail["remain"])
if unit == "GB" {
total = mbToGB(total)
used = mbToGB(used)
remain = mbToGB(remain)
}
name := textOf(detail["addUpItemName"])
if name == "" {
name = textOf(detail["feePolicyName"])
}
out = append(out, Resource{
Name: name,
Used: used,
Remain: remain,
Total: total,
Unit: unit,
Percent: percent(used, total),
})
}
}
return out
}
func unitFor(elemType string) string {
switch elemType {
case "1":
return "分钟"
case "2":
return "条"
case "3":
return "GB"
default:
return ""
}
}
func voiceHeadline(list []Resource) (total, remain string) {
var sumTotal, sumRemain float64
var seen bool
for _, item := range list {
if item.Unit != "分钟" {
continue
}
t, err1 := strconv.ParseFloat(item.Total, 64)
r, err2 := strconv.ParseFloat(item.Remain, 64)
if err1 != nil || err2 != nil {
continue
}
sumTotal += t
sumRemain += r
seen = true
}
if !seen {
return "", ""
}
return trimNum(sumTotal), trimNum(sumRemain)
}
func mbToGB(raw string) string {
v, err := strconv.ParseFloat(strings.TrimSpace(raw), 64)
if err != nil {
return raw
}
return trimNum(v / 1024)
}
func percent(used, total string) float64 {
u, err1 := strconv.ParseFloat(used, 64)
t, err2 := strconv.ParseFloat(total, 64)
if err1 != nil || err2 != nil || t <= 0 {
return 0
}
p := u / t * 100
if p < 0 {
return 0
}
if p > 100 {
return 100
}
return p
}
func trimNum(v float64) string {
s := strconv.FormatFloat(v, 'f', 2, 64)
s = strings.TrimRight(s, "0")
s = strings.TrimRight(s, ".")
if s == "" || s == "-" {
return "0"
}
return s
}
func textOf(v any) string {
switch t := v.(type) {
case string:
return strings.TrimSpace(t)
case float64:
return trimNum(t)
case json.Number:
return t.String()
case bool:
if t {
return "true"
}
return "false"
default:
return ""
}
}
func unitSuffix(unit string) string {
if unit == "" {
return ""
}
return " " + unit
}
func MaskPhone(phone string) string {
phone = strings.TrimSpace(phone)
if len(phone) < 7 {
return phone
}
return phone[:3] + "****" + phone[len(phone)-4:]
}
+30
View File
@@ -0,0 +1,30 @@
package unicom
import "testing"
func TestBuildSnapshot(t *testing.T) {
balance := []byte(`{"code":"0000","canusefeecust":"12.50","realfeecust":"3.20","allbowefeecust":"0.00"}`)
plan := []byte(`{
"packageName":"测试套餐",
"canUseFlowAll":"1.5",
"canuseFlowAllUnit":"GB",
"resources":[
{"type":"flow","details":[{"elemType":"3","addUpItemName":"国内流量","total":"2048","use":"512","remain":"1536"}]},
{"type":"Voice","details":[{"elemType":"1","addUpItemName":"语音","total":"100","use":"2","remain":"98"}]},
{"type":"smsList","details":[{"elemType":"2","addUpItemName":"短信","total":"100","use":"3","remain":"97"}]}
]
}`)
snap := BuildSnapshot("13800000000", balance, plan)
if snap.PhoneMasked != "138****0000" || snap.Balance != "12.50" || snap.MonthFee != "3.20" {
t.Fatalf("money %#v", snap)
}
if snap.PackageName != "测试套餐" || snap.DataRemain != "1.5 GB" {
t.Fatalf("plan %#v", snap)
}
if snap.VoiceTotal != "100" || snap.VoiceRemain != "98" {
t.Fatalf("voice %s %s", snap.VoiceTotal, snap.VoiceRemain)
}
if len(snap.Resources) != 3 || snap.Resources[0].Unit != "GB" || snap.Resources[0].Total != "2" {
t.Fatalf("resources %#v", snap.Resources)
}
}
+48
View File
@@ -0,0 +1,48 @@
package unicom
import (
"encoding/json"
"errors"
"regexp"
"strconv"
"strings"
)
var bareKeyRE = regexp.MustCompile(`([{\[,]\s*)([A-Za-z_][A-Za-z0-9_]*)\s*:`)
func parseJSONP(body string) (map[string]any, error) {
text := strings.TrimSpace(body)
if i := strings.Index(text, "("); i >= 0 && strings.Contains(text, ")") {
text = text[i+1 : strings.LastIndex(text, ")")]
text = strings.TrimSpace(text)
}
if text == "" {
return nil, errors.New("接口没有返回结果")
}
dec := json.NewDecoder(strings.NewReader(text))
dec.UseNumber()
var out map[string]any
if err := dec.Decode(&out); err == nil {
return out, nil
}
fixed := bareKeyRE.ReplaceAllString(text, `$1"$2":`)
dec = json.NewDecoder(strings.NewReader(fixed))
dec.UseNumber()
if err := dec.Decode(&out); err != nil {
return nil, errors.New("接口结果无法解析")
}
return out, nil
}
func asString(v any) string {
switch t := v.(type) {
case string:
return t
case json.Number:
return t.String()
case float64:
return strconv.FormatFloat(t, 'f', -1, 64)
default:
return ""
}
}
+39
View File
@@ -0,0 +1,39 @@
package unicom
import (
"context"
"os"
"testing"
"time"
)
func TestLiveDiscover(t *testing.T) {
if os.Getenv("CU_LIVE") == "" {
t.Skip()
}
client, err := New()
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 70*time.Second)
defer cancel()
if err := client.Prepare(ctx); err != nil {
t.Fatal(err)
}
script, appID := client.Captcha()
if script == "" || appID == "" {
t.Fatalf("captcha script=%q app=%q", script, appID)
}
client.mu.Lock()
err = client.prepareBill(ctx)
fee, plan := client.fee.URL, client.plan.URL
version := client.fee.Version
client.mu.Unlock()
if err != nil {
t.Fatal(err)
}
if fee == "" || plan == "" || version == "" {
t.Fatalf("fee=%s plan=%s version=%s", fee, plan, version)
}
t.Logf("captcha app %s fee %s plan %s", appID, fee, plan)
}
+56
View File
@@ -0,0 +1,56 @@
package unicom
import (
"math/big"
"strings"
)
// encryptPassword 按登录脚本里的 RSAUtils.encryptedString 加密。
// 明文按字节放入 16 位小端 digit,再做模幂,输出不带空格分隔的十六进制块。
func encryptPassword(exponentHex, modulusHex, plain string) (string, error) {
modulus := new(big.Int)
if _, ok := modulus.SetString(modulusHex, 16); !ok || modulus.Sign() <= 0 {
return "", errBadKey
}
exponent := new(big.Int)
if _, ok := exponent.SetString(exponentHex, 16); !ok || exponent.Sign() <= 0 {
return "", errBadKey
}
chunk := 2 * highIndex(modulus)
if chunk < 2 {
return "", errBadKey
}
raw := []byte(plain)
for len(raw)%chunk != 0 {
raw = append(raw, 0)
}
parts := make([]string, 0, len(raw)/chunk)
for i := 0; i < len(raw); i += chunk {
block := new(big.Int)
for j := 0; j < chunk; j += 2 {
digit := int64(raw[i+j]) + int64(raw[i+j+1])<<8
block.Add(block, new(big.Int).Lsh(big.NewInt(digit), uint(j/2*16)))
}
crypt := new(big.Int).Exp(block, exponent, modulus)
parts = append(parts, hexBlock(crypt))
}
return strings.Join(parts, " "), nil
}
func highIndex(n *big.Int) int {
if n.Sign() == 0 {
return 0
}
return (n.BitLen() - 1) / 16
}
func hexBlock(n *big.Int) string {
h := n.Text(16)
if h == "" {
h = "0"
}
for len(h)%4 != 0 {
h = "0" + h
}
return h
}
+22
View File
@@ -0,0 +1,22 @@
package unicom
import (
"math/big"
"testing"
)
func TestEncryptPasswordPacksLittleEndian(t *testing.T) {
modulus := "10001"
exponent := "11"
got, err := encryptPassword(exponent, modulus, "A")
if err != nil {
t.Fatal(err)
}
m := big.NewInt(65537)
e := big.NewInt(17)
block := big.NewInt(65)
want := hexBlock(new(big.Int).Exp(block, e, m))
if got != want {
t.Fatalf("got %s want %s", got, want)
}
}
+266
View File
@@ -0,0 +1,266 @@
package unicom
import (
"errors"
"regexp"
"strings"
)
type loginScript struct {
exponent string
modulus string
captchaAppID string
captchaScript string
sendPath string
loginPath string
genQRPath string
heartPath string
logonPath string
secCookie string
piwCookie string
pwdType string
userType string
redirectType string
}
type billAPI struct {
URL string
Origin string
Referer string
Version string
Language string
}
var (
keyPairRE = regexp.MustCompile(`RSAUtils\.getKeyPair\(\s*"([0-9a-fA-F]+)"\s*,\s*"([0-9a-fA-F]*)"\s*,\s*"([0-9a-fA-F]+)"\s*\)`)
captchaAppRE = regexp.MustCompile(`new\s+TencentCaptcha\(\s*['"](\d+)['"]`)
captchaSrcRE = regexp.MustCompile(`src=["']([^"']*turing\.captcha[^"']+)["']`)
sendPathRE = regexp.MustCompile(`(/portal/Service/SendMSG)`)
loginPathRE = regexp.MustCompile(`(/portal/Service/MallLogin)`)
genQRRE = regexp.MustCompile(`(/oauth2/genqr)`)
heartRE = regexp.MustCompile(`(/qrcode/qrcode_hbt)`)
logonRE = regexp.MustCompile(`(/portal/qrcode/qrcode_logon)`)
secCookieRE = regexp.MustCompile(`secsnid\s*=\s*\$\.cookie\(["']([A-Za-z0-9_]+)["']\)`)
piwCookieRE = regexp.MustCompile(`setCookie\(\s*["']([A-Za-z0-9_]+)["']\s*,\s*data\.piw`)
pwdTypeRE = regexp.MustCompile(`PWD_TYPE_RND\s*=\s*["'](\d+)["']`)
userTypeRE = regexp.MustCompile(`USER_TYPE_MOBILE\s*=\s*["'](\d+)["']`)
loginFromRE = regexp.MustCompile(`(?is)<input[^>]*id=["']loginFrom["'][^>]*>`)
inputValueRE = regexp.MustCompile(`value=["']([^"']*)["']`)
scriptSrcRE = regexp.MustCompile(`(?i)<script[^>]*?\ssrc=["']?([^"'\s>]+)`)
navURLRE = regexp.MustCompile(`https://www\.10010\.com/mall/service/query/QueryNavigations`)
queryPrefixRE = regexp.MustCompile(`QueryRequestPrefix\s*:\s*function\s*\(\)\s*\{\s*return\s*["']([^"']+)["']`)
xxBaseRE = regexp.MustCompile(`VUE_APP_XX_BASE_URL:"(https://[^"]+)"`)
queryKeyRE = regexp.MustCompile(`(?:VUE_APP_KEY_QUERY|key_query):"([^"]+)"`)
httpsHostRE = regexp.MustCompile(`"(https://[a-zA-Z0-9.-]+\.10010\.com)"`)
versionRE = regexp.MustCompile(`version:"([^"]+)"`)
languageRE = regexp.MustCompile(`language:"([^"]+)"`)
jsPathRE = regexp.MustCompile(`["']([^"']+\.js(?:\?[^"']*)?)["']`)
)
func parseLoginBundle(js string) (loginScript, error) {
var out loginScript
key := keyPairRE.FindStringSubmatch(js)
if key == nil {
return out, errors.New("登录公钥没有在脚本里找到")
}
out.exponent = key[1]
out.modulus = key[3]
if app := captchaAppRE.FindStringSubmatch(js); app != nil {
out.captchaAppID = app[1]
}
out.sendPath = first(sendPathRE, js)
out.loginPath = first(loginPathRE, js)
out.genQRPath = first(genQRRE, js)
out.heartPath = first(heartRE, js)
out.logonPath = first(logonRE, js)
if m := secCookieRE.FindStringSubmatch(js); m != nil {
out.secCookie = m[1]
}
if m := piwCookieRE.FindStringSubmatch(js); m != nil {
out.piwCookie = m[1]
}
if m := pwdTypeRE.FindStringSubmatch(js); m != nil {
out.pwdType = m[1]
}
if m := userTypeRE.FindStringSubmatch(js); m != nil {
out.userType = m[1]
}
if out.sendPath == "" || out.loginPath == "" || out.captchaAppID == "" {
return out, errors.New("登录脚本不完整")
}
return out, nil
}
func parseLoginFrom(html string) string {
tag := loginFromRE.FindString(html)
if tag == "" {
return ""
}
if m := inputValueRE.FindStringSubmatch(tag); m != nil {
return m[1]
}
return ""
}
func parseCaptchaScript(html string) string {
if m := captchaSrcRE.FindStringSubmatch(html); m != nil {
return m[1]
}
return ""
}
func scriptSrcs(html string) []string {
all := scriptSrcRE.FindAllStringSubmatch(html, -1)
out := make([]string, 0, len(all))
seen := map[string]bool{}
for _, item := range all {
src := strings.TrimSpace(item[1])
if src == "" || seen[src] {
continue
}
seen[src] = true
out = append(out, src)
}
return out
}
func findNavURL(text string) string {
return navURLRE.FindString(text)
}
func resolveNav(texts []string) string {
var prefix string
called := false
for _, text := range texts {
if nav := findNavURL(text); nav != "" {
return nav
}
if m := queryPrefixRE.FindStringSubmatch(text); m != nil {
prefix = m[1]
}
if strings.Contains(text, "QueryNavigations") {
called = true
}
}
if prefix == "" || !called {
return ""
}
if strings.HasPrefix(prefix, "//") {
prefix = "https:" + prefix
}
return strings.TrimRight(prefix, "/") + "/QueryNavigations"
}
func parseBillAPI(js, pageURL, pathMarker string) (billAPI, bool) {
if !strings.Contains(js, pathMarker) {
return billAPI{}, false
}
base := firstGroup(xxBaseRE, js)
key := firstGroup(queryKeyRE, js)
if base == "" && key != "" {
base = hostNear(js, key)
}
if base == "" || key == "" {
return billAPI{}, false
}
path := pathMarker
if i := strings.Index(js, pathMarker); i >= 0 {
start := strings.LastIndex(js[:i], `"`)
if start >= 0 && start < i {
candidate := js[start+1 : i+len(pathMarker)]
if strings.HasPrefix(candidate, "/") {
path = candidate
}
}
}
full := strings.TrimRight(base, "/") + "/" + strings.Trim(key, "/") + path
origin, referer := pageEndpoint(pageURL)
return billAPI{
URL: full,
Origin: origin,
Referer: referer,
Version: firstGroup(versionRE, js),
Language: firstGroup(languageRE, js),
}, true
}
func pageEndpoint(raw string) (origin, referer string) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", ""
}
scheme := "https://"
rest := raw
if i := strings.Index(raw, "://"); i >= 0 {
scheme = raw[:i+3]
rest = raw[i+3:]
}
host := rest
if i := strings.IndexAny(host, "/?#"); i >= 0 {
host = host[:i]
}
return scheme + host, raw
}
func jsRefs(js string) []string {
all := jsPathRE.FindAllStringSubmatch(js, -1)
out := make([]string, 0, len(all))
seen := map[string]bool{}
for _, item := range all {
ref := item[1]
if strings.Contains(ref, "://") && !strings.Contains(ref, "10010.com") {
continue
}
if strings.HasPrefix(ref, "data:") || strings.Contains(ref, " ") {
continue
}
if seen[ref] {
continue
}
seen[ref] = true
out = append(out, ref)
}
return out
}
func hostNear(js, key string) string {
i := strings.Index(js, `key_query:"`+key+`"`)
if i < 0 {
i = strings.Index(js, key)
}
if i < 0 {
return ""
}
start := i - 1500
if start < 0 {
start = 0
}
end := i + 200
if end > len(js) {
end = len(js)
}
matches := httpsHostRE.FindAllStringSubmatch(js[start:end], -1)
if len(matches) == 0 {
return ""
}
return matches[len(matches)-1][1]
}
func first(re *regexp.Regexp, text string) string {
m := re.FindStringSubmatch(text)
if m == nil {
return ""
}
if len(m) > 1 {
return m[1]
}
return m[0]
}
func firstGroup(re *regexp.Regexp, text string) string {
m := re.FindStringSubmatch(text)
if m == nil || len(m) < 2 {
return ""
}
return m[1]
}
+87
View File
@@ -0,0 +1,87 @@
package unicom
import "testing"
func TestParseJSONP(t *testing.T) {
quoted, err := parseJSONP(`cb({"resultCode":"false","ckCode":"2"});`)
if err != nil || asString(quoted["resultCode"]) != "false" {
t.Fatalf("quoted %#v %v", quoted, err)
}
bare, err := parseJSONP(`jQuery1({resultCode:"0000",redirectURL:"null"});`)
if err != nil || asString(bare["resultCode"]) != "0000" || asString(bare["redirectURL"]) != "null" {
t.Fatalf("bare %#v %v", bare, err)
}
}
func TestParseLoginBundle(t *testing.T) {
js := `
RSAUtils.getKeyPair("11", "", "abc123");
new TencentCaptcha('197439193', callback);
CommonConstants.SEND_RNDCODE_URL = UacPrefix.PRXFIX + "/portal/Service/SendMSG?callback=?";
CommonConstants.LOGIN_URL = UacPrefix.PRXFIX + "/portal/Service/MallLogin?callback=?";
var genqrimg = UacPrefix.PRXFIX + "/oauth2/genqr";
var heartbeaturl = UacPrefix.PRXFIX + "/qrcode/qrcode_hbt?callback=?";
var logonurl = UacPrefix.PRXFIX + "/portal/qrcode/qrcode_logon?callback=?";
params.secsnid = $.cookie("unisecid");
setCookie("piw", data.piw);
CommonConstants.PWD_TYPE_RND = "02";
CommonConstants.USER_TYPE_MOBILE = "01";
`
got, err := parseLoginBundle(js)
if err != nil {
t.Fatal(err)
}
if got.exponent != "11" || got.modulus != "abc123" || got.captchaAppID != "197439193" {
t.Fatalf("key %#v", got)
}
if got.sendPath != "/portal/Service/SendMSG" || got.loginPath != "/portal/Service/MallLogin" {
t.Fatalf("paths %#v", got)
}
if got.genQRPath != "/oauth2/genqr" || got.heartPath != "/qrcode/qrcode_hbt" || got.logonPath != "/portal/qrcode/qrcode_logon" {
t.Fatalf("qr %#v", got)
}
if got.secCookie != "unisecid" || got.piwCookie != "piw" || got.pwdType != "02" || got.userType != "01" {
t.Fatalf("names %#v", got)
}
html := `<input type="hidden" id="loginFrom" name="loginFrom" value='01' />
<script src="https://turing.captcha.qcloud.com/TJCaptcha.js"></script>`
if parseLoginFrom(html) != "01" {
t.Fatal(parseLoginFrom(html))
}
if parseCaptchaScript(html) != "https://turing.captcha.qcloud.com/TJCaptcha.js" {
t.Fatal(parseCaptchaScript(html))
}
}
func TestParseBillAPI(t *testing.T) {
js := `VUE_APP_XX_BASE_URL:"https://bill.example.10010.com",VUE_APP_KEY_QUERY:"servicequerybusiness",version:"WT",language:"chinese"
A(B+"/balancenew/accountBalancenew.htm",t)`
api, ok := parseBillAPI(js, "https://img.example.10010.com/fee/index.html", "/balancenew/accountBalancenew.htm")
if !ok {
t.Fatal("not parsed")
}
if api.URL != "https://bill.example.10010.com/servicequerybusiness/balancenew/accountBalancenew.htm" {
t.Fatal(api.URL)
}
if api.Version != "WT" || api.Language != "chinese" || api.Origin != "https://img.example.10010.com" {
t.Fatalf("%#v", api)
}
}
func TestResolveNav(t *testing.T) {
texts := []string{
`function getNavJson(){ var url = CommonsVariables.QueryRequestPrefix() +'/QueryNavigations'; }`,
`QueryRequestPrefix : function() { return "//www.10010.com/mall/service/query"; },`,
}
if got := resolveNav(texts); got != "https://www.10010.com/mall/service/query/QueryNavigations" {
t.Fatal(got)
}
}
func TestMenuPages(t *testing.T) {
raw := []byte(`{"list":[{"title":"剩余话费","url":"https://img.example.10010.com/fee/index.html"},{"title":"余量查询","url":"https://img.example.10010.com/plan/index.html"}]}`)
fee, plan := menuPages(raw)
if len(fee) != 1 || fee[0] != "https://img.example.10010.com/fee/index.html" || len(plan) != 1 || plan[0] != "https://img.example.10010.com/plan/index.html" {
t.Fatalf("%v %v", fee, plan)
}
}
+502
View File
@@ -0,0 +1,502 @@
package main
import (
"context"
_ "embed"
"encoding/json"
"errors"
"io"
"log"
"math/rand/v2"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
_ "time/tzdata"
"cusiminfo/internal/unicom"
)
//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 {
PollMinutes int `json:"pollMinutes"`
JitterMinutes int `json:"jitterMinutes"`
}
type overview struct {
LoggedIn bool `json:"loggedIn"`
NeedLogin bool `json:"needLogin"`
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"`
HasData bool `json:"hasData"`
LoginEpoch int `json:"loginEpoch"`
CaptchaScript string `json:"captchaScript,omitempty"`
CaptchaAppID string `json:"captchaAppId,omitempty"`
PhonePrefill string `json:"phonePrefill,omitempty"`
unicom.Snapshot
}
type App struct {
client *unicom.Client
cfgPhone string
interval time.Duration
jitter time.Duration
mu sync.Mutex
phone string
loggedIn bool
snap unicom.Snapshot
lastError string
refreshed time.Time
refreshing bool
nextAt time.Time
epoch int
}
func main() {
cfg := loadConfig()
client, err := unicom.New()
if err != nil {
log.Fatal(err)
}
app := &App{client: client, cfgPhone: strings.TrimSpace(cfg.Phone)}
app.interval = 30 * time.Minute
if d, err := time.ParseDuration(cfg.PollInterval); err == nil && d >= time.Minute {
app.interval = d
}
if cfg.JitterMinutes > 0 {
app.jitter = time.Duration(cfg.JitterMinutes) * time.Minute
}
app.load()
prepCtx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
if err := app.client.Prepare(prepCtx); err != nil {
log.Printf("登录参数暂未就绪,登录时会再试: %v", err)
}
cancel()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go app.loop(ctx)
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", func(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)
})
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/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/refresh", app.manualRefresh)
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("已启动,浏览器打开 http://127.0.0.1%s", strings.TrimPrefix(cfg.Listen, "0.0.0.0"))
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}
func (a *App) sms(w http.ResponseWriter, r *http.Request) {
var req struct {
Phone string `json:"phone"`
Ticket string `json:"ticket"`
Randstr string `json:"randstr"`
}
if err := decode(r, &req); err != nil {
writeErr(w, "请求无法识别")
return
}
phone := strings.TrimSpace(req.Phone)
if !validPhone(phone) {
writeErr(w, "请输入 11 位手机号")
return
}
if strings.TrimSpace(req.Ticket) == "" || strings.TrimSpace(req.Randstr) == "" {
writeErr(w, "请先完成验证码")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 40*time.Second)
defer cancel()
msg, err := a.client.SendSMS(ctx, phone, req.Ticket, req.Randstr)
if err != nil {
writeErr(w, err.Error())
return
}
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"`
SMSCode string `json:"smsCode"`
Ticket string `json:"ticket"`
Randstr string `json:"randstr"`
}
if err := decode(r, &req); err != nil {
writeErr(w, "请求无法识别")
return
}
phone := strings.TrimSpace(req.Phone)
if !validPhone(phone) || strings.TrimSpace(req.SMSCode) == "" {
writeErr(w, "请填写手机号和短信验证码")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 50*time.Second)
defer cancel()
result, err := a.client.Login(ctx, phone, strings.TrimSpace(req.SMSCode), req.Ticket, req.Randstr)
if err != nil {
writeErr(w, err.Error())
return
}
a.acceptLogin(result.Phone)
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
func (a *App) qrCode(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 40*time.Second)
defer cancel()
img, err := a.client.QRCode(ctx)
if err != nil {
writeErr(w, err.Error())
return
}
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(img)
}
func (a *App) qrPoll(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 40*time.Second)
defer cancel()
status, err := a.client.PollQR(ctx)
if err != nil {
writeErr(w, err.Error())
return
}
if !status.Waiting && !status.Expired {
a.acceptLogin("")
}
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"waiting": status.Waiting,
"scanned": status.Scanned,
"expired": status.Expired,
"message": status.Message,
"loggedIn": !status.Waiting && !status.Expired,
})
}
func (a *App) acceptLogin(phone string) {
a.mu.Lock()
a.loggedIn = true
if phone != "" {
a.phone = phone
}
a.lastError = ""
a.mu.Unlock()
a.refresh()
a.mu.Lock()
if a.loggedIn {
log.Printf("登录成功 %s", unicom.MaskPhone(a.phone))
}
a.mu.Unlock()
}
func (a *App) logout(w http.ResponseWriter, r *http.Request) {
a.client.Reset()
a.mu.Lock()
a.loggedIn = false
a.phone = ""
a.snap = unicom.Snapshot{}
a.lastError = ""
a.refreshed = time.Time{}
a.nextAt = time.Time{}
a.epoch++
a.mu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
func (a *App) manualRefresh(w http.ResponseWriter, r *http.Request) {
a.mu.Lock()
ok := a.loggedIn
a.mu.Unlock()
if !ok {
writeErr(w, "请先登录")
return
}
a.refresh()
writeJSON(w, http.StatusOK, a.view())
}
func (a *App) setInterval(w http.ResponseWriter, r *http.Request) {
var req struct {
PollMinutes int `json:"pollMinutes"`
JitterMinutes int `json:"jitterMinutes"`
}
if err := decode(r, &req); err != nil {
writeErr(w, "请求无法识别")
return
}
if req.PollMinutes < 1 {
req.PollMinutes = 1
}
if req.PollMinutes > 24*60 {
req.PollMinutes = 24 * 60
}
if req.JitterMinutes < 0 {
req.JitterMinutes = 0
}
if req.JitterMinutes > 24*60 {
req.JitterMinutes = 24 * 60
}
a.mu.Lock()
a.interval = time.Duration(req.PollMinutes) * time.Minute
a.jitter = time.Duration(req.JitterMinutes) * time.Minute
if a.loggedIn {
a.nextAt = time.Now().Add(a.wait())
}
a.mu.Unlock()
_ = a.save()
writeJSON(w, http.StatusOK, a.view())
}
func (a *App) loop(ctx context.Context) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
a.mu.Lock()
due := a.loggedIn && !a.refreshing && !a.nextAt.IsZero() && !time.Now().Before(a.nextAt)
a.mu.Unlock()
if due {
a.refresh()
}
}
}
}
func (a *App) refresh() {
a.mu.Lock()
if !a.loggedIn || a.refreshing {
a.mu.Unlock()
return
}
a.refreshing = true
phone := a.phone
a.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
snap, err := a.client.Query(ctx, phone)
cancel()
a.mu.Lock()
defer a.mu.Unlock()
a.refreshing = false
if !a.loggedIn {
return
}
if err != nil {
if errors.Is(err, unicom.ErrNeedLogin) {
a.loggedIn = false
a.phone = ""
a.snap = unicom.Snapshot{}
a.lastError = "会话已失效,请重新登录"
a.epoch++
a.client.Reset()
return
}
a.lastError = err.Error()
if snap.Balance != "" || len(snap.Resources) > 0 {
a.snap = snap
a.refreshed = time.Now()
}
} else {
a.snap = snap
a.lastError = ""
a.refreshed = time.Now()
if a.phone == "" && snap.Phone != "" {
a.phone = snap.Phone
}
}
a.nextAt = time.Now().Add(a.wait())
}
func (a *App) wait() time.Duration {
d := a.interval
if a.jitter > 0 {
d += time.Duration(rand.Int64N(int64(a.jitter)))
}
if d < time.Second {
d = time.Second
}
return d
}
func (a *App) view() overview {
a.mu.Lock()
defer a.mu.Unlock()
script, appID := a.client.Captcha()
left := 0
if a.loggedIn && !a.nextAt.IsZero() {
left = int(time.Until(a.nextAt).Seconds())
if left < 0 {
left = 0
}
}
out := overview{
LoggedIn: a.loggedIn,
NeedLogin: !a.loggedIn,
Refreshing: a.refreshing,
PollEvery: a.interval.String(),
PollMinutes: int(a.interval / time.Minute),
JitterMinutes: int(a.jitter / time.Minute),
SecondsLeft: left,
Error: a.lastError,
HasData: a.snap.Balance != "" || len(a.snap.Resources) > 0,
LoginEpoch: a.epoch,
CaptchaScript: script,
CaptchaAppID: appID,
PhonePrefill: a.cfgPhone,
Snapshot: a.snap,
}
if !a.refreshed.IsZero() {
out.RefreshedAt = a.refreshed.Format("2006-01-02 15:04:05")
}
return out
}
func (a *App) load() {
b, err := os.ReadFile(statePath)
if err != nil {
return
}
var saved savedState
if json.Unmarshal(b, &saved) != nil {
return
}
if saved.PollMinutes >= 1 {
a.interval = time.Duration(saved.PollMinutes) * time.Minute
}
if saved.JitterMinutes >= 0 {
a.jitter = time.Duration(saved.JitterMinutes) * time.Minute
}
}
func (a *App) save() error {
a.mu.Lock()
saved := savedState{
PollMinutes: int(a.interval / time.Minute),
JitterMinutes: int(a.jitter / time.Minute),
}
a.mu.Unlock()
if err := os.MkdirAll(filepath.Dir(statePath), 0700); err != nil {
return err
}
b, err := json.MarshalIndent(saved, "", " ")
if err != nil {
return err
}
tmp := statePath + ".tmp"
if err := os.WriteFile(tmp, b, 0600); err != nil {
return err
}
return os.Rename(tmp, statePath)
}
func loadConfig() Config {
cfg := Config{Listen: ":8786", PollInterval: "30m"}
if b, err := os.ReadFile("config.json"); err == nil {
_ = json.Unmarshal(b, &cfg)
}
if v := os.Getenv("CU_LISTEN"); v != "" {
cfg.Listen = v
}
if v := os.Getenv("CU_POLL"); v != "" {
cfg.PollInterval = v
}
if v := os.Getenv("CU_JITTER"); v != "" {
if n, err := strconv.Atoi(v); err == nil {
cfg.JitterMinutes = n
}
}
if v := os.Getenv("CU_PHONE"); v != "" {
cfg.Phone = v
}
if cfg.Listen == "" {
cfg.Listen = ":8786"
}
return cfg
}
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 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
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

+272
View File
@@ -0,0 +1,272 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>联通账户</title>
<link rel="icon" href="/favicon.ico">
<style>
:root {
--bg: #eef1f6; --card: #fff; --ink: #1b2433; --muted: #6b7585; --line: #e4e9f0;
--accent: #e60027; --ok: #0f7b4c; --danger: #b42318; --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(380px, calc(100% - 24px)); padding: 24px 0; }
header { position: sticky; top: 0; z-index: 4; display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: -8px 0 12px; padding: 8px 0; background: var(--bg); }
h1 { margin: 0; font-size: 22px; }
button, input { font: inherit; }
button { border: 0; border-radius: 8px; background: var(--accent); color: #fff; padding: 8px 12px; cursor: pointer; }
button.ghost { background: #fff; color: var(--ink); border: 1px solid var(--line); }
button:disabled { opacity: .55; cursor: default; }
.card { background: var(--card); border: 1px solid var(--line); border-radius: 14px; box-shadow: var(--shadow); padding: 14px; }
.tabs { display: flex; gap: 6px; margin-bottom: 12px; }
.tabs button { flex: 1; background: #f4f6fa; color: var(--ink); }
.tabs button.on { background: var(--accent); color: #fff; }
.row { display: flex; align-items: center; gap: 8px; margin: 8px 0; }
.row label { width: 72px; flex: none; color: var(--muted); font-size: 13px; }
.row input { flex: 1; min-width: 0; border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; }
.msg { min-height: 20px; color: var(--danger); font-size: 13px; }
.msg.ok { color: var(--ok); }
.hint { color: var(--muted); font-size: 13px; margin: 8px 0; }
.qr { display: flex; justify-content: center; }
.qr img { width: 220px; height: 220px; object-fit: contain; background: #fff; }
.help { display: inline-flex; width: 16px; height: 16px; margin-left: 4px; border-radius: 50%; border: 1px solid var(--line); color: var(--muted); font-size: 11px; align-items: center; justify-content: center; cursor: help; }
.stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-bottom: 12px; }
.stat { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; }
.stat b { display: block; font-size: 20px; margin-top: 4px; }
.stat span { color: var(--muted); font-size: 12px; }
.res { display: grid; grid-template-columns: 1.4fr .6fr .6fr .6fr; gap: 8px; padding: 8px 0; border-bottom: 1px solid var(--line); font-size: 14px; }
.res.head { color: var(--muted); font-size: 12px; }
.bar { height: 6px; background: #eef1f6; border-radius: 99px; overflow: hidden; margin-top: 4px; }
.bar i { display: block; height: 100%; background: var(--accent); }
.menu { position: relative; }
.menu-list { position: absolute; right: 0; top: calc(100% + 6px); width: 240px; padding: 10px; background: #fff; border: 1px solid var(--line); border-radius: 10px; box-shadow: var(--shadow); }
.menu-list[hidden] { display: none; }
.menu-list .row label { width: 88px; }
@media (max-width: 720px) { .stats { grid-template-columns: 1fr 1fr; } .res { grid-template-columns: 1fr 1fr; } }
</style>
</head>
<body class="guest">
<main>
<header>
<h1>联通账户 <span class="help" title="只读查看话费和套餐余量。短信登录需要完成页面上的验证码。扫码请用中国联通 App。">?</span></h1>
<div class="menu" id="menu" hidden>
<button class="ghost" id="menuBtn" type="button">设置</button>
<div class="menu-list" id="menuList" hidden>
<div class="row"><label>刷新间隔</label><input id="pollMinutes" type="number" min="1" max="1440"></div>
<div class="row"><label>随机分钟</label><input id="jitterMinutes" type="number" min="0" max="1440"></div>
<div class="row"><label></label><button id="saveInterval" type="button">保存</button></div>
<div class="row"><label></label><button class="ghost" id="logoutBtn" type="button">退出</button></div>
</div>
</div>
</header>
<section id="guest" class="card">
<div class="tabs">
<button type="button" id="tabSms" class="on">短信登录</button>
<button type="button" id="tabQr">扫码登录</button>
</div>
<form id="smsForm">
<div class="row"><label>手机号</label><input id="phone" inputmode="numeric" maxlength="11" autocomplete="tel"></div>
<div class="row"><label>短信码</label><input id="smsCode" inputmode="numeric" maxlength="8" autocomplete="one-time-code"></div>
<div class="row"><label></label><button type="button" id="sendBtn">获取短信</button><button type="submit" id="loginBtn">登录</button></div>
<div class="msg" id="smsMsg"></div>
</form>
<div id="qrBox" hidden>
<div class="qr"><img id="qrImg" alt="登录二维码"></div>
<p class="hint" id="qrHint">请用中国联通 App 扫码,并在手机上确认登录</p>
<div class="row"><label></label><button type="button" id="qrRefresh" class="ghost">刷新二维码</button></div>
</div>
</section>
<section id="home" hidden>
<div class="stats">
<div class="stat"><span>可用余额</span><b id="balance">-</b></div>
<div class="stat"><span>实时话费</span><b id="monthFee">-</b></div>
<div class="stat"><span>剩余流量</span><b id="dataRemain">-</b></div>
<div class="stat"><span>剩余语音</span><b id="voiceRemain">-</b></div>
</div>
<div class="card">
<div id="pkg" class="hint"></div>
<div class="res head"><span>项目</span><span>已用</span><span>剩余</span><span>总量</span></div>
<div id="resources"></div>
<p class="hint" id="updated"></p>
</div>
</section>
</main>
<script>
const $ = (id) => document.getElementById(id);
let mode = "sms";
let ticket = "";
let randstr = "";
let pollTimer = 0;
let viewTimer = 0;
let captchaReady = null;
function setMsg(text, ok) {
$("smsMsg").textContent = text || "";
$("smsMsg").className = ok ? "msg ok" : "msg";
}
async function api(url, opts) {
const res = await fetch(url, opts);
const type = res.headers.get("content-type") || "";
if (type.includes("image")) return res.blob();
const data = await res.json();
if (!res.ok || data.ok === false) throw new Error(data.message || "请求失败");
return data;
}
function loadScript(src) {
return new Promise((resolve, reject) => {
const found = document.querySelector(`script[src="${src}"]`);
if (found) { resolve(); return; }
const s = document.createElement("script");
s.src = src;
s.onload = () => resolve();
s.onerror = () => reject(new Error("验证码脚本没有加载"));
document.head.appendChild(s);
});
}
async function solveCaptcha(view) {
if (!view.captchaScript || !view.captchaAppId) throw new Error("验证码还没准备好");
await loadScript(view.captchaScript);
if (!window.TencentCaptcha) throw new Error("验证码没有就绪");
return new Promise((resolve, reject) => {
const cap = new TencentCaptcha(view.captchaAppId, (res) => {
if (res && res.ret === 0 && res.ticket && res.randstr) resolve(res);
else reject(new Error("验证码未完成"));
}, { userLanguage: "zh-cn" });
cap.show();
});
}
function render(view) {
document.body.classList.toggle("guest", !view.loggedIn);
$("guest").hidden = view.loggedIn;
$("home").hidden = !view.loggedIn;
$("menu").hidden = !view.loggedIn;
if (!view.loggedIn && view.phonePrefill && !$("phone").value) $("phone").value = view.phonePrefill;
if (view.error && !view.loggedIn) setMsg(view.error, false);
$("balance").textContent = view.balance || "-";
$("monthFee").textContent = view.monthFee || "-";
$("dataRemain").textContent = view.dataRemain || "-";
$("voiceRemain").textContent = view.voiceRemain ? view.voiceRemain + " 分钟" : "-";
const who = [view.phoneMasked, view.packageName].filter(Boolean).join(" · ");
$("pkg").textContent = who;
$("pollMinutes").value = view.pollMinutes || 30;
$("jitterMinutes").value = view.jitterMinutes || 0;
const rows = view.resources || [];
$("resources").innerHTML = rows.map((item) => {
const pct = Math.max(0, Math.min(100, item.percent || 0));
return `<div class="res"><div>${item.name || ""}<div class="bar"><i style="width:${pct}%"></i></div></div><div>${item.used || "-"} ${item.unit || ""}</div><div>${item.remain || "-"} ${item.unit || ""}</div><div>${item.total || "-"} ${item.unit || ""}</div></div>`;
}).join("");
const extra = (view.extras || []).map((item) => item.name + " " + item.used).join(" ");
$("updated").textContent = [view.refreshedAt ? "更新于 " + view.refreshedAt : "", view.refreshing ? "正在刷新" : "", view.error || "", extra].filter(Boolean).join(" · ");
}
async function refreshView() {
const view = await api("/api/overview");
render(view);
return view;
}
async function sendSMS() {
setMsg("");
const phone = $("phone").value.trim();
const view = await refreshView();
const solved = await solveCaptcha(view);
ticket = solved.ticket;
randstr = solved.randstr;
$("sendBtn").disabled = true;
try {
const data = await api("/api/sms", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ phone, ticket, randstr }) });
setMsg(data.message || "短信已发送", true);
} finally {
$("sendBtn").disabled = false;
}
}
async function login(event) {
event.preventDefault();
setMsg("");
if (!ticket) { setMsg("请先获取短信"); return; }
$("loginBtn").disabled = true;
try {
await api("/api/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ phone: $("phone").value.trim(), smsCode: $("smsCode").value.trim(), ticket, randstr }) });
ticket = "";
randstr = "";
await refreshView();
} catch (err) {
setMsg(err.message);
} finally {
$("loginBtn").disabled = false;
}
}
function stopQR() {
if (pollTimer) clearInterval(pollTimer);
pollTimer = 0;
}
async function startQR() {
stopQR();
$("qrHint").textContent = "正在获取二维码";
try {
const blob = await api("/api/qr");
$("qrImg").src = URL.createObjectURL(blob);
$("qrHint").textContent = "请用中国联通 App 扫码,并在手机上确认登录";
} catch (err) {
$("qrHint").textContent = err.message;
return;
}
pollTimer = setInterval(async () => {
try {
const data = await api("/api/qr/poll");
if (data.message) $("qrHint").textContent = data.message;
if (data.loggedIn) {
stopQR();
await refreshView();
} else if (data.expired) {
stopQR();
}
} catch (err) {
$("qrHint").textContent = err.message;
stopQR();
}
}, 2000);
}
function showMode(next) {
mode = next;
$("tabSms").classList.toggle("on", next === "sms");
$("tabQr").classList.toggle("on", next === "qr");
$("smsForm").hidden = next !== "sms";
$("qrBox").hidden = next !== "qr";
if (next === "qr") startQR();
else stopQR();
}
$("tabSms").onclick = () => showMode("sms");
$("tabQr").onclick = () => showMode("qr");
$("sendBtn").onclick = () => sendSMS().catch((err) => setMsg(err.message));
$("smsForm").onsubmit = login;
$("qrRefresh").onclick = () => startQR();
$("menuBtn").onclick = () => { $("menuList").hidden = !$("menuList").hidden; };
$("logoutBtn").onclick = async () => {
await api("/api/logout", { method: "POST" });
$("menuList").hidden = true;
await refreshView();
};
$("saveInterval").onclick = async () => {
await api("/api/interval", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pollMinutes: Number($("pollMinutes").value), jitterMinutes: Number($("jitterMinutes").value) }) });
$("menuList").hidden = true;
};
refreshView().catch((err) => setMsg(err.message));
viewTimer = setInterval(() => { if (!$("home").hidden) refreshView().catch(() => {}); }, 5000);
</script>
</body>
</html>