完善电竞手册鉴权与诊断日志

This commit is contained in:
yml2213
2026-07-29 14:24:26 +08:00
parent f64838f8db
commit c052a589d1
5 changed files with 359 additions and 61 deletions
+197 -43
View File
@@ -1,12 +1,14 @@
package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"sort"
"strconv"
"strings"
"time"
@@ -258,8 +260,16 @@ func (c *DouyuClient) Score(cookie string) (int, error) {
return result.Data.Balance, nil
}
// GenerateCSRF 调用 generateCsrf,并从 Set-Cookie 中取 cvl_csrf_token。
// GenerateCSRF 生成当前活动需要的鉴权 token。
func (c *DouyuClient) GenerateCSRF(cookie string) (string, error) {
if c.Activity.UseCTN {
ctn, err := c.FetchCTN(cookie)
if err != nil {
return "", fmt.Errorf("获取CTN失败: %w", err)
}
return combineAuthToken("", ctn), nil
}
req, err := http.NewRequest("POST", c.Activity.CSRFURL, nil)
if err != nil {
return "", err
@@ -271,7 +281,7 @@ func (c *DouyuClient) GenerateCSRF(cookie string) (string, error) {
resp, err := c.HTTPClient.Do(req)
if err != nil {
c.Trace.Record("生成CSRF", req, 0, time.Since(start), reqBody, nil, err.Error(), 0, "")
logNetworkError("生成CSRF", req, time.Since(start), err)
c.logNetworkError("生成CSRF", req, time.Since(start), err)
return "", err
}
defer resp.Body.Close()
@@ -279,51 +289,51 @@ func (c *DouyuClient) GenerateCSRF(cookie string) (string, error) {
body, err := io.ReadAll(resp.Body)
if err != nil {
c.Trace.RecordResponse("生成CSRF", req, resp, resp.StatusCode, time.Since(start), reqBody, nil, err.Error(), 0, "")
logNetworkError("生成CSRF", req, time.Since(start), err)
c.logNetworkError("生成CSRF", req, time.Since(start), err)
return "", err
}
if resp.StatusCode != http.StatusOK {
c.Trace.RecordResponse("生成CSRF", req, resp, resp.StatusCode, time.Since(start), reqBody, body, "", 0, "")
logNetworkHTTPError("生成CSRF", req, resp.StatusCode, time.Since(start), body)
c.logNetworkHTTPError("生成CSRF", req, resp.StatusCode, time.Since(start), body)
return "", fmt.Errorf("CSRF HTTP %d: %s", resp.StatusCode, utils.TrimForLog(string(body), 120))
}
var api types.APIResponse
if err := json.Unmarshal(body, &api); err != nil {
c.Trace.RecordResponse("生成CSRF", req, resp, resp.StatusCode, time.Since(start), reqBody, body, err.Error(), 0, "")
logNetworkParseError("生成CSRF", req, time.Since(start), body, err)
c.logNetworkParseError("生成CSRF", req, time.Since(start), body, err)
return "", fmt.Errorf("CSRF 响应解析失败: %w", err)
}
traceErr := ""
if api.Error != 0 {
traceErr = api.Msg
c.Trace.RecordResponse("生成CSRF", req, resp, resp.StatusCode, time.Since(start), reqBody, body, traceErr, api.Error, api.Msg)
logNetworkAPIResult("生成CSRF", req, time.Since(start), api.Error, api.Msg)
c.logNetworkAPIResult("生成CSRF", req, time.Since(start), api.Error, api.Msg)
return "", fmt.Errorf("CSRF 接口失败: %s", api.Msg)
}
for _, ck := range resp.Cookies() {
if ck.Name == "cvl_csrf_token" && ck.Value != "" {
c.Trace.RecordResponse("生成CSRF", req, resp, resp.StatusCode, time.Since(start), reqBody, body, "", api.Error, api.Msg)
logNetworkSuccess("生成CSRF", req, time.Since(start), 0, "")
// 电竞手册还需获取 acf_ccn 作为 ctn,组合返回 csrf\x00ctn
if c.Activity.UseCTN {
ctn, err := c.FetchCTN(utils.MergeCookie(cookie, "cvl_csrf_token", ck.Value))
if err != nil {
return "", fmt.Errorf("获取CTN失败: %w", err)
}
return ck.Value + "\x00" + ctn, nil
}
c.logNetworkSuccess("生成CSRF", req, time.Since(start), 0, "")
return ck.Value, nil
}
}
c.Trace.RecordResponse("生成CSRF", req, resp, resp.StatusCode, time.Since(start), reqBody, body, "响应没有 cvl_csrf_token", api.Error, api.Msg)
logger.LogEvent("网络", "warn", "接口返回异常: 生成CSRF %s %s 耗时=%s msg=响应没有 cvl_csrf_token",
req.Method, requestPath(req), utils.RoundDuration(time.Since(start)))
logger.LogEvent("网络", "warn", "接口返回异常: %s 耗时=%s msg=响应没有 cvl_csrf_token",
c.networkDiagnostic("生成CSRF", req), utils.RoundDuration(time.Since(start)))
return "", errors.New("CSRF 响应没有 cvl_csrf_token")
}
// FetchCTN 调用 csrfNlApi/getCsrfCookie 获取 acf_ccn(电竞手册用 ctn 鉴权)。
// FetchCTN 获取 acf_ccn(电竞手册用 ctn 鉴权)。
func (c *DouyuClient) FetchCTN(cookie string) (string, error) {
if ctn := cookieValue(cookie, "acf_ccn"); ctn != "" {
return ctn, nil
}
if strings.TrimSpace(c.Activity.CTNURL) == "" {
logger.LogEvent("网络", "error", "CTN配置缺失: %s", c.networkDiagnostic("获取CTN", nil))
return "", errors.New("CTNURL 未配置")
}
req, err := http.NewRequest("GET", c.Activity.CTNURL, nil)
if err != nil {
return "", err
@@ -335,18 +345,32 @@ func (c *DouyuClient) FetchCTN(cookie string) (string, error) {
resp, err := c.HTTPClient.Do(req)
if err != nil {
c.Trace.Record("获取CTN", req, 0, time.Since(start), reqBody, nil, err.Error(), 0, "")
c.logNetworkError("获取CTN", req, time.Since(start), err)
return "", err
}
defer resp.Body.Close()
io.ReadAll(resp.Body) // 消费 body
body, err := io.ReadAll(resp.Body)
if err != nil {
c.Trace.RecordResponse("获取CTN", req, resp, resp.StatusCode, time.Since(start), reqBody, nil, err.Error(), 0, "")
c.logNetworkError("获取CTN", req, time.Since(start), err)
return "", err
}
if resp.StatusCode != http.StatusOK {
c.Trace.RecordResponse("获取CTN", req, resp, resp.StatusCode, time.Since(start), reqBody, body, "", 0, "")
c.logNetworkHTTPError("获取CTN", req, resp.StatusCode, time.Since(start), body)
return "", fmt.Errorf("CTN HTTP %d: %s", resp.StatusCode, utils.TrimForLog(string(body), 120))
}
for _, ck := range resp.Cookies() {
if ck.Name == "acf_ccn" && ck.Value != "" {
c.Trace.RecordResponse("获取CTN", req, resp, resp.StatusCode, time.Since(start), reqBody, nil, "", 0, "")
c.Trace.RecordResponse("获取CTN", req, resp, resp.StatusCode, time.Since(start), reqBody, body, "", 0, "")
c.logNetworkSuccess("获取CTN", req, time.Since(start), 0, "")
return ck.Value, nil
}
}
c.Trace.RecordResponse("获取CTN", req, resp, resp.StatusCode, time.Since(start), reqBody, nil, "响应没有 acf_ccn", 0, "")
c.Trace.RecordResponse("获取CTN", req, resp, resp.StatusCode, time.Since(start), reqBody, body, "响应没有 acf_ccn", 0, "")
logger.LogEvent("网络", "warn", "接口返回异常: %s 耗时=%s msg=响应没有 acf_ccn 响应=%s",
c.networkDiagnostic("获取CTN", req), utils.RoundDuration(time.Since(start)), utils.TrimForLog(string(body), 120))
return "", errors.New("CTN 响应没有 acf_ccn")
}
@@ -446,6 +470,9 @@ func (c *DouyuClient) Exchange(cookie, commodityID string, csrf *string) (string
return "", fmt.Errorf("获取CTN失败: %w", err)
}
ctn = ctnVal
if csrf != nil {
*csrf = combineAuthToken(*csrf, ctn)
}
}
if err := c.postMultipart(c.Activity.ExchangeURL, cookie, csrf, "正式兑换", map[string]string{
"manualID": c.Activity.ManualID,
@@ -553,8 +580,9 @@ func (c *DouyuClient) postMultipart(url, cookie string, csrf *string, label stri
if err != nil {
return err
}
req = withFormFieldDiagnostics(req, fields)
// 处理组合 token:csrf\x00ctn(电竞手册用 ctn 鉴权时)
// 拆分后 cvl_csrf_token 和 acf_ccn 都合并到 Cookie 头
// 拆分后按需把 cvl_csrf_token 和 acf_ccn 合并到 Cookie 头
currentCSRF := ""
ctnVal := ""
if csrf != nil {
@@ -564,7 +592,13 @@ func (c *DouyuClient) postMultipart(url, cookie string, csrf *string, label stri
ctnVal = parts[1]
}
}
mergedCookie := utils.MergeCookie(cookie, "cvl_csrf_token", currentCSRF)
if ctnVal == "" && c.Activity.UseCTN {
ctnVal = fields["ctn"]
}
mergedCookie := cookie
if currentCSRF != "" {
mergedCookie = utils.MergeCookie(mergedCookie, "cvl_csrf_token", currentCSRF)
}
if ctnVal != "" {
mergedCookie = utils.MergeCookie(mergedCookie, "acf_ccn", ctnVal)
}
@@ -592,7 +626,7 @@ func (c *DouyuClient) doJSON(req *http.Request, out any, label string) (*http.Re
resp, err := c.HTTPClient.Do(req)
if err != nil {
c.Trace.Record(label, req, 0, time.Since(start), reqBody, nil, err.Error(), 0, "")
logNetworkError(label, req, time.Since(start), err)
c.logNetworkError(label, req, time.Since(start), err)
return nil, err
}
defer resp.Body.Close()
@@ -600,25 +634,25 @@ func (c *DouyuClient) doJSON(req *http.Request, out any, label string) (*http.Re
body, err := io.ReadAll(resp.Body)
if err != nil {
c.Trace.RecordResponse(label, req, resp, resp.StatusCode, time.Since(start), reqBody, nil, err.Error(), 0, "")
logNetworkError(label, req, time.Since(start), err)
c.logNetworkError(label, req, time.Since(start), err)
return resp, err
}
if resp.StatusCode != http.StatusOK {
c.Trace.RecordResponse(label, req, resp, resp.StatusCode, time.Since(start), reqBody, body, "", 0, "")
logNetworkHTTPError(label, req, resp.StatusCode, time.Since(start), body)
c.logNetworkHTTPError(label, req, resp.StatusCode, time.Since(start), body)
return resp, fmt.Errorf("HTTP %d: %s", resp.StatusCode, utils.TrimForLog(string(body), 160))
}
if err := json.Unmarshal(body, out); err != nil {
c.Trace.RecordResponse(label, req, resp, resp.StatusCode, time.Since(start), reqBody, body, err.Error(), 0, "")
logNetworkParseError(label, req, time.Since(start), body, err)
c.logNetworkParseError(label, req, time.Since(start), body, err)
return resp, fmt.Errorf("JSON 解析失败: %w, body=%s", err, utils.TrimForLog(string(body), 160))
}
if apiError, apiMsg, ok := extractAPIStatus(out); ok && apiError != 0 {
c.Trace.RecordResponse(label, req, resp, resp.StatusCode, time.Since(start), reqBody, body, apiMsg, apiError, apiMsg)
logNetworkAPIResult(label, req, time.Since(start), apiError, apiMsg)
c.logNetworkAPIResult(label, req, time.Since(start), apiError, apiMsg)
} else if shouldLogNetworkSuccess(label) {
c.Trace.RecordResponse(label, req, resp, resp.StatusCode, time.Since(start), reqBody, body, "", 0, "")
logNetworkSuccess(label, req, time.Since(start), 0, "")
c.logNetworkSuccess(label, req, time.Since(start), 0, "")
} else {
c.Trace.RecordResponse(label, req, resp, resp.StatusCode, time.Since(start), reqBody, body, "", 0, "")
}
@@ -629,7 +663,7 @@ func shouldLogNetworkSuccess(label string) bool {
return label != "服务时间"
}
func logNetworkSuccess(label string, req *http.Request, cost time.Duration, apiError int, apiMsg string) {
func (c *DouyuClient) logNetworkSuccess(label string, req *http.Request, cost time.Duration, apiError int, apiMsg string) {
if !shouldLogNetworkSuccess(label) {
return
}
@@ -637,27 +671,116 @@ func logNetworkSuccess(label string, req *http.Request, cost time.Duration, apiE
if apiMsg != "" || apiError != 0 {
extra = fmt.Sprintf(" apiError=%d msg=%s", apiError, utils.TrimForLog(apiMsg, 80))
}
logger.LogEvent("网络", "info", "请求完成: %s %s %s 耗时=%s%s", label, req.Method, requestPath(req), utils.RoundDuration(cost), extra)
logger.LogEvent("网络", "info", "请求完成: %s 耗时=%s%s", c.networkDiagnostic(label, req), utils.RoundDuration(cost), extra)
}
func logNetworkAPIResult(label string, req *http.Request, cost time.Duration, apiError int, apiMsg string) {
logger.LogEvent("网络", "warn", "接口返回异常: %s %s %s 耗时=%s apiError=%d msg=%s",
label, req.Method, requestPath(req), utils.RoundDuration(cost), apiError, utils.TrimForLog(apiMsg, 120))
func (c *DouyuClient) logNetworkAPIResult(label string, req *http.Request, cost time.Duration, apiError int, apiMsg string) {
logger.LogEvent("网络", "warn", "接口返回异常: %s 耗时=%s apiError=%d msg=%s",
c.networkDiagnostic(label, req), utils.RoundDuration(cost), apiError, utils.TrimForLog(apiMsg, 120))
}
func logNetworkHTTPError(label string, req *http.Request, status int, cost time.Duration, body []byte) {
logger.LogEvent("网络", "error", "HTTP异常: %s %s %s 状态=%d 耗时=%s 响应=%s",
label, req.Method, requestPath(req), status, utils.RoundDuration(cost), utils.TrimForLog(string(body), 160))
func (c *DouyuClient) logNetworkHTTPError(label string, req *http.Request, status int, cost time.Duration, body []byte) {
logger.LogEvent("网络", "error", "HTTP异常: %s 状态=%d 耗时=%s 响应=%s",
c.networkDiagnostic(label, req), status, utils.RoundDuration(cost), utils.TrimForLog(string(body), 160))
}
func logNetworkParseError(label string, req *http.Request, cost time.Duration, body []byte, err error) {
logger.LogEvent("网络", "error", "响应解析失败: %s %s %s 耗时=%s 错误=%v 响应=%s",
label, req.Method, requestPath(req), utils.RoundDuration(cost), err, utils.TrimForLog(string(body), 160))
func (c *DouyuClient) logNetworkParseError(label string, req *http.Request, cost time.Duration, body []byte, err error) {
logger.LogEvent("网络", "error", "响应解析失败: %s 耗时=%s 错误=%v 响应=%s",
c.networkDiagnostic(label, req), utils.RoundDuration(cost), err, utils.TrimForLog(string(body), 160))
}
func logNetworkError(label string, req *http.Request, cost time.Duration, err error) {
logger.LogEvent("网络", "error", "请求失败: %s %s %s 耗时=%s 错误=%v",
label, req.Method, requestPath(req), utils.RoundDuration(cost), err)
func (c *DouyuClient) logNetworkError(label string, req *http.Request, cost time.Duration, err error) {
logger.LogEvent("网络", "error", "请求失败: %s 耗时=%s 错误=%v",
c.networkDiagnostic(label, req), utils.RoundDuration(cost), err)
}
type networkRequestMetaKey struct{}
type networkRequestMeta struct {
formFields []string
}
func withFormFieldDiagnostics(req *http.Request, fields map[string]string) *http.Request {
if req == nil {
return nil
}
names := sortedFieldNames(fields)
if len(names) == 0 {
return req
}
meta := networkRequestMeta{formFields: names}
return req.WithContext(context.WithValue(req.Context(), networkRequestMetaKey{}, meta))
}
func sortedFieldNames(fields map[string]string) []string {
if len(fields) == 0 {
return nil
}
names := make([]string, 0, len(fields))
for key := range fields {
names = append(names, key)
}
sort.Strings(names)
return names
}
func formFieldNames(req *http.Request) []string {
if req == nil {
return nil
}
meta, ok := req.Context().Value(networkRequestMetaKey{}).(networkRequestMeta)
if !ok || len(meta.formFields) == 0 {
return nil
}
return meta.formFields
}
func (c *DouyuClient) networkDiagnostic(label string, req *http.Request) string {
if strings.TrimSpace(label) == "" {
label = "-"
}
activityName := "-"
activityID := "-"
manualID := "-"
roomID := "-"
actAlias := "-"
useCTN := false
if c != nil && c.Activity != nil {
if c.Activity.DisplayName != "" {
activityName = c.Activity.DisplayName
}
if c.Activity.ID != "" {
activityID = c.Activity.ID
}
if c.Activity.ManualID != "" {
manualID = c.Activity.ManualID
}
if c.Activity.RoomID != "" {
roomID = c.Activity.RoomID
}
if c.Activity.ActAlias != "" {
actAlias = c.Activity.ActAlias
}
useCTN = c.Activity.UseCTN
}
method := "-"
if req != nil && req.Method != "" {
method = req.Method
}
parts := []string{
fmt.Sprintf("活动=%s(%s)", activityName, activityID),
fmt.Sprintf("UseCTN=%t", useCTN),
fmt.Sprintf("label=%s", label),
fmt.Sprintf("method=%s", method),
fmt.Sprintf("path=%s", requestPath(req)),
fmt.Sprintf("manualID=%s", manualID),
fmt.Sprintf("rid=%s", roomID),
fmt.Sprintf("actAlias=%s", actAlias),
}
if fields := formFieldNames(req); len(fields) > 0 {
parts = append(parts, "fields="+strings.Join(fields, ","))
}
return strings.Join(parts, " ")
}
func requestPath(req *http.Request) string {
@@ -667,6 +790,37 @@ func requestPath(req *http.Request) string {
return req.URL.Path
}
func cookieValue(cookie, name string) string {
if strings.TrimSpace(cookie) == "" || strings.TrimSpace(name) == "" {
return ""
}
for _, part := range strings.Split(cookie, ";") {
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
if !ok {
continue
}
if strings.TrimSpace(key) == name {
return strings.TrimSpace(value)
}
}
return ""
}
func combineAuthToken(current, ctn string) string {
if ctn == "" {
return current
}
csrf := ""
if current != "" {
parts := strings.SplitN(current, "\x00", 2)
csrf = parts[0]
}
if csrf == "" {
return "\x00" + ctn
}
return csrf + "\x00" + ctn
}
func extractAPIStatus(out any) (int, string, bool) {
if out == nil {
return 0, "", false