feat: 实现联通话费余量只读面板
This commit is contained in:
@@ -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())
|
||||
}
|
||||
@@ -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, "<")
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package unicom
|
||||
|
||||
import "errors"
|
||||
|
||||
var errBadKey = errors.New("登录公钥无法使用")
|
||||
@@ -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:]
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 ""
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user