init
This commit is contained in:
@@ -0,0 +1,581 @@
|
||||
package huya
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"huya-go/internal/taf"
|
||||
)
|
||||
|
||||
const (
|
||||
ActivityWebUA = "web&1.0&huya"
|
||||
ActivityRecordUA = "webh5&1.0.0&huya"
|
||||
ActivityBindUA = "pc&1.0.0&huya"
|
||||
ServantWebActUI = "webActUI"
|
||||
FuncGetUserScore = "getUserScore"
|
||||
FuncPrizeList = "getActPrizeList"
|
||||
FuncPrizeRecords = "getUserPrizeRecords"
|
||||
FuncExchangePrize = "scoreExchangePrize"
|
||||
)
|
||||
|
||||
type ActivityUserID struct {
|
||||
UID int64 `json:"uid"`
|
||||
GUID string `json:"guid,omitempty"`
|
||||
Token string `json:"token,omitempty"`
|
||||
HuyaUA string `json:"huya_ua"`
|
||||
Cookie string `json:"-"`
|
||||
TokenType int32 `json:"token_type"`
|
||||
DeviceInfo string `json:"device_info,omitempty"`
|
||||
}
|
||||
|
||||
func NewActivityUserID(uid int64, cookie, ua string) ActivityUserID {
|
||||
return ActivityUserID{
|
||||
UID: uid,
|
||||
HuyaUA: ua,
|
||||
Cookie: NormalizeCookie(cookie),
|
||||
TokenType: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ActivityUserID) WriteTo(w *taf.Writer) error {
|
||||
if err := w.WriteInt64(0, u.UID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(1, u.GUID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(2, u.Token); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(3, u.HuyaUA); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(4, u.Cookie); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteInt32(5, int64(u.TokenType)); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.WriteString(6, u.DeviceInfo)
|
||||
}
|
||||
|
||||
func (u *ActivityUserID) ReadFrom(r *taf.Reader) error {
|
||||
var err error
|
||||
if u.UID, err = r.ReadInt64(0, false, u.UID); err != nil {
|
||||
return err
|
||||
}
|
||||
if u.GUID, err = r.ReadString(1, false, u.GUID); err != nil {
|
||||
return err
|
||||
}
|
||||
if u.Token, err = r.ReadString(2, false, u.Token); err != nil {
|
||||
return err
|
||||
}
|
||||
if u.HuyaUA, err = r.ReadString(3, false, u.HuyaUA); err != nil {
|
||||
return err
|
||||
}
|
||||
if u.Cookie, err = r.ReadString(4, false, u.Cookie); err != nil {
|
||||
return err
|
||||
}
|
||||
if u.TokenType, err = r.ReadInt32(5, false, u.TokenType); err != nil {
|
||||
return err
|
||||
}
|
||||
u.DeviceInfo, err = r.ReadString(6, false, u.DeviceInfo)
|
||||
return err
|
||||
}
|
||||
|
||||
type GetUserScoreReq struct {
|
||||
User ActivityUserID
|
||||
SID int32
|
||||
}
|
||||
|
||||
func (q *GetUserScoreReq) WriteTo(w *taf.Writer) error {
|
||||
if err := w.WriteStruct(0, &q.User); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.WriteInt32(1, int64(q.SID))
|
||||
}
|
||||
|
||||
func (q *GetUserScoreReq) ReadFrom(r *taf.Reader) error {
|
||||
_, err := r.ReadStruct(0, false, &q.User)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
q.SID, err = r.ReadInt32(1, false, q.SID)
|
||||
return err
|
||||
}
|
||||
|
||||
type GetUserScoreResp struct {
|
||||
Status int32 `json:"status"`
|
||||
Msg string `json:"msg"`
|
||||
GainScore int32 `json:"gain_score"`
|
||||
UsedScore int32 `json:"used_score"`
|
||||
NewGainScore int64 `json:"new_gain_score"`
|
||||
NewUsedScore int64 `json:"new_used_score"`
|
||||
Score int64 `json:"score"`
|
||||
IsOpenExchangeTip int32 `json:"is_open_exchange_tip"`
|
||||
}
|
||||
|
||||
func (r *GetUserScoreResp) WriteTo(w *taf.Writer) error { return nil }
|
||||
|
||||
func (r *GetUserScoreResp) ReadFrom(rd *taf.Reader) error {
|
||||
var err error
|
||||
if r.Status, err = rd.ReadInt32(0, false, r.Status); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Msg, err = rd.ReadString(1, false, r.Msg); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.GainScore, err = rd.ReadInt32(2, false, r.GainScore); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.UsedScore, err = rd.ReadInt32(3, false, r.UsedScore); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.NewGainScore, err = rd.ReadInt64(4, false, r.NewGainScore); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.NewUsedScore, err = rd.ReadInt64(5, false, r.NewUsedScore); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Score, err = rd.ReadInt64(6, false, r.Score); err != nil {
|
||||
return err
|
||||
}
|
||||
r.IsOpenExchangeTip, err = rd.ReadInt32(7, false, r.IsOpenExchangeTip)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r GetUserScoreResp) AvailableScore() int64 {
|
||||
if r.NewGainScore != 0 || r.NewUsedScore != 0 {
|
||||
score := r.NewGainScore - r.NewUsedScore
|
||||
if score < 0 {
|
||||
return 0
|
||||
}
|
||||
return score
|
||||
}
|
||||
return r.Score
|
||||
}
|
||||
|
||||
type GetActPrizeListReq struct {
|
||||
User ActivityUserID
|
||||
SID int32
|
||||
}
|
||||
|
||||
func (q *GetActPrizeListReq) WriteTo(w *taf.Writer) error {
|
||||
if err := w.WriteStruct(0, &q.User); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.WriteInt32(1, int64(q.SID))
|
||||
}
|
||||
|
||||
func (q *GetActPrizeListReq) ReadFrom(r *taf.Reader) error {
|
||||
_, err := r.ReadStruct(0, false, &q.User)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
q.SID, err = r.ReadInt32(1, false, q.SID)
|
||||
return err
|
||||
}
|
||||
|
||||
type PrizeInfo struct {
|
||||
ID int64 `json:"id"`
|
||||
SID int64 `json:"sid"`
|
||||
Name string `json:"name"`
|
||||
Score int64 `json:"score"`
|
||||
Type int32 `json:"type"`
|
||||
Image string `json:"img,omitempty"`
|
||||
Sort int32 `json:"sort"`
|
||||
Frequency int32 `json:"frequency"`
|
||||
FrequencyLimit int32 `json:"frequency_limit"`
|
||||
CreateTime int64 `json:"create_time"`
|
||||
Num int64 `json:"num"`
|
||||
Status int32 `json:"status"`
|
||||
Percent string `json:"percent"`
|
||||
NewScore int64 `json:"new_score"`
|
||||
Tags string `json:"tags,omitempty"`
|
||||
LeftNum int64 `json:"left_num"`
|
||||
IsShowNum int32 `json:"is_show_num"`
|
||||
}
|
||||
|
||||
func (p *PrizeInfo) WriteTo(w *taf.Writer) error { return nil }
|
||||
|
||||
func (p *PrizeInfo) ReadFrom(r *taf.Reader) error {
|
||||
var err error
|
||||
if p.ID, err = r.ReadInt64(0, false, p.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.SID, err = r.ReadInt64(1, false, p.SID); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Name, err = r.ReadString(2, false, p.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Score, err = r.ReadInt64(3, false, p.Score); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Type, err = r.ReadInt32(4, false, p.Type); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Image, err = r.ReadString(5, false, p.Image); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Sort, err = r.ReadInt32(6, false, p.Sort); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Frequency, err = r.ReadInt32(7, false, p.Frequency); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.FrequencyLimit, err = r.ReadInt32(8, false, p.FrequencyLimit); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.CreateTime, err = r.ReadInt64(9, false, p.CreateTime); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Num, err = r.ReadInt64(10, false, p.Num); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Status, err = r.ReadInt32(11, false, p.Status); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Percent, err = r.ReadString(12, false, p.Percent); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.NewScore, err = r.ReadInt64(13, false, p.NewScore); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Tags, err = r.ReadString(14, false, p.Tags); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.LeftNum, err = r.ReadInt64(15, false, p.LeftNum); err != nil {
|
||||
return err
|
||||
}
|
||||
p.IsShowNum, err = r.ReadInt32(16, false, p.IsShowNum)
|
||||
return err
|
||||
}
|
||||
|
||||
func (p PrizeInfo) Price() int64 {
|
||||
if p.NewScore != 0 {
|
||||
return p.NewScore
|
||||
}
|
||||
return p.Score
|
||||
}
|
||||
|
||||
func (p PrizeInfo) EstimatedLeft() int64 {
|
||||
if p.LeftNum > 0 {
|
||||
return p.LeftNum
|
||||
}
|
||||
text := strings.TrimSuffix(strings.TrimSpace(p.Percent), "%")
|
||||
if text == "" || p.Num <= 0 {
|
||||
return 0
|
||||
}
|
||||
percent, err := strconv.ParseFloat(text, 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return int64(math.Floor(float64(p.Num)*percent/100.0 + 1e-9))
|
||||
}
|
||||
|
||||
type PrizeTag struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Weight int32 `json:"weight"`
|
||||
}
|
||||
|
||||
func (t *PrizeTag) WriteTo(w *taf.Writer) error { return nil }
|
||||
|
||||
func (t *PrizeTag) ReadFrom(r *taf.Reader) error {
|
||||
var err error
|
||||
if t.ID, err = r.ReadInt64(0, false, t.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if t.Name, err = r.ReadString(1, false, t.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
t.Weight, err = r.ReadInt32(2, false, t.Weight)
|
||||
return err
|
||||
}
|
||||
|
||||
type GetActPrizeListResp struct {
|
||||
Status int32 `json:"status"`
|
||||
Msg string `json:"msg"`
|
||||
Prizes []PrizeInfo `json:"prizes"`
|
||||
ModuleID int32 `json:"module_id"`
|
||||
Tags []PrizeTag `json:"tags"`
|
||||
}
|
||||
|
||||
func (r *GetActPrizeListResp) WriteTo(w *taf.Writer) error { return nil }
|
||||
|
||||
func (r *GetActPrizeListResp) ReadFrom(rd *taf.Reader) error {
|
||||
var err error
|
||||
if r.Status, err = rd.ReadInt32(0, false, r.Status); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Msg, err = rd.ReadString(1, false, r.Msg); err != nil {
|
||||
return err
|
||||
}
|
||||
items, err := rd.ReadListStruct(2, false, func() taf.Unmarshaler { return &PrizeInfo{} })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Prizes = make([]PrizeInfo, 0, len(items))
|
||||
for _, item := range items {
|
||||
if prize, ok := item.(*PrizeInfo); ok {
|
||||
r.Prizes = append(r.Prizes, *prize)
|
||||
}
|
||||
}
|
||||
if r.ModuleID, err = rd.ReadInt32(3, false, r.ModuleID); err != nil {
|
||||
return err
|
||||
}
|
||||
tags, err := rd.ReadListStruct(4, false, func() taf.Unmarshaler { return &PrizeTag{} })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Tags = make([]PrizeTag, 0, len(tags))
|
||||
for _, item := range tags {
|
||||
if tag, ok := item.(*PrizeTag); ok {
|
||||
r.Tags = append(r.Tags, *tag)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type GetUserPrizeRecordsReq struct {
|
||||
User ActivityUserID
|
||||
SID int32
|
||||
}
|
||||
|
||||
func (q *GetUserPrizeRecordsReq) WriteTo(w *taf.Writer) error {
|
||||
if err := w.WriteStruct(0, &q.User); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.WriteInt32(1, int64(q.SID))
|
||||
}
|
||||
|
||||
func (q *GetUserPrizeRecordsReq) ReadFrom(r *taf.Reader) error {
|
||||
_, err := r.ReadStruct(0, false, &q.User)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
q.SID, err = r.ReadInt32(1, false, q.SID)
|
||||
return err
|
||||
}
|
||||
|
||||
type UserPrizeInfo struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Score int64 `json:"score"`
|
||||
CreateTime int64 `json:"create_time"`
|
||||
Status int32 `json:"status"`
|
||||
Type int32 `json:"type"`
|
||||
IsReal int32 `json:"is_real"`
|
||||
NewScore int64 `json:"new_score"`
|
||||
Account string `json:"account,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
CommonPrizeType int32 `json:"common_prize_type"`
|
||||
}
|
||||
|
||||
func (p *UserPrizeInfo) WriteTo(w *taf.Writer) error { return nil }
|
||||
|
||||
func (p *UserPrizeInfo) ReadFrom(r *taf.Reader) error {
|
||||
var err error
|
||||
if p.ID, err = r.ReadInt64(0, false, p.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Name, err = r.ReadString(1, false, p.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Score, err = r.ReadInt64(2, false, p.Score); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.CreateTime, err = r.ReadInt64(3, false, p.CreateTime); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Status, err = r.ReadInt32(4, false, p.Status); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Type, err = r.ReadInt32(5, false, p.Type); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.IsReal, err = r.ReadInt32(6, false, p.IsReal); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.NewScore, err = r.ReadInt64(7, false, p.NewScore); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Account, err = r.ReadString(8, false, p.Account); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Code, err = r.ReadString(9, false, p.Code); err != nil {
|
||||
return err
|
||||
}
|
||||
p.CommonPrizeType, err = r.ReadInt32(10, false, p.CommonPrizeType)
|
||||
return err
|
||||
}
|
||||
|
||||
type GetUserPrizeRecordsResp struct {
|
||||
Status int32 `json:"status"`
|
||||
Msg string `json:"msg"`
|
||||
Records []UserPrizeInfo `json:"records"`
|
||||
}
|
||||
|
||||
func (r *GetUserPrizeRecordsResp) WriteTo(w *taf.Writer) error { return nil }
|
||||
|
||||
func (r *GetUserPrizeRecordsResp) ReadFrom(rd *taf.Reader) error {
|
||||
var err error
|
||||
if r.Status, err = rd.ReadInt32(0, false, r.Status); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Msg, err = rd.ReadString(1, false, r.Msg); err != nil {
|
||||
return err
|
||||
}
|
||||
items, err := rd.ReadListStruct(2, false, func() taf.Unmarshaler { return &UserPrizeInfo{} })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.Records = make([]UserPrizeInfo, 0, len(items))
|
||||
for _, item := range items {
|
||||
if record, ok := item.(*UserPrizeInfo); ok {
|
||||
r.Records = append(r.Records, *record)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type ScoreExchangePrizeReq struct {
|
||||
User ActivityUserID
|
||||
SID int32
|
||||
PID int32
|
||||
IP string
|
||||
ClientEnv map[string]string
|
||||
Source string
|
||||
IsRole int32
|
||||
}
|
||||
|
||||
func (q *ScoreExchangePrizeReq) WriteTo(w *taf.Writer) error {
|
||||
if err := w.WriteStruct(0, &q.User); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteInt32(1, int64(q.SID)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteInt32(2, int64(q.PID)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(3, q.IP); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteMapStringString(4, q.ClientEnv); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(5, q.Source); err != nil {
|
||||
return err
|
||||
}
|
||||
if q.IsRole == 0 {
|
||||
q.IsRole = 1
|
||||
}
|
||||
return w.WriteInt32(6, int64(q.IsRole))
|
||||
}
|
||||
|
||||
func (q *ScoreExchangePrizeReq) ReadFrom(r *taf.Reader) error {
|
||||
_, err := r.ReadStruct(0, false, &q.User)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if q.SID, err = r.ReadInt32(1, false, q.SID); err != nil {
|
||||
return err
|
||||
}
|
||||
if q.PID, err = r.ReadInt32(2, false, q.PID); err != nil {
|
||||
return err
|
||||
}
|
||||
if q.IP, err = r.ReadString(3, false, q.IP); err != nil {
|
||||
return err
|
||||
}
|
||||
if q.ClientEnv, err = r.ReadMapStringString(4, false); err != nil {
|
||||
return err
|
||||
}
|
||||
if q.Source, err = r.ReadString(5, false, q.Source); err != nil {
|
||||
return err
|
||||
}
|
||||
q.IsRole, err = r.ReadInt32(6, false, q.IsRole)
|
||||
return err
|
||||
}
|
||||
|
||||
type ExchangeInfo struct {
|
||||
PID int32 `json:"pid"`
|
||||
ExchangeScore int64 `json:"exchange_score"`
|
||||
Desc string `json:"desc"`
|
||||
}
|
||||
|
||||
func (e *ExchangeInfo) WriteTo(w *taf.Writer) error { return nil }
|
||||
|
||||
func (e *ExchangeInfo) ReadFrom(r *taf.Reader) error {
|
||||
var err error
|
||||
if e.PID, err = r.ReadInt32(1, false, e.PID); err != nil {
|
||||
return err
|
||||
}
|
||||
if e.ExchangeScore, err = r.ReadInt64(2, false, e.ExchangeScore); err != nil {
|
||||
return err
|
||||
}
|
||||
e.Desc, err = r.ReadString(3, false, e.Desc)
|
||||
return err
|
||||
}
|
||||
|
||||
type ActPreCondition struct {
|
||||
ConditionType int32 `json:"condition_type"`
|
||||
ConditionParams map[string]string `json:"condition_params,omitempty"`
|
||||
Tip string `json:"tip,omitempty"`
|
||||
JumpURL string `json:"jump_url,omitempty"`
|
||||
ButtonDesc string `json:"button_desc,omitempty"`
|
||||
}
|
||||
|
||||
func (c *ActPreCondition) WriteTo(w *taf.Writer) error { return nil }
|
||||
|
||||
func (c *ActPreCondition) ReadFrom(r *taf.Reader) error {
|
||||
var err error
|
||||
if c.ConditionType, err = r.ReadInt32(0, false, c.ConditionType); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.ConditionParams, err = r.ReadMapStringString(1, false); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Tip, err = r.ReadString(2, false, c.Tip); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.JumpURL, err = r.ReadString(3, false, c.JumpURL); err != nil {
|
||||
return err
|
||||
}
|
||||
c.ButtonDesc, err = r.ReadString(4, false, c.ButtonDesc)
|
||||
return err
|
||||
}
|
||||
|
||||
type ScoreExchangePrizeResp struct {
|
||||
Status int32 `json:"status"`
|
||||
Msg string `json:"msg"`
|
||||
OrderID string `json:"order_id,omitempty"`
|
||||
ExchangeInfo ExchangeInfo `json:"exchange_info"`
|
||||
ActPreCondition ActPreCondition `json:"act_pre_condition"`
|
||||
}
|
||||
|
||||
func (r *ScoreExchangePrizeResp) WriteTo(w *taf.Writer) error { return nil }
|
||||
|
||||
func (r *ScoreExchangePrizeResp) ReadFrom(rd *taf.Reader) error {
|
||||
var err error
|
||||
if r.Status, err = rd.ReadInt32(0, false, r.Status); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Msg, err = rd.ReadString(1, false, r.Msg); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.OrderID, err = rd.ReadString(3, false, r.OrderID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = rd.ReadStruct(4, false, &r.ExchangeInfo); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = rd.ReadStruct(5, false, &r.ActPreCondition)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r ScoreExchangePrizeResp) Success() bool {
|
||||
return r.Status == 200 && (r.Msg == "" || strings.Contains(r.Msg, "成功"))
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package huya
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"math/rand"
|
||||
"net/url"
|
||||
|
||||
"huya-go/internal/taf"
|
||||
)
|
||||
|
||||
const (
|
||||
HTTPHuyaUA = "webh5&0.0.1&websocket&&diypc_52775"
|
||||
PCUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36"
|
||||
)
|
||||
|
||||
type WSConnectParaInfo struct {
|
||||
UID int64
|
||||
GUID string
|
||||
UA string
|
||||
AppSrc string
|
||||
MID string
|
||||
Exp string
|
||||
TokenType int32
|
||||
Token string
|
||||
Cookie string
|
||||
TraceID string
|
||||
CustomHeaders map[string]string
|
||||
}
|
||||
|
||||
func NewWSConnectParaInfo(uid int64, guid, cookie string) WSConnectParaInfo {
|
||||
return WSConnectParaInfo{
|
||||
UID: uid,
|
||||
GUID: guid,
|
||||
UA: HTTPHuyaUA,
|
||||
AppSrc: "HUYA&ZH&2052",
|
||||
Cookie: cookie,
|
||||
TraceID: NewTraceID(),
|
||||
CustomHeaders: map[string]string{},
|
||||
}
|
||||
}
|
||||
|
||||
func (i WSConnectParaInfo) WriteTo(w *taf.Writer) error {
|
||||
if err := w.WriteInt64(0, i.UID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(1, i.GUID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(2, i.UA); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(3, i.AppSrc); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(4, i.MID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(5, i.Exp); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteInt32(6, int64(i.TokenType)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(7, i.Token); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(8, i.Cookie); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(9, i.TraceID); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.WriteMapStringString(10, i.CustomHeaders)
|
||||
}
|
||||
|
||||
func NewTraceID() string {
|
||||
// 与前端 traceId 格式保持一致:hex16:hex16:0:0。
|
||||
v := rand.Uint64()
|
||||
s := lowerHex16(v)
|
||||
return s + ":" + s + ":0:0"
|
||||
}
|
||||
|
||||
func lowerHex16(v uint64) string {
|
||||
const digits = "0123456789abcdef"
|
||||
var b [16]byte
|
||||
for i := 15; i >= 0; i-- {
|
||||
b[i] = digits[v&0xf]
|
||||
v >>= 4
|
||||
}
|
||||
return string(b[:])
|
||||
}
|
||||
|
||||
func GenerateHTTPBaseinfo(uid int64, guid, cookie string) (string, error) {
|
||||
info := NewWSConnectParaInfo(uid, guid, cookie)
|
||||
w := taf.NewWriter()
|
||||
if err := info.WriteTo(w); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return url.QueryEscape(base64.StdEncoding.EncodeToString(w.Bytes())), nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package huya
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ActivityClient 抽象虎牙活动接口,HTTP 与 WSS 传输都实现它。
|
||||
type ActivityClient interface {
|
||||
GetActPrizeList(ctx context.Context, uid int64, cookie string, sid int32) (*GetActPrizeListResp, error)
|
||||
QueryUserScore(ctx context.Context, uid int64, cookie string, sid int32) (*GetUserScoreResp, error)
|
||||
GetUserPrizeRecords(ctx context.Context, uid int64, cookie string, sid int32) (*GetUserPrizeRecordsResp, error)
|
||||
ScoreExchangePrize(ctx context.Context, uid int64, cookie string, sid, pid int32) (*ScoreExchangePrizeResp, error)
|
||||
}
|
||||
|
||||
// NewActivityClient 按传输层创建活动客户端,供 CLI 和 GUI 共用。
|
||||
func NewActivityClient(transport, wssHost string, timeout time.Duration, logger func(string)) (ActivityClient, func(), error) {
|
||||
switch strings.ToLower(strings.TrimSpace(transport)) {
|
||||
case "", "http":
|
||||
client := NewHTTPClient(logger)
|
||||
if timeout > 0 {
|
||||
client.Client.Timeout = timeout
|
||||
}
|
||||
return client, func() {}, nil
|
||||
case "wss", "ws", "websocket":
|
||||
client := NewWSSClient(logger)
|
||||
if strings.TrimSpace(wssHost) != "" {
|
||||
client.Host = strings.TrimSpace(wssHost)
|
||||
}
|
||||
if timeout > 0 {
|
||||
client.CallTimeout = timeout
|
||||
}
|
||||
return client, func() { _ = client.Close() }, nil
|
||||
default:
|
||||
return nil, func() {}, fmt.Errorf("未知传输层: %s", transport)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package huya
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CookiePair struct {
|
||||
Key string
|
||||
Value string
|
||||
}
|
||||
|
||||
func CookiePairs(cookie string) []CookiePair {
|
||||
parts := strings.Split(cookie, ";")
|
||||
pairs := make([]CookiePair, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
item := strings.TrimSpace(part)
|
||||
if item == "" || !strings.Contains(item, "=") {
|
||||
continue
|
||||
}
|
||||
key, value, _ := strings.Cut(item, "=")
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
pairs = append(pairs, CookiePair{Key: key, Value: strings.TrimSpace(value)})
|
||||
}
|
||||
return pairs
|
||||
}
|
||||
|
||||
func NormalizeCookie(cookie string) string {
|
||||
pairs := CookiePairs(cookie)
|
||||
order := make([]string, 0, len(pairs))
|
||||
values := map[string]string{}
|
||||
for _, pair := range pairs {
|
||||
if _, ok := values[pair.Key]; !ok {
|
||||
order = append(order, pair.Key)
|
||||
}
|
||||
values[pair.Key] = pair.Value
|
||||
}
|
||||
out := make([]string, 0, len(order))
|
||||
for _, key := range order {
|
||||
out = append(out, key+"="+values[key])
|
||||
}
|
||||
return strings.Join(out, "; ")
|
||||
}
|
||||
|
||||
func CookieValue(cookie, key string) string {
|
||||
value := ""
|
||||
for _, pair := range CookiePairs(cookie) {
|
||||
if pair.Key == key {
|
||||
value = pair.Value
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func ResolveUID(cookie string) int64 {
|
||||
for _, key := range []string{"yyuid", "udb_uid", "uid"} {
|
||||
value := CookieValue(cookie, key)
|
||||
if value == "" {
|
||||
continue
|
||||
}
|
||||
uid, err := strconv.ParseInt(value, 10, 64)
|
||||
if err == nil && uid > 0 {
|
||||
return uid
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package huya
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"huya-go/internal/taf"
|
||||
"huya-go/internal/wup"
|
||||
)
|
||||
|
||||
const DefaultCDNWSEndpoint = "https://cdnws.api.huya.com/"
|
||||
|
||||
type HTTPClient struct {
|
||||
Endpoint string
|
||||
Client *http.Client
|
||||
Logger func(string)
|
||||
}
|
||||
|
||||
type CallOptions struct {
|
||||
UID int64
|
||||
GUID string
|
||||
Cookie string
|
||||
RequestID int32
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func NewHTTPClient(logger func(string)) *HTTPClient {
|
||||
return &HTTPClient{
|
||||
Endpoint: DefaultCDNWSEndpoint,
|
||||
Client: &http.Client{
|
||||
Timeout: 15 * time.Second,
|
||||
},
|
||||
Logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HTTPClient) logf(format string, args ...any) {
|
||||
if c.Logger != nil {
|
||||
c.Logger(fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HTTPClient) CallRPC(ctx context.Context, service, method string, reqStruct taf.Marshaler, respStruct taf.Unmarshaler, opt CallOptions) (*wup.Response, error) {
|
||||
if opt.RequestID == 0 {
|
||||
opt.RequestID = 1
|
||||
}
|
||||
reqWup := wup.NewRequest(service, method, opt.RequestID)
|
||||
if err := reqWup.WriteStruct("tReq", reqStruct); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body, err := reqWup.Encode()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
baseinfo, err := GenerateHTTPBaseinfo(opt.UID, opt.GUID, opt.Cookie)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
endpoint := c.Endpoint
|
||||
if endpoint == "" {
|
||||
endpoint = DefaultCDNWSEndpoint
|
||||
}
|
||||
url := endpoint + "?baseinfo=" + baseinfo
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
httpReq.Header.Set("User-Agent", PCUserAgent)
|
||||
httpReq.Header.Set("Origin", "https://zt.huya.com")
|
||||
httpReq.Header.Set("Referer", "https://zt.huya.com/")
|
||||
httpReq.Header.Set("Content-Type", "application/octet-stream")
|
||||
httpReq.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
|
||||
|
||||
client := c.Client
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
if opt.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, opt.Timeout)
|
||||
defer cancel()
|
||||
httpReq = httpReq.WithContext(ctx)
|
||||
}
|
||||
|
||||
c.logf("[HTTP] POST %s.%s body=%dB", service, method, len(body))
|
||||
httpResp, err := client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer httpResp.Body.Close()
|
||||
respBody, err := io.ReadAll(httpResp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(respBody) >= 2 && respBody[0] == 0x1f && respBody[1] == 0x8b {
|
||||
gz, err := gzip.NewReader(bytes.NewReader(respBody))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
respBody, err = io.ReadAll(gz)
|
||||
_ = gz.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("http status %d: %s", httpResp.StatusCode, string(respBody[:min(len(respBody), 200)]))
|
||||
}
|
||||
|
||||
var resp wup.Response
|
||||
if err := resp.Decode(respBody); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if respStruct != nil {
|
||||
ok, err := resp.ReadStruct("tRsp", respStruct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s.%s 响应缺少 tRsp/tResp", service, method)
|
||||
}
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) buildUser(uid int64, cookie, ua string) ActivityUserID {
|
||||
return NewActivityUserID(uid, cookie, ua)
|
||||
}
|
||||
|
||||
func (c *HTTPClient) QueryUserScore(ctx context.Context, uid int64, cookie string, sid int32) (*GetUserScoreResp, error) {
|
||||
req := &GetUserScoreReq{User: c.buildUser(uid, cookie, ActivityWebUA), SID: sid}
|
||||
var resp GetUserScoreResp
|
||||
_, err := c.CallRPC(ctx, ServantWebActUI, FuncGetUserScore, req, &resp, CallOptions{UID: uid, Cookie: cookie, RequestID: 2})
|
||||
return &resp, err
|
||||
}
|
||||
|
||||
func (c *HTTPClient) GetActPrizeList(ctx context.Context, uid int64, cookie string, sid int32) (*GetActPrizeListResp, error) {
|
||||
req := &GetActPrizeListReq{User: c.buildUser(uid, cookie, ActivityWebUA), SID: sid}
|
||||
var resp GetActPrizeListResp
|
||||
_, err := c.CallRPC(ctx, ServantWebActUI, FuncPrizeList, req, &resp, CallOptions{UID: uid, Cookie: cookie, RequestID: 1})
|
||||
return &resp, err
|
||||
}
|
||||
|
||||
func (c *HTTPClient) GetUserPrizeRecords(ctx context.Context, uid int64, cookie string, sid int32) (*GetUserPrizeRecordsResp, error) {
|
||||
user := c.buildUser(uid, cookie, ActivityRecordUA)
|
||||
user.GUID = CookieValue(cookie, "guid")
|
||||
req := &GetUserPrizeRecordsReq{User: user, SID: sid}
|
||||
var resp GetUserPrizeRecordsResp
|
||||
_, err := c.CallRPC(ctx, ServantWebActUI, FuncPrizeRecords, req, &resp, CallOptions{UID: uid, Cookie: cookie, RequestID: 6})
|
||||
return &resp, err
|
||||
}
|
||||
|
||||
func (c *HTTPClient) ScoreExchangePrize(ctx context.Context, uid int64, cookie string, sid, pid int32) (*ScoreExchangePrizeResp, error) {
|
||||
req := &ScoreExchangePrizeReq{
|
||||
User: c.buildUser(uid, cookie, ActivityWebUA),
|
||||
SID: sid,
|
||||
PID: pid,
|
||||
ClientEnv: map[string]string{},
|
||||
IsRole: 1,
|
||||
}
|
||||
var resp ScoreExchangePrizeResp
|
||||
_, err := c.CallRPC(ctx, ServantWebActUI, FuncExchangePrize, req, &resp, CallOptions{UID: uid, Cookie: cookie, RequestID: 1})
|
||||
return &resp, err
|
||||
}
|
||||
@@ -0,0 +1,674 @@
|
||||
package huya
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"huya-go/internal/taf"
|
||||
"huya-go/internal/wup"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultWSSHost = "77bc035c-ws.va.huya.com"
|
||||
DefaultWSSOrigin = "https://zt.huya.com"
|
||||
|
||||
WSSCookieUA = "webh5&0.0.1&websocket&&diypc_52775"
|
||||
WSSBizUA = "web&1.0.0&huya"
|
||||
WSSInitUA = "webh5&0.0.1&websocket&&h5_/index.html"
|
||||
)
|
||||
|
||||
type WSSClient struct {
|
||||
Host string
|
||||
Origin string
|
||||
UserAgent string
|
||||
Dialer *websocket.Dialer
|
||||
Logger func(string)
|
||||
CallTimeout time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
sessions map[string]*WSSSession
|
||||
}
|
||||
|
||||
type WSSSession struct {
|
||||
client *WSSClient
|
||||
uid int64
|
||||
cookie string
|
||||
guid string
|
||||
|
||||
conn *websocket.Conn
|
||||
|
||||
writeMu sync.Mutex
|
||||
pendingMu sync.Mutex
|
||||
pending []chan rpcResult
|
||||
closed chan struct{}
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
|
||||
nextWUPRequestID int32
|
||||
launchGUID string
|
||||
launchIP string
|
||||
}
|
||||
|
||||
type rpcResult struct {
|
||||
body []byte
|
||||
err error
|
||||
}
|
||||
|
||||
func NewWSSClient(logger func(string)) *WSSClient {
|
||||
return &WSSClient{
|
||||
Host: DefaultWSSHost,
|
||||
Origin: DefaultWSSOrigin,
|
||||
UserAgent: PCUserAgent,
|
||||
Logger: logger,
|
||||
CallTimeout: 10 * time.Second,
|
||||
sessions: map[string]*WSSSession{},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *WSSClient) logf(format string, args ...any) {
|
||||
if c.Logger != nil {
|
||||
c.Logger(fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (c *WSSClient) Close() error {
|
||||
c.mu.Lock()
|
||||
sessions := make([]*WSSSession, 0, len(c.sessions))
|
||||
for _, session := range c.sessions {
|
||||
sessions = append(sessions, session)
|
||||
}
|
||||
c.sessions = map[string]*WSSSession{}
|
||||
c.mu.Unlock()
|
||||
|
||||
var firstErr error
|
||||
for _, session := range sessions {
|
||||
if err := session.Close(); err != nil && firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
}
|
||||
return firstErr
|
||||
}
|
||||
|
||||
func (c *WSSClient) session(ctx context.Context, uid int64, cookie string) (*WSSSession, error) {
|
||||
key := strconv.FormatInt(uid, 10)
|
||||
c.mu.Lock()
|
||||
if session := c.sessions[key]; session != nil && !session.isClosed() {
|
||||
c.mu.Unlock()
|
||||
return session, nil
|
||||
}
|
||||
c.mu.Unlock()
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if session := c.sessions[key]; session != nil && !session.isClosed() {
|
||||
return session, nil
|
||||
}
|
||||
session, err := c.dialSession(ctx, uid, cookie)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.sessions[key] = session
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (c *WSSClient) dialSession(ctx context.Context, uid int64, cookie string) (*WSSSession, error) {
|
||||
host := c.Host
|
||||
if host == "" {
|
||||
host = DefaultWSSHost
|
||||
}
|
||||
origin := c.Origin
|
||||
if origin == "" {
|
||||
origin = DefaultWSSOrigin
|
||||
}
|
||||
userAgent := c.UserAgent
|
||||
if userAgent == "" {
|
||||
userAgent = PCUserAgent
|
||||
}
|
||||
|
||||
guid := CookieValue(cookie, "guid")
|
||||
baseinfo, err := GenerateHTTPBaseinfo(uid, guid, NormalizeWSSCookie(cookie))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
wsURL := url.URL{Scheme: "wss", Host: host, Path: "/"}
|
||||
wsURL.RawQuery = "baseinfo=" + baseinfo
|
||||
|
||||
dialer := c.Dialer
|
||||
if dialer == nil {
|
||||
dialer = &websocket.Dialer{
|
||||
HandshakeTimeout: 10 * time.Second,
|
||||
EnableCompression: true,
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
}
|
||||
}
|
||||
headers := http.Header{}
|
||||
headers.Set("Origin", origin)
|
||||
headers.Set("User-Agent", userAgent)
|
||||
headers.Set("Accept-Language", "zh-CN,zh;q=0.9")
|
||||
|
||||
c.logf("[WSS] 连接 %s uid=%d", host, uid)
|
||||
conn, resp, err := dialer.DialContext(ctx, wsURL.String(), headers)
|
||||
if err != nil {
|
||||
if resp != nil {
|
||||
return nil, fmt.Errorf("wss dial: %w (status=%s)", err, resp.Status)
|
||||
}
|
||||
return nil, fmt.Errorf("wss dial: %w", err)
|
||||
}
|
||||
conn.EnableWriteCompression(true)
|
||||
conn.SetReadLimit(4 << 20)
|
||||
|
||||
session := &WSSSession{
|
||||
client: c,
|
||||
uid: uid,
|
||||
cookie: cookie,
|
||||
guid: guid,
|
||||
conn: conn,
|
||||
closed: make(chan struct{}),
|
||||
nextWUPRequestID: 8,
|
||||
}
|
||||
go session.readLoop()
|
||||
go session.heartbeatLoop()
|
||||
|
||||
if err := session.initialize(ctx); err != nil {
|
||||
_ = session.Close()
|
||||
return nil, err
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *WSSSession) isClosed() bool {
|
||||
select {
|
||||
case <-s.closed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *WSSSession) Close() error {
|
||||
var err error
|
||||
s.closeOnce.Do(func() {
|
||||
close(s.closed)
|
||||
err = s.conn.Close()
|
||||
s.failPending(errors.New("wss closed"))
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *WSSSession) readLoop() {
|
||||
for {
|
||||
messageType, raw, err := s.conn.ReadMessage()
|
||||
if err != nil {
|
||||
s.closeWithError(err)
|
||||
return
|
||||
}
|
||||
if messageType != websocket.BinaryMessage {
|
||||
continue
|
||||
}
|
||||
msg, err := DecodeWSSMessage(raw)
|
||||
if err != nil {
|
||||
s.client.logf("[WSS] 解码消息失败: %v", err)
|
||||
continue
|
||||
}
|
||||
switch msg.Command {
|
||||
case WSSCommandRPCResponse:
|
||||
s.resolveNext(rpcResult{body: msg.Body})
|
||||
case WSSCommandHeartbeatRecv:
|
||||
// 心跳响应无需处理。
|
||||
default:
|
||||
s.client.logf("[WSS] 收到 cmd=0x%02x seq=0x%08x body=%dB", msg.Command, msg.Sequence, len(msg.Body))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *WSSSession) heartbeatLoop() {
|
||||
ticker := time.NewTicker(8 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_ = s.sendHeartbeat(ctx)
|
||||
cancel()
|
||||
case <-s.closed:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *WSSSession) closeWithError(err error) {
|
||||
s.closeOnce.Do(func() {
|
||||
s.closeErr = err
|
||||
close(s.closed)
|
||||
_ = s.conn.Close()
|
||||
s.failPending(err)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *WSSSession) failPending(err error) {
|
||||
s.pendingMu.Lock()
|
||||
pending := s.pending
|
||||
s.pending = nil
|
||||
s.pendingMu.Unlock()
|
||||
for _, ch := range pending {
|
||||
ch <- rpcResult{err: err}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *WSSSession) resolveNext(result rpcResult) {
|
||||
s.pendingMu.Lock()
|
||||
if len(s.pending) == 0 {
|
||||
s.pendingMu.Unlock()
|
||||
return
|
||||
}
|
||||
ch := s.pending[0]
|
||||
copy(s.pending, s.pending[1:])
|
||||
s.pending = s.pending[:len(s.pending)-1]
|
||||
s.pendingMu.Unlock()
|
||||
ch <- result
|
||||
}
|
||||
|
||||
func (s *WSSSession) removePending(target chan rpcResult) {
|
||||
s.pendingMu.Lock()
|
||||
defer s.pendingMu.Unlock()
|
||||
for i, ch := range s.pending {
|
||||
if ch == target {
|
||||
copy(s.pending[i:], s.pending[i+1:])
|
||||
s.pending = s.pending[:len(s.pending)-1]
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *WSSSession) writeMessage(ctx context.Context, msg WSSMessage) error {
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
if deadline, ok := ctx.Deadline(); ok {
|
||||
_ = s.conn.SetWriteDeadline(deadline)
|
||||
defer s.conn.SetWriteDeadline(time.Time{})
|
||||
}
|
||||
return s.conn.WriteMessage(websocket.BinaryMessage, msg.Encode())
|
||||
}
|
||||
|
||||
func (s *WSSSession) callRaw(ctx context.Context, msg WSSMessage) ([]byte, error) {
|
||||
ch := make(chan rpcResult, 1)
|
||||
s.pendingMu.Lock()
|
||||
s.pending = append(s.pending, ch)
|
||||
s.pendingMu.Unlock()
|
||||
|
||||
if err := s.writeMessage(ctx, msg); err != nil {
|
||||
s.removePending(ch)
|
||||
return nil, err
|
||||
}
|
||||
select {
|
||||
case result := <-ch:
|
||||
return result.body, result.err
|
||||
case <-ctx.Done():
|
||||
s.removePending(ch)
|
||||
return nil, ctx.Err()
|
||||
case <-s.closed:
|
||||
if s.closeErr != nil {
|
||||
return nil, s.closeErr
|
||||
}
|
||||
return nil, errors.New("wss closed")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *WSSSession) initialize(ctx context.Context) error {
|
||||
if err := s.sendHeartbeat(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.callWSLaunch(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.callGetConfig(ctx); err != nil {
|
||||
s.client.logf("[WSS] getConfig 失败但继续: %v", err)
|
||||
}
|
||||
if s.launchGUID != "" {
|
||||
if err := s.sendRegister(ctx, s.launchGUID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.sendConfirm(ctx)
|
||||
}
|
||||
|
||||
func (s *WSSSession) withTimeout(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
if _, ok := ctx.Deadline(); ok || s.client.CallTimeout <= 0 {
|
||||
return ctx, func() {}
|
||||
}
|
||||
return context.WithTimeout(ctx, s.client.CallTimeout)
|
||||
}
|
||||
|
||||
func (s *WSSSession) sendHeartbeat(ctx context.Context) error {
|
||||
w := taf.NewWriter()
|
||||
if err := w.WriteHead(0, taf.TypeList); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteInt32(0, 1); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(0, "live:0"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(1, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
body := append(append([]byte{}, w.Bytes()...), wssTailBytes...)
|
||||
return s.writeMessage(ctx, WSSMessage{Command: WSSCommandHeartbeatSend, Sequence: wssSeqHeartbeat, Body: body})
|
||||
}
|
||||
|
||||
func (s *WSSSession) callWSLaunch(ctx context.Context) error {
|
||||
req := &wsLaunchReq{}
|
||||
wupReq := wup.NewRequest("launch", "wsLaunch", -1)
|
||||
wupReq.Timeout = 0
|
||||
if err := wupReq.WriteStruct("tReq", req); err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := wupReq.Encode()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
body, err := s.callRaw(ctx, WSSMessage{
|
||||
Command: WSSCommandRPCRequest,
|
||||
Sequence: wssSeqWSLaunch,
|
||||
Body: encodeWSSRPCBody(data),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var resp wup.Response
|
||||
if err := resp.Decode(extractWUPFromWSSBody(body)); err != nil {
|
||||
return err
|
||||
}
|
||||
var launch wsLaunchResp
|
||||
ok, err := resp.ReadStruct("tRsp", &launch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return errors.New("wsLaunch 响应缺少 tRsp")
|
||||
}
|
||||
s.launchGUID = launch.GUID
|
||||
s.launchIP = launch.ClientIP
|
||||
s.client.logf("[WSS] wsLaunch guid=%s ip=%s", launch.GUID, launch.ClientIP)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *WSSSession) callGetConfig(ctx context.Context) error {
|
||||
req := &getConfigReq{}
|
||||
wupReq := wup.NewRequest("mobileui", "getConfig", 7)
|
||||
wupReq.Timeout = 0
|
||||
if err := wupReq.WriteStruct("tReq", req); err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := wupReq.Encode()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
_, err = s.callRaw(ctx, WSSMessage{
|
||||
Command: WSSCommandRPCRequest,
|
||||
Sequence: wssSeqGetConfig,
|
||||
Body: encodeWSSRPCBody(data),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *WSSSession) sendRegister(ctx context.Context, launchGUID string) error {
|
||||
w := taf.NewWriter()
|
||||
if err := w.WriteString(0, "HUYA&ZH&2052"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(1, launchGUID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteInt32(2, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteInt32(3, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteStructBegin(6); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteMapStringString(0, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteMapStringString(1, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteInt32(3, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteStructEnd(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteMapStringString(7, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteInt32(8, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
body := append(append([]byte{}, w.Bytes()...), wssTailBytes...)
|
||||
return s.writeMessage(ctx, WSSMessage{Command: WSSCommandRegister, Sequence: wssSeqRegister, Body: body})
|
||||
}
|
||||
|
||||
func (s *WSSSession) sendConfirm(ctx context.Context) error {
|
||||
w := taf.NewWriter()
|
||||
if err := w.WriteMapStringString(0, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
body := append(append([]byte{}, w.Bytes()...), wssTailBytes...)
|
||||
return s.writeMessage(ctx, WSSMessage{Command: WSSCommandConfirmSend, Sequence: wssSeqConfirm, Body: body})
|
||||
}
|
||||
|
||||
func (s *WSSSession) nextRequestID() int32 {
|
||||
id := s.nextWUPRequestID
|
||||
s.nextWUPRequestID++
|
||||
return id
|
||||
}
|
||||
|
||||
func (s *WSSSession) callRPC(ctx context.Context, service, method string, reqStruct taf.Marshaler, respStruct taf.Unmarshaler) (*wup.Response, error) {
|
||||
wupReq := wup.NewRequest(service, method, s.nextRequestID())
|
||||
wupReq.Timeout = 0
|
||||
if err := wupReq.WriteStruct("tReq", reqStruct); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := wupReq.Encode()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
s.client.logf("[WSS] RPC %s.%s body=%dB", service, method, len(data))
|
||||
body, err := s.callRaw(ctx, WSSMessage{
|
||||
Command: WSSCommandRPCRequest,
|
||||
Sequence: wssSeqBusiness,
|
||||
Body: encodeWSSRPCBody(data),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var resp wup.Response
|
||||
if err := resp.Decode(extractWUPFromWSSBody(body)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if respStruct != nil {
|
||||
ok, err := resp.ReadStruct("tRsp", respStruct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s.%s 响应缺少 tRsp/tResp", service, method)
|
||||
}
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
func (c *WSSClient) buildUser(uid int64, cookie string) ActivityUserID {
|
||||
user := NewActivityUserID(uid, NormalizeWSSCookie(cookie), WSSBizUA)
|
||||
user.GUID = ""
|
||||
user.Token = ""
|
||||
user.DeviceInfo = ""
|
||||
return user
|
||||
}
|
||||
|
||||
func (c *WSSClient) QueryUserScore(ctx context.Context, uid int64, cookie string, sid int32) (*GetUserScoreResp, error) {
|
||||
session, err := c.session(ctx, uid, cookie)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req := &GetUserScoreReq{User: c.buildUser(uid, cookie), SID: sid}
|
||||
var resp GetUserScoreResp
|
||||
_, err = session.callRPC(ctx, ServantWebActUI, FuncGetUserScore, req, &resp)
|
||||
return &resp, err
|
||||
}
|
||||
|
||||
func (c *WSSClient) GetActPrizeList(ctx context.Context, uid int64, cookie string, sid int32) (*GetActPrizeListResp, error) {
|
||||
session, err := c.session(ctx, uid, cookie)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req := &GetActPrizeListReq{User: c.buildUser(uid, cookie), SID: sid}
|
||||
var resp GetActPrizeListResp
|
||||
_, err = session.callRPC(ctx, ServantWebActUI, FuncPrizeList, req, &resp)
|
||||
return &resp, err
|
||||
}
|
||||
|
||||
func (c *WSSClient) GetUserPrizeRecords(ctx context.Context, uid int64, cookie string, sid int32) (*GetUserPrizeRecordsResp, error) {
|
||||
session, err := c.session(ctx, uid, cookie)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req := &GetUserPrizeRecordsReq{User: c.buildUser(uid, cookie), SID: sid}
|
||||
var resp GetUserPrizeRecordsResp
|
||||
_, err = session.callRPC(ctx, ServantWebActUI, FuncPrizeRecords, req, &resp)
|
||||
return &resp, err
|
||||
}
|
||||
|
||||
func (c *WSSClient) ScoreExchangePrize(ctx context.Context, uid int64, cookie string, sid, pid int32) (*ScoreExchangePrizeResp, error) {
|
||||
session, err := c.session(ctx, uid, cookie)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req := &ScoreExchangePrizeReq{
|
||||
User: c.buildUser(uid, cookie),
|
||||
SID: sid,
|
||||
PID: pid,
|
||||
ClientEnv: map[string]string{},
|
||||
IsRole: 1,
|
||||
}
|
||||
var resp ScoreExchangePrizeResp
|
||||
_, err = session.callRPC(ctx, ServantWebActUI, FuncExchangePrize, req, &resp)
|
||||
return &resp, err
|
||||
}
|
||||
|
||||
func NormalizeWSSCookie(cookie string) string {
|
||||
cookie = NormalizeCookie(cookie)
|
||||
pairs := CookiePairs(cookie)
|
||||
out := []string{"huya_ua=" + WSSCookieUA}
|
||||
for _, pair := range pairs {
|
||||
if strings.EqualFold(pair.Key, "huya_ua") {
|
||||
continue
|
||||
}
|
||||
out = append(out, pair.Key+"="+pair.Value)
|
||||
}
|
||||
return strings.Join(out, "; ")
|
||||
}
|
||||
|
||||
type wsLaunchReq struct{}
|
||||
|
||||
func (r *wsLaunchReq) WriteTo(w *taf.Writer) error {
|
||||
if err := w.WriteInt64(0, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(1, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(2, WSSInitUA); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(3, "HUYA&ZH&2052"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteStructBegin(4); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
if err := w.WriteString(i, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return w.WriteStructEnd()
|
||||
}
|
||||
|
||||
type wsLaunchResp struct {
|
||||
GUID string
|
||||
ClientIP string
|
||||
}
|
||||
|
||||
func (r *wsLaunchResp) ReadFrom(rd *taf.Reader) error {
|
||||
var err error
|
||||
if r.GUID, err = rd.ReadString(0, false, r.GUID); err != nil {
|
||||
return err
|
||||
}
|
||||
r.ClientIP, err = rd.ReadString(1, false, r.ClientIP)
|
||||
return err
|
||||
}
|
||||
|
||||
type getConfigReq struct{}
|
||||
|
||||
func (r *getConfigReq) WriteTo(w *taf.Writer) error {
|
||||
if err := w.WriteStructBegin(0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteInt64(0, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(1, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(2, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(3, WSSInitUA); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(4, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteInt32(5, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(6, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(7, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteStructEnd(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteMapStringString(1, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteString(2, "huya"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteHead(3, taf.TypeList); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.WriteInt32(0, 0)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package huya
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
)
|
||||
|
||||
const (
|
||||
WSSCommandRPCRequest byte = 0x03
|
||||
WSSCommandRPCResponse byte = 0x04
|
||||
WSSCommandAuth byte = 0x0a
|
||||
WSSCommandHeartbeatSend byte = 0x10
|
||||
WSSCommandHeartbeatRecv byte = 0x11
|
||||
WSSCommandConfirmSend byte = 0x17
|
||||
WSSCommandRegister byte = 0x21
|
||||
|
||||
wssSeqHeartbeat uint32 = 0x1d00000d
|
||||
wssSeqWSLaunch uint32 = 0x1d000078
|
||||
wssSeqGetConfig uint32 = 0x1d000076
|
||||
wssSeqRegister uint32 = 0x1d00003c
|
||||
wssSeqConfirm uint32 = 0x1d000002
|
||||
wssSeqBusiness uint32 = 0x1d000106
|
||||
)
|
||||
|
||||
var (
|
||||
wssTailBytes = []byte{0x2c, 0x36, 0x00, 0x4c, 0x5c, 0x66, 0x00}
|
||||
wssBigTailSuffix = []byte{0x4c, 0x5c, 0x66, 0x00}
|
||||
)
|
||||
|
||||
// WSSMessage 是虎牙 WebSocketCommand 的 Go 表达。
|
||||
//
|
||||
// 外层格式来自浏览器/参考项目:
|
||||
//
|
||||
// 1B version(0) + 1B command + 4B sequence + body
|
||||
type WSSMessage struct {
|
||||
Command byte
|
||||
Sequence uint32
|
||||
Body []byte
|
||||
}
|
||||
|
||||
func (m WSSMessage) Encode() []byte {
|
||||
out := make([]byte, 6+len(m.Body))
|
||||
out[0] = 0
|
||||
out[1] = m.Command
|
||||
binary.BigEndian.PutUint32(out[2:6], m.Sequence)
|
||||
copy(out[6:], m.Body)
|
||||
return out
|
||||
}
|
||||
|
||||
func DecodeWSSMessage(data []byte) (WSSMessage, error) {
|
||||
if len(data) < 6 {
|
||||
return WSSMessage{}, fmt.Errorf("wss: 消息太短: %d", len(data))
|
||||
}
|
||||
return WSSMessage{
|
||||
Command: data[1],
|
||||
Sequence: binary.BigEndian.Uint32(data[2:6]),
|
||||
Body: append([]byte(nil), data[6:]...),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func encodeWSSRPCBody(wupData []byte) []byte {
|
||||
if len(wupData) < 4 {
|
||||
out := append([]byte{}, wupData...)
|
||||
return append(out, wssTailBytes...)
|
||||
}
|
||||
declaredLen := int(binary.BigEndian.Uint32(wupData[:4]))
|
||||
wupBody := wupData
|
||||
if declaredLen == len(wupData) {
|
||||
wupBody = wupData[4:]
|
||||
}
|
||||
if len(wupBody) <= 0xff {
|
||||
out := append([]byte{}, wupData...)
|
||||
return append(out, wssTailBytes...)
|
||||
}
|
||||
|
||||
trace := NewWSSBigTailTrace()
|
||||
packetLen := len(wupData)
|
||||
out := make([]byte, 0, 1+4+len(wupBody)+len(trace))
|
||||
out = append(out, byte(packetLen&0xff))
|
||||
var lenBuf [4]byte
|
||||
binary.BigEndian.PutUint32(lenBuf[:], uint32(packetLen))
|
||||
out = append(out, lenBuf[:]...)
|
||||
out = append(out, wupBody...)
|
||||
out = append(out, trace...)
|
||||
return out
|
||||
}
|
||||
|
||||
func extractWUPFromWSSBody(body []byte) []byte {
|
||||
if len(body) < 5 {
|
||||
return body
|
||||
}
|
||||
// 大包格式: [1B prefix][4B wup_len][裸 WUP body][tail]
|
||||
wupLen := int(binary.BigEndian.Uint32(body[1:5]))
|
||||
if 5+wupLen <= len(body) && len(body) >= 7 && body[5] == 0x10 && body[6] == 0x03 {
|
||||
return body[5 : 5+wupLen]
|
||||
}
|
||||
// 小包格式: [4B total_len][WUP body][tail]
|
||||
totalLen := int(binary.BigEndian.Uint32(body[:4]))
|
||||
if 8 <= totalLen && totalLen <= len(body) && body[4] == 0x10 && body[5] == 0x03 {
|
||||
return body[:totalLen]
|
||||
}
|
||||
if 5+wupLen <= len(body) {
|
||||
return body[5 : 5+wupLen]
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func NewWSSBigTailTrace() []byte {
|
||||
trace := lowerHex16(rand.Uint64())
|
||||
out := []byte(",6%" + trace + ":" + trace + ":0:3")
|
||||
return append(out, wssBigTailSuffix...)
|
||||
}
|
||||
Reference in New Issue
Block a user