阶段十:完成 Go Xianyu 注释基线清零

This commit is contained in:
Christ committed 2026-08-15 05:05:10 +08:00
1 parent 668a4ed3f3
commit 9255c233aa
53 files changed
+3457 -22590

No files matched your search

+124 -11
View File
@@ -10,6 +10,7 @@ import (
"time"
)
// metadataSnapshotKey 保存metadataSnapshotKey,供当前处理流程使用
const (
metadataSnapshotKey = "cookies_refresh_snapshot"
legacyMetadataSnapshot = "cookie_refresh_snapshot"
@@ -30,12 +31,15 @@ type BrowserCookie struct {
// ParseCookieString 把 Cookie 头解析为 name -> value。
func ParseCookieString(s string) map[string]string {
// out 保存out,供当前处理流程使用
out := make(map[string]string)
// part 表示当前遍历过程中的part
for _, part := range strings.Split(s, ";") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
// eq 保存eq,供当前处理流程使用
eq := strings.Index(part, "=")
if eq <= 0 {
continue
@@ -50,14 +54,18 @@ func MarshalCookieString(m map[string]string) string {
if len(m) == 0 {
return ""
}
// keys 保存keys,供当前处理流程使用
keys := make([]string, 0, len(m))
// k 表示当前遍历过程中的k
for k := range m {
if strings.TrimSpace(k) != "" {
keys = append(keys, k)
}
}
sort.Strings(keys)
// parts 保存parts,供当前处理流程使用
parts := make([]string, 0, len(keys))
// k 表示当前遍历过程中的k
for _, k := range keys {
parts = append(parts, k+"="+m[k])
}
@@ -66,13 +74,18 @@ func MarshalCookieString(m map[string]string) string {
// MergeSetCookies 将 Set-Cookie 响应头合并进原 Cookie 字符串。
func MergeSetCookies(original string, setCookies []string) string {
// m 保存m,供当前处理流程使用
m := ParseCookieString(original)
// raw 表示当前遍历过程中的原始
for _, raw := range setCookies {
// first 保存first,供当前处理流程使用
first := strings.TrimSpace(strings.Split(raw, ";")[0])
// eq 保存eq,供当前处理流程使用
eq := strings.Index(first, "=")
if eq <= 0 {
continue
}
// name 保存名称,供当前处理流程使用
name := strings.TrimSpace(first[:eq])
if name == "" {
continue
@@ -84,19 +97,26 @@ func MergeSetCookies(original string, setCookies []string) string {
// SnapshotFromCookieString 为只有扁平 Cookie 的历史账号建立兼容快照。浏览器刷新后
// 应使用真实快照覆盖它,避免长期依赖推断出的 Domain/Path。
// SnapshotFromCookieString 负责SnapshotFrom登录凭证String相关处理。
func SnapshotFromCookieString(cookieString, domain string) []BrowserCookie {
domain = strings.TrimSpace(domain)
if domain == "" {
domain = ".goofish.com"
}
// values 保存values,供当前处理流程使用
values := ParseCookieString(cookieString)
// names 保存names,供当前处理流程使用
names := make([]string, 0, len(values))
// name 表示当前遍历过程中的名称
for name := range values {
names = append(names, name)
}
sort.Strings(names)
// out 保存out,供当前处理流程使用
out := make([]BrowserCookie, 0, len(names))
// name 表示当前遍历过程中的名称
for _, name := range names {
// value 保存值,供当前处理流程使用
value := values[name]
out = append(out, BrowserCookie{Name: name, Value: value, Domain: domain, Path: "/", Secure: true})
}
@@ -105,15 +125,23 @@ func SnapshotFromCookieString(cookieString, domain string) []BrowserCookie {
// ReconcileSnapshotWithCookieString 在调用方暂时只能获得扁平 Cookie 结果时保留
// 已知属性,并同步值与删除项。新增字段使用 .goofish.com 根路径作为兼容作用域。
// ReconcileSnapshotWithCookieString 负责ReconcileSnapshotWith登录凭证String相关处理。
func ReconcileSnapshotWithCookieString(snapshot []BrowserCookie, cookieString string) []BrowserCookie {
// values 保存values,供当前处理流程使用
values := ParseCookieString(cookieString)
// counts 保存counts,供当前处理流程使用
counts := make(map[string]int, len(snapshot))
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range NormalizeSnapshot(snapshot) {
counts[cookie.Name]++
}
// seen 保存seen,供当前处理流程使用
seen := make(map[string]struct{})
// out 保存out,供当前处理流程使用
out := make([]BrowserCookie, 0, len(snapshot)+len(values))
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range NormalizeSnapshot(snapshot) {
// value、exists 保存value、exists,供当前处理流程使用
value, exists := values[cookie.Name]
if !exists {
continue
@@ -127,15 +155,20 @@ func ReconcileSnapshotWithCookieString(snapshot []BrowserCookie, cookieString st
out = append(out, cookie)
seen[cookie.Name] = struct{}{}
}
// names 保存names,供当前处理流程使用
names := make([]string, 0, len(values))
// name 表示当前遍历过程中的名称
for name := range values {
names = append(names, name)
}
sort.Strings(names)
// name 表示当前遍历过程中的名称
for _, name := range names {
if _, exists := seen[name]; exists {
if // exists 保存exists,供当前处理流程使用
_, exists := seen[name]; exists {
continue
}
// value 保存值,供当前处理流程使用
value := values[name]
out = append(out, BrowserCookie{Name: name, Value: value, Domain: ".goofish.com", Path: "/", Secure: true})
}
@@ -144,7 +177,9 @@ func ReconcileSnapshotWithCookieString(snapshot []BrowserCookie, cookieString st
// CookieHeaderForURL 按浏览器 Domain/Path/Secure/Expires 规则生成指定 URL 的
// Cookie header,并保留不同路径下的同名 Cookie。
// CookieHeaderForURL 负责登录凭证HeaderForURL相关处理。
func CookieHeaderForURL(snapshot []BrowserCookie, rawURL string, now time.Time) string {
// header 保存header,供当前处理流程使用
header, _ := ScopedCookieHeaderForURL(snapshot, rawURL, now)
return header
}
@@ -155,6 +190,7 @@ func CookieHeaderForURL(snapshot []BrowserCookie, rawURL string, now time.Time)
//
// 此简化入口不具备顶级站点上下文,因此不会发送分区 Cookie。需要处理 CHIPS
// 时应使用 ScopedCookieHeaderForRequest 并传入浏览器提供的 PartitionKey。
// ScopedCookieHeaderForURL 负责Scoped登录凭证HeaderForURL相关处理。
func ScopedCookieHeaderForURL(snapshot []BrowserCookie, rawURL string, now time.Time) (string, bool) {
return ScopedCookieHeaderForRequest(snapshot, rawURL, "", now)
}
@@ -164,15 +200,19 @@ func ScopedCookieHeaderForRequest(snapshot []BrowserCookie, rawURL, partitionKey
if snapshot == nil {
return "", false
}
// target、err 保存target、err,供当前处理流程使用
target, err := url.Parse(rawURL)
if err != nil || target.Hostname() == "" {
return "", false
}
// matchedCookie 保存matched登录凭证,供当前处理流程使用
type matchedCookie struct {
cookie BrowserCookie
index int
}
// matched 保存matched,供当前处理流程使用
matched := make([]matchedCookie, 0, len(snapshot))
// index、cookie 表示当前遍历过程中的index、cookie
for index, cookie := range NormalizeSnapshot(snapshot) {
// Unpartitioned cookies are always eligible. Partitioned cookies are
// additionally sent when their key matches the current top-level site.
@@ -196,7 +236,9 @@ func ScopedCookieHeaderForRequest(snapshot []BrowserCookie, rawURL, partitionKey
}
return matched[i].index < matched[j].index
})
// parts 保存parts,供当前处理流程使用
parts := make([]string, 0, len(matched))
// item 表示当前遍历过程中的商品
for _, item := range matched {
parts = append(parts, item.cookie.Name+"="+item.cookie.Value)
}
@@ -205,7 +247,9 @@ func ScopedCookieHeaderForRequest(snapshot []BrowserCookie, rawURL, partitionKey
// ApplySetCookies 把某次请求响应的 Set-Cookie 应用到完整快照。删除操作只删除
// 相同 name/domain/path 的 Cookie,不会误删其他作用域下的同名项。
// ApplySetCookies 负责ApplySetCookies相关处理。
func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []string, now time.Time, partitionKeys ...string) []BrowserCookie {
// target、err 保存target、err,供当前处理流程使用
target, err := url.Parse(requestURL)
if err != nil || target.Hostname() == "" {
return NormalizeSnapshot(snapshot)
@@ -214,23 +258,32 @@ func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []s
// equal paths follows creation time. Keep the input position when replacing an
// existing cookie; if it is deleted and later recreated, append it as a new
// creation, just like Chromium's cookie store.
// state 保存状态,供当前处理流程使用
state := make([]BrowserCookie, 0, len(snapshot)+len(setCookies))
// positions 保存positions,供当前处理流程使用
positions := make(map[string]int, len(snapshot)+len(setCookies))
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range NormalizeSnapshot(snapshot) {
// key 保存key,供当前处理流程使用
key := snapshotKey(cookie)
if index, exists := positions[key]; exists {
if // index、exists 保存index、exists,供当前处理流程使用
index, exists := positions[key]; exists {
state[index] = cookie
continue
}
positions[key] = len(state)
state = append(state, cookie)
}
// raw 表示当前遍历过程中的原始
for _, raw := range setCookies {
// parsed、err 保存parsed、err,供当前处理流程使用
parsed, err := http.ParseSetCookie(raw)
if err != nil || strings.TrimSpace(parsed.Name) == "" {
continue
}
// rawDomain 保存原始Domain,供当前处理流程使用
rawDomain := strings.TrimSpace(parsed.Domain)
// domain 保存domain,供当前处理流程使用
domain := strings.ToLower(rawDomain)
if domain == "" {
domain = strings.ToLower(target.Hostname())
@@ -246,6 +299,7 @@ func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []s
domain = "." + domain
}
}
// cookiePath 保存登录凭证路径,供当前处理流程使用
cookiePath := parsed.Path
if cookiePath == "" {
cookiePath = defaultCookiePath(target.Path)
@@ -261,6 +315,7 @@ func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []s
// __Host- requires Secure, an explicit Path=/, and no Domain attribute.
continue
}
// partitionKey 保存partitionKey,供当前处理流程使用
partitionKey := ""
if parsed.Partitioned {
if !parsed.Secure || len(partitionKeys) == 0 || strings.TrimSpace(partitionKeys[0]) == "" {
@@ -270,6 +325,7 @@ func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []s
}
partitionKey = strings.TrimSpace(partitionKeys[0])
}
// cookie 保存登录凭证,供当前处理流程使用
cookie := BrowserCookie{
Name: parsed.Name, Value: parsed.Value, Domain: domain, Path: cookiePath,
HTTPOnly: parsed.HttpOnly, Secure: parsed.Secure, SameSite: sameSiteLabel(parsed.SameSite), PartitionKey: partitionKey,
@@ -280,18 +336,22 @@ func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []s
} else if !parsed.Expires.IsZero() {
cookie.Expires = float64(parsed.Expires.Unix())
}
// key 保存key,供当前处理流程使用
key := snapshotKey(cookie)
if parsed.MaxAge < 0 || (parsed.MaxAge == 0 && !parsed.Expires.IsZero() && !parsed.Expires.After(now)) {
if index, exists := positions[key]; exists {
if // index、exists 保存index、exists,供当前处理流程使用
index, exists := positions[key]; exists {
state = append(state[:index], state[index+1:]...)
delete(positions, key)
for i := index; i < len(state); i++ {
for // i 保存i,供当前处理流程使用
i := index; i < len(state); i++ {
positions[snapshotKey(state[i])] = i
}
}
continue
}
if index, exists := positions[key]; exists {
if // index、exists 保存index、exists,供当前处理流程使用
index, exists := positions[key]; exists {
state[index] = cookie
continue
}
@@ -301,16 +361,20 @@ func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []s
return NormalizeSnapshot(state)
}
// snapshotKey 负责snapshotKey相关处理。
func snapshotKey(cookie BrowserCookie) string {
return cookie.Name + "\x00" + strings.ToLower(cookie.Domain) + "\x00" + cookie.Path + "\x00" + cookie.PartitionKey
}
// cookieDomainAttributeMatches 负责登录凭证DomainAttributeMatches相关处理。
func cookieDomainAttributeMatches(host, domain string) bool {
host = strings.ToLower(strings.TrimSpace(host))
// base 保存base,供当前处理流程使用
base := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(domain)), ".")
return base != "" && (host == base || strings.HasSuffix(host, "."+base))
}
// cookieDomainMatches 负责登录凭证DomainMatches相关处理。
func cookieDomainMatches(host, domain string) bool {
host = strings.ToLower(strings.TrimSpace(host))
domain = strings.ToLower(strings.TrimSpace(domain))
@@ -318,12 +382,14 @@ func cookieDomainMatches(host, domain string) bool {
return false
}
if strings.HasPrefix(domain, ".") {
// base 保存base,供当前处理流程使用
base := strings.TrimPrefix(domain, ".")
return host == base || strings.HasSuffix(host, "."+base)
}
return host == domain
}
// cookiePathMatches 负责登录凭证路径Matches相关处理。
func cookiePathMatches(requestPath, cookiePath string) bool {
if requestPath == "" {
requestPath = "/"
@@ -340,10 +406,12 @@ func cookiePathMatches(requestPath, cookiePath string) bool {
return strings.HasSuffix(cookiePath, "/") || (len(requestPath) > len(cookiePath) && requestPath[len(cookiePath)] == '/')
}
// defaultCookiePath 负责default登录凭证路径相关处理。
func defaultCookiePath(requestPath string) string {
if requestPath == "" || requestPath[0] != '/' || requestPath == "/" {
return "/"
}
// dir 保存dir,供当前处理流程使用
dir := path.Dir(requestPath)
if dir == "." || dir == "/" {
return "/"
@@ -351,6 +419,7 @@ func defaultCookiePath(requestPath string) string {
return dir
}
// sameSiteLabel 负责sameSiteLabel相关处理。
func sameSiteLabel(value http.SameSite) string {
switch value {
case http.SameSiteStrictMode:
@@ -366,16 +435,23 @@ func sameSiteLabel(value http.SameSite) string {
// ChangedCookieNames 返回两个 Cookie 字符串之间发生变化的字段名。
func ChangedCookieNames(before, after string) []string {
// a 保存a,供当前处理流程使用
a := ParseCookieString(before)
// b 保存b,供当前处理流程使用
b := ParseCookieString(after)
// seen 保存seen,供当前处理流程使用
seen := make(map[string]struct{}, len(a)+len(b))
// k 表示当前遍历过程中的k
for k := range a {
seen[k] = struct{}{}
}
// k 表示当前遍历过程中的k
for k := range b {
seen[k] = struct{}{}
}
// names 保存names,供当前处理流程使用
names := make([]string, 0, len(seen))
// k 表示当前遍历过程中的k
for k := range seen {
if a[k] != b[k] {
names = append(names, k)
@@ -387,19 +463,24 @@ func ChangedCookieNames(before, after string) []string {
// ChangedSnapshotLabels 返回完整浏览器 Cookie 快照变化标签,格式 name@domain/path。
func ChangedSnapshotLabels(before, after []BrowserCookie) []string {
// key 保存key,供当前处理流程使用
key := func(c BrowserCookie) string {
// path 保存路径,供当前处理流程使用
path := c.Path
if path == "" {
path = "/"
}
return c.Name + "|" + c.Domain + "|" + path + "|" + c.PartitionKey
}
// label 保存label,供当前处理流程使用
label := func(c BrowserCookie) string {
// path 保存路径,供当前处理流程使用
path := c.Path
if path == "" {
path = "/"
}
if c.Domain != "" {
// out 保存out,供当前处理流程使用
out := c.Name + "@" + c.Domain + path
if c.PartitionKey != "" {
out += "#" + c.PartitionKey
@@ -408,24 +489,35 @@ func ChangedSnapshotLabels(before, after []BrowserCookie) []string {
}
return c.Name
}
// oldMap 保存oldMap,供当前处理流程使用
oldMap := make(map[string]BrowserCookie)
// newMap 保存newMap,供当前处理流程使用
newMap := make(map[string]BrowserCookie)
// c 表示当前遍历过程中的c
for _, c := range NormalizeSnapshot(before) {
oldMap[key(c)] = c
}
// c 表示当前遍历过程中的c
for _, c := range NormalizeSnapshot(after) {
newMap[key(c)] = c
}
// seen 保存seen,供当前处理流程使用
seen := make(map[string]struct{}, len(oldMap)+len(newMap))
// k 表示当前遍历过程中的k
for k := range oldMap {
seen[k] = struct{}{}
}
// k 表示当前遍历过程中的k
for k := range newMap {
seen[k] = struct{}{}
}
// labels 保存labels,供当前处理流程使用
labels := make([]string, 0, len(seen))
// k 表示当前遍历过程中的k
for k := range seen {
// old 保存old,供当前处理流程使用
old := oldMap[k]
// newCookie 保存new登录凭证,供当前处理流程使用
newCookie := newMap[k]
if old == newCookie {
continue
@@ -442,7 +534,9 @@ func ChangedSnapshotLabels(before, after []BrowserCookie) []string {
// CookieStringFromSnapshot 将浏览器 Cookie 快照压成请求 Cookie 字符串。
func CookieStringFromSnapshot(cookies []BrowserCookie) string {
// parts 保存parts,供当前处理流程使用
parts := make([]string, 0, len(cookies))
// c 表示当前遍历过程中的c
for _, c := range NormalizeSnapshot(cookies) {
if c.Name == "" {
continue
@@ -454,7 +548,9 @@ func CookieStringFromSnapshot(cookies []BrowserCookie) string {
// MergeOriginalFields 补回浏览器未返回但原 Cookie 中存在的字段。
func MergeOriginalFields(original, browserCookieString string) string {
// m 保存m,供当前处理流程使用
m := ParseCookieString(original)
// k、v 表示当前遍历过程中的k、v
for k, v := range ParseCookieString(browserCookieString) {
m[k] = v
}
@@ -463,11 +559,14 @@ func MergeOriginalFields(original, browserCookieString string) string {
// NormalizeSnapshot 补齐默认 path 并保留浏览器返回的创建顺序。Cookie
// header 在 Path 长度相同时必须沿用该顺序,因此不能在这里按名称重排。
// NormalizeSnapshot 归一化Snapshot。
func NormalizeSnapshot(cookies []BrowserCookie) []BrowserCookie {
if cookies == nil {
return nil
}
// out 保存out,供当前处理流程使用
out := make([]BrowserCookie, 0, len(cookies))
// c 表示当前遍历过程中的c
for _, c := range cookies {
if c.Name == "" {
continue
@@ -482,6 +581,7 @@ func NormalizeSnapshot(cookies []BrowserCookie) []BrowserCookie {
// SnapshotFromMetadata 从 cookies.metadata_json 中读取浏览器 Cookie 快照。
func SnapshotFromMetadata(metadata string) []BrowserCookie {
// out 保存out,供当前处理流程使用
out, _ := SnapshotFromMetadataOK(metadata)
return out
}
@@ -489,18 +589,26 @@ func SnapshotFromMetadata(metadata string) []BrowserCookie {
// SnapshotFromMetadataOK 读取完整 Cookie 快照,并报告 metadata 中是否真的
// 存在快照键。存在空数组时返回非 nil 空切片和 true,避免被误当成历史账号
// 而回退到扁平 Cookie。
// SnapshotFromMetadataOK 负责SnapshotFromMetadataOK相关处理。
func SnapshotFromMetadataOK(metadata string) ([]BrowserCookie, bool) {
// m 保存m,供当前处理流程使用
var m map[string]json.RawMessage
if err := json.Unmarshal([]byte(strings.TrimSpace(metadata)), &m); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(strings.TrimSpace(metadata)), &m); err != nil {
return nil, false
}
// out 保存out,供当前处理流程使用
var out []BrowserCookie
if raw := m[metadataSnapshotKey]; len(raw) > 0 {
if err := json.Unmarshal(raw, &out); err != nil {
if // raw 保存原始,供当前处理流程使用
raw := m[metadataSnapshotKey]; len(raw) > 0 {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &out); err != nil {
return nil, false
}
} else if raw := m[legacyMetadataSnapshot]; len(raw) > 0 {
if err := json.Unmarshal(raw, &out); err != nil {
} else if // raw 保存原始,供当前处理流程使用
raw := m[legacyMetadataSnapshot]; len(raw) > 0 {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &out); err != nil {
return nil, false
}
} else {
@@ -514,12 +622,14 @@ func SnapshotFromMetadataOK(metadata string) ([]BrowserCookie, bool) {
// MetadataWithSnapshot 写入浏览器 Cookie 快照,保留 metadata 中的其他键。
func MetadataWithSnapshot(metadata string, cookies []BrowserCookie) string {
// m 保存m,供当前处理流程使用
m := make(map[string]any)
if strings.TrimSpace(metadata) != "" {
_ = json.Unmarshal([]byte(metadata), &m)
}
delete(m, legacyMetadataSnapshot)
m[metadataSnapshotKey] = NormalizeSnapshot(cookies)
// b、err 保存b、err,供当前处理流程使用
b, err := json.Marshal(m)
if err != nil {
return metadata
@@ -532,12 +642,15 @@ func MetadataWithoutSnapshot(metadata string) string {
if strings.TrimSpace(metadata) == "" {
return ""
}
// m 保存m,供当前处理流程使用
m := make(map[string]any)
if err := json.Unmarshal([]byte(metadata), &m); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(metadata), &m); err != nil {
return metadata
}
delete(m, metadataSnapshotKey)
delete(m, legacyMetadataSnapshot)
// b、err 保存b、err,供当前处理流程使用
b, err := json.Marshal(m)
if err != nil {
return metadata
+100 -20
View File
@@ -6,92 +6,122 @@ import (
"time"
)
// TestMetadataSnapshotKeyCompatibility 负责TestMetadataSnapshotKeyCompatibility相关处理。
func TestMetadataSnapshotKeyCompatibility(t *testing.T) {
// oldMeta 保存oldMeta,供当前处理流程使用
oldMeta := `{"cookie_refresh_snapshot":[{"name":"a","value":"1","domain":".goofish.com","path":"/"}]}`
// snapshot 保存snapshot,供当前处理流程使用
snapshot := SnapshotFromMetadata(oldMeta)
if len(snapshot) != 1 || snapshot[0].Name != "a" {
t.Fatalf("旧 key 快照读取失败: %+v", snapshot)
}
// newMeta 保存newMeta,供当前处理流程使用
newMeta := MetadataWithSnapshot(oldMeta, []BrowserCookie{{Name: "b", Value: "2", Domain: ".taobao.com", Path: "/"}})
if SnapshotFromMetadata(newMeta)[0].Name != "b" {
t.Fatalf("新 key 快照写入失败: %s", newMeta)
}
if got := MetadataWithoutSnapshot(newMeta); len(SnapshotFromMetadata(got)) != 0 {
if // got 保存got,供当前处理流程使用
got := MetadataWithoutSnapshot(newMeta); len(SnapshotFromMetadata(got)) != 0 {
t.Fatalf("快照应被清除: %s", got)
}
}
// TestCookieHeaderForURLScopesDomainPathAndSecure 负责Test登录凭证HeaderForURLScopesDomain路径AndSecure相关处理。
func TestCookieHeaderForURLScopesDomainPathAndSecure(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_800_000_000, 0)
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []BrowserCookie{
{Name: "root", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "passport", Value: "2", Domain: "passport.goofish.com", Path: "/newlogin", Secure: true},
{Name: "other", Value: "3", Domain: "h5api.m.goofish.com", Path: "/", Secure: true},
{Name: "expired", Value: "4", Domain: ".goofish.com", Path: "/", Expires: float64(now.Add(-time.Hour).Unix())},
}
// got 保存got,供当前处理流程使用
got := CookieHeaderForURL(snapshot, "https://passport.goofish.com/newlogin/silentHasLogin.do", now)
if got != "passport=2; root=1" {
t.Fatalf("CookieHeaderForURL=%q", got)
}
}
// TestCookieHeaderForURLOrdersLongerPathFirst 负责Test登录凭证HeaderForURL订单列表Longer路径First相关处理。
func TestCookieHeaderForURLOrdersLongerPathFirst(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Now()
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []BrowserCookie{
{Name: "_m_h5_tk", Value: "root_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "im_2", Domain: "www.goofish.com", Path: "/im", Secure: true},
}
// got 保存got,供当前处理流程使用
got := CookieHeaderForURL(snapshot, "https://www.goofish.com/im", now)
if !strings.HasPrefix(got, "_m_h5_tk=im_2; _m_h5_tk=root_1") {
t.Fatalf("longer-path cookie must be first, got %q", got)
}
}
// TestCookieHeaderForURLKeepsCreationOrderForEqualPaths 负责Test登录凭证HeaderForURLKeepsCreation订单ForEqualPaths相关处理。
func TestCookieHeaderForURLKeepsCreationOrderForEqualPaths(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Now()
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []BrowserCookie{
{Name: "third", Value: "3", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "first", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "second", Value: "2", Domain: ".goofish.com", Path: "/", Secure: true},
}
if got := CookieHeaderForURL(snapshot, "https://www.goofish.com/im", now); got != "third=3; first=1; second=2" {
if // got 保存got,供当前处理流程使用
got := CookieHeaderForURL(snapshot, "https://www.goofish.com/im", now); got != "third=3; first=1; second=2" {
t.Fatalf("equal-path creation order lost: %q", got)
}
}
// TestScopedCookieHeaderDistinguishesEmptySnapshotFromUnavailable 负责TestScoped登录凭证HeaderDistinguishesEmptySnapshotFromUnavailable相关处理。
func TestScopedCookieHeaderDistinguishesEmptySnapshotFromUnavailable(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_800_000_000, 0)
if got, ok := ScopedCookieHeaderForURL(nil, "https://www.goofish.com/im", now); ok || got != "" {
if // got、ok 保存got、ok,供当前处理流程使用
got, ok := ScopedCookieHeaderForURL(nil, "https://www.goofish.com/im", now); ok || got != "" {
t.Fatalf("nil snapshot=(%q,%v), want unavailable", got, ok)
}
if got, ok := ScopedCookieHeaderForURL([]BrowserCookie{}, "https://www.goofish.com/im", now); !ok || got != "" {
if // got、ok 保存got、ok,供当前处理流程使用
got, ok := ScopedCookieHeaderForURL([]BrowserCookie{}, "https://www.goofish.com/im", now); !ok || got != "" {
t.Fatalf("empty snapshot=(%q,%v), want authoritative empty", got, ok)
}
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []BrowserCookie{{
Name: "partitioned", Value: "1", Domain: ".goofish.com", Path: "/",
Secure: true, PartitionKey: "https://example.com",
}}
if got, ok := ScopedCookieHeaderForURL(snapshot, "https://www.goofish.com/im", now); !ok || got != "" {
if // got、ok 保存got、ok,供当前处理流程使用
got, ok := ScopedCookieHeaderForURL(snapshot, "https://www.goofish.com/im", now); !ok || got != "" {
t.Fatalf("partitionless request=(%q,%v)", got, ok)
}
if got, ok := ScopedCookieHeaderForRequest(snapshot, "https://www.goofish.com/im", "https://example.com", now); !ok || got != "partitioned=1" {
if // got、ok 保存got、ok,供当前处理流程使用
got, ok := ScopedCookieHeaderForRequest(snapshot, "https://www.goofish.com/im", "https://example.com", now); !ok || got != "partitioned=1" {
t.Fatalf("partitioned request=(%q,%v)", got, ok)
}
}
// TestApplySetCookiesPreservesAttributesAndDeletesExactScope 负责TestApplySetCookiesPreservesAttributesAndDeletesExactScope相关处理。
func TestApplySetCookiesPreservesAttributesAndDeletesExactScope(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_800_000_000, 0)
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []BrowserCookie{
{Name: "sid", Value: "root", Domain: ".goofish.com", Path: "/"},
{Name: "sid", Value: "login", Domain: ".goofish.com", Path: "/newlogin"},
}
// updated 保存updated,供当前处理流程使用
updated := ApplySetCookies(snapshot, "https://passport.goofish.com/newlogin/silentHasLogin.do", []string{
"sid=; Domain=.goofish.com; Path=/newlogin; Max-Age=0",
"fresh=ok; Domain=.goofish.com; Path=/; Secure; HttpOnly; SameSite=None",
}, now)
if got := CookieHeaderForURL(updated, "https://www.goofish.com/", now); !strings.Contains(got, "sid=root") || !strings.Contains(got, "fresh=ok") {
if // got 保存got,供当前处理流程使用
got := CookieHeaderForURL(updated, "https://www.goofish.com/", now); !strings.Contains(got, "sid=root") || !strings.Contains(got, "fresh=ok") {
t.Fatalf("updated header=%q snapshot=%+v", got, updated)
}
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range updated {
if cookie.Name == "sid" && cookie.Path == "/newlogin" {
t.Fatalf("精确作用域删除失败: %+v", updated)
@@ -102,30 +132,38 @@ func TestApplySetCookiesPreservesAttributesAndDeletesExactScope(t *testing.T) {
}
}
// TestApplySetCookiesAcceptsDomainAttributeWithoutLeadingDot 负责TestApplySetCookiesAcceptsDomainAttributeWithoutLeadingDot相关处理。
func TestApplySetCookiesAcceptsDomainAttributeWithoutLeadingDot(t *testing.T) {
// updated 保存updated,供当前处理流程使用
updated := ApplySetCookies(nil, "https://passport.goofish.com/ivCheckLogin.htm", []string{
"unb=777; Domain=goofish.com; Path=/; Secure; HttpOnly",
}, time.Now(), "https://goofish.com")
if len(updated) != 1 || updated[0].Domain != ".goofish.com" || !updated[0].Secure || !updated[0].HTTPOnly {
t.Fatalf("Domain 属性未按域 Cookie 处理: %+v", updated)
}
if got := CookieHeaderForURL(updated, "https://www.goofish.com/im", time.Now()); got != "unb=777" {
if // got 保存got,供当前处理流程使用
got := CookieHeaderForURL(updated, "https://www.goofish.com/im", time.Now()); got != "unb=777" {
t.Fatalf("跨子域 Cookie header=%q", got)
}
}
// TestApplySetCookiesMaxAgeOverridesExpires 负责TestApplySetCookiesMaxAgeOverridesExpires相关处理。
func TestApplySetCookiesMaxAgeOverridesExpires(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_800_000_000, 0)
// updated 保存updated,供当前处理流程使用
updated := ApplySetCookies(nil, "https://www.goofish.com/im", []string{
"sid=fresh; Domain=.goofish.com; Path=/; Max-Age=3600; Expires=Thu, 01 Jan 1970 00:00:00 GMT",
}, now)
if len(updated) != 1 {
t.Fatalf("snapshot=%+v", updated)
}
if got, want := int64(updated[0].Expires), now.Add(time.Hour).Unix(); got != want {
if // got、want 保存got、want,供当前处理流程使用
got, want := int64(updated[0].Expires), now.Add(time.Hour).Unix(); got != want {
t.Fatalf("expires=%d want %d", got, want)
}
// deleted 保存deleted,供当前处理流程使用
deleted := ApplySetCookies(updated, "https://www.goofish.com/im", []string{
"sid=stale; Domain=.goofish.com; Path=/; Max-Age=0; Expires=Thu, 01 Jan 2099 00:00:00 GMT",
}, now)
@@ -134,46 +172,62 @@ func TestApplySetCookiesMaxAgeOverridesExpires(t *testing.T) {
}
}
// TestApplySetCookiesReplacementAndRecreationOrder 负责TestApplySetCookiesReplacementAndRecreation订单相关处理。
func TestApplySetCookiesReplacementAndRecreationOrder(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_800_000_000, 0)
// initial 保存initial,供当前处理流程使用
initial := []BrowserCookie{
{Name: "a", Value: "1", Domain: ".goofish.com", Path: "/"},
{Name: "b", Value: "2", Domain: ".goofish.com", Path: "/"},
{Name: "c", Value: "3", Domain: ".goofish.com", Path: "/"},
}
// replaced 保存replaced,供当前处理流程使用
replaced := ApplySetCookies(initial, "https://www.goofish.com/im", []string{
"b=fresh; Domain=.goofish.com; Path=/",
}, now)
if got := CookieHeaderForURL(replaced, "https://www.goofish.com/im", now); got != "a=1; b=fresh; c=3" {
if // got 保存got,供当前处理流程使用
got := CookieHeaderForURL(replaced, "https://www.goofish.com/im", now); got != "a=1; b=fresh; c=3" {
t.Fatalf("replacement moved cookie: %q", got)
}
// recreated 保存recreated,供当前处理流程使用
recreated := ApplySetCookies(replaced, "https://www.goofish.com/im", []string{
"b=; Domain=.goofish.com; Path=/; Max-Age=0",
"b=recreated; Domain=.goofish.com; Path=/",
}, now)
if got := CookieHeaderForURL(recreated, "https://www.goofish.com/im", now); got != "a=1; c=3; b=recreated" {
if // got 保存got,供当前处理流程使用
got := CookieHeaderForURL(recreated, "https://www.goofish.com/im", now); got != "a=1; c=3; b=recreated" {
t.Fatalf("recreated cookie was not appended: %q", got)
}
}
// TestApplySetCookiesRejectsUnrepresentablePartitionedCookie 负责TestApplySetCookiesRejectsUnrepresentablePartitioned登录凭证相关处理。
func TestApplySetCookiesRejectsUnrepresentablePartitionedCookie(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_800_000_000, 0)
// raw 保存原始,供当前处理流程使用
raw := []string{"chip=value; Domain=.goofish.com; Path=/; Secure; SameSite=None; Partitioned"}
if got := ApplySetCookies(nil, "https://www.goofish.com/im", raw, now); len(got) != 0 {
if // got 保存got,供当前处理流程使用
got := ApplySetCookies(nil, "https://www.goofish.com/im", raw, now); len(got) != 0 {
t.Fatalf("partitioned cookie without key must be rejected: %+v", got)
}
if got := ApplySetCookies(nil, "https://www.goofish.com/im", raw, now, " "); len(got) != 0 {
if // got 保存got,供当前处理流程使用
got := ApplySetCookies(nil, "https://www.goofish.com/im", raw, now, " "); len(got) != 0 {
t.Fatalf("partitioned cookie with empty key must be rejected: %+v", got)
}
// got 保存got,供当前处理流程使用
got := ApplySetCookies(nil, "https://www.goofish.com/im", raw, now, "https://goofish.com")
if len(got) != 1 || got[0].PartitionKey != "https://goofish.com" {
t.Fatalf("valid partitioned cookie missing: %+v", got)
}
}
// TestApplySetCookiesEnforcesSameSiteAndCookiePrefixes 负责TestApplySetCookiesEnforcesSameSiteAnd登录凭证Prefixes相关处理。
func TestApplySetCookiesEnforcesSameSiteAndCookiePrefixes(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_800_000_000, 0)
// updated 保存updated,供当前处理流程使用
updated := ApplySetCookies(nil, "https://www.goofish.com/im", []string{
"none_insecure=1; Domain=.goofish.com; Path=/; SameSite=None",
"none_secure=1; Domain=.goofish.com; Path=/; SameSite=None; Secure",
@@ -183,41 +237,53 @@ func TestApplySetCookiesEnforcesSameSiteAndCookiePrefixes(t *testing.T) {
"__Host-default-path=1; Secure",
"__Host-good=1; Path=/; Secure",
}, now)
// values 保存values,供当前处理流程使用
values := make(map[string]BrowserCookie, len(updated))
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range updated {
values[cookie.Name] = cookie
}
// rejected 表示当前遍历过程中的rejected
for _, rejected := range []string{"none_insecure", "__Secure-bad", "__Host-domain", "__Host-default-path"} {
if _, exists := values[rejected]; exists {
if // exists 保存exists,供当前处理流程使用
_, exists := values[rejected]; exists {
t.Fatalf("invalid cookie %s was accepted: %+v", rejected, updated)
}
}
// accepted 表示当前遍历过程中的accepted
for _, accepted := range []string{"none_secure", "__Secure-good", "__Host-good"} {
if _, exists := values[accepted]; !exists {
if // exists 保存exists,供当前处理流程使用
_, exists := values[accepted]; !exists {
t.Fatalf("valid cookie %s was rejected: %+v", accepted, updated)
}
}
}
// TestSameNameCookiesKeepScopeAndPartitionIdentity 负责TestSame名称CookiesKeepScopeAndPartitionIdentity相关处理。
func TestSameNameCookiesKeepScopeAndPartitionIdentity(t *testing.T) {
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []BrowserCookie{
{Name: "sid", Value: "root", Domain: ".goofish.com", Path: "/"},
{Name: "sid", Value: "im", Domain: ".goofish.com", Path: "/im"},
{Name: "sid", Value: "partitioned", Domain: ".goofish.com", Path: "/", PartitionKey: "https://example.com"},
}
if got := CookieStringFromSnapshot(snapshot); got != "sid=root; sid=im; sid=partitioned" {
if // got 保存got,供当前处理流程使用
got := CookieStringFromSnapshot(snapshot); got != "sid=root; sid=im; sid=partitioned" {
t.Fatalf("flat snapshot lost scoped duplicate: %q", got)
}
// reconciled 保存reconciled,供当前处理流程使用
reconciled := ReconcileSnapshotWithCookieString(snapshot, "sid=new-flat")
if len(reconciled) != 3 {
t.Fatalf("reconciled=%+v", reconciled)
}
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range reconciled {
if cookie.Value == "new-flat" {
t.Fatalf("ambiguous flat value overwrote scoped cookie: %+v", reconciled)
}
}
// updated 保存updated,供当前处理流程使用
updated := ApplySetCookies(snapshot, "https://www.goofish.com/", []string{
"sid=new-root; Domain=.goofish.com; Path=/",
}, time.Unix(1_800_000_000, 0))
@@ -226,40 +292,54 @@ func TestSameNameCookiesKeepScopeAndPartitionIdentity(t *testing.T) {
}
}
// TestSynthesizedSnapshotsRemainDeterministic 负责TestSynthesizedSnapshotsRemainDeterministic相关处理。
func TestSynthesizedSnapshotsRemainDeterministic(t *testing.T) {
// fromFlat 保存fromFlat,供当前处理流程使用
fromFlat := SnapshotFromCookieString("z=3; a=1; m=2", ".goofish.com")
if got := CookieStringFromSnapshot(fromFlat); got != "a=1; m=2; z=3" {
if // got 保存got,供当前处理流程使用
got := CookieStringFromSnapshot(fromFlat); got != "a=1; m=2; z=3" {
t.Fatalf("flat snapshot order=%q", got)
}
// reconciled 保存reconciled,供当前处理流程使用
reconciled := ReconcileSnapshotWithCookieString(
[]BrowserCookie{{Name: "keep", Value: "old", Domain: ".goofish.com", Path: "/"}},
"z=3; keep=new; a=1",
)
if got := CookieStringFromSnapshot(reconciled); got != "keep=new; a=1; z=3" {
if // got 保存got,供当前处理流程使用
got := CookieStringFromSnapshot(reconciled); got != "keep=new; a=1; z=3" {
t.Fatalf("reconciled snapshot order=%q", got)
}
}
// TestSnapshotMetadataReportsAuthoritativeEmptyAndPreservesPartitionKey 负责TestSnapshotMetadataReportsAuthoritativeEmptyAndPreservesPartitionKey相关处理。
func TestSnapshotMetadataReportsAuthoritativeEmptyAndPreservesPartitionKey(t *testing.T) {
if got, ok := SnapshotFromMetadataOK(`{"other":true}`); ok || got != nil {
if // got、ok 保存got、ok,供当前处理流程使用
got, ok := SnapshotFromMetadataOK(`{"other":true}`); ok || got != nil {
t.Fatalf("missing snapshot=(%+v,%v)", got, ok)
}
// metadata 保存metadata,供当前处理流程使用
metadata := MetadataWithSnapshot(`{"other":true}`, []BrowserCookie{})
if got, ok := SnapshotFromMetadataOK(metadata); !ok || got == nil || len(got) != 0 {
if // got、ok 保存got、ok,供当前处理流程使用
got, ok := SnapshotFromMetadataOK(metadata); !ok || got == nil || len(got) != 0 {
t.Fatalf("empty snapshot=(%+v,%v) metadata=%s", got, ok, metadata)
}
metadata = MetadataWithSnapshot("", []BrowserCookie{{
Name: "chip", Value: "secret", Domain: ".goofish.com", Path: "/", PartitionKey: "https://example.com",
}})
// got、ok 保存got、ok,供当前处理流程使用
got, ok := SnapshotFromMetadataOK(metadata)
if !ok || len(got) != 1 || got[0].PartitionKey != "https://example.com" {
t.Fatalf("partition snapshot=(%+v,%v) metadata=%s", got, ok, metadata)
}
}
// TestChangedSnapshotLabels 负责TestChangedSnapshotLabels相关处理。
func TestChangedSnapshotLabels(t *testing.T) {
// before 保存before,供当前处理流程使用
before := []BrowserCookie{{Name: "a", Value: "1", Domain: ".goofish.com", Path: "/"}}
// after 保存after,供当前处理流程使用
after := []BrowserCookie{{Name: "a", Value: "2", Domain: ".goofish.com", Path: "/"}}
// got 保存got,供当前处理流程使用
got := ChangedSnapshotLabels(before, after)
if len(got) != 1 || got[0] != "[email protected]/" {
t.Fatalf("ChangedSnapshotLabels=%v", got)
+72 -11
View File
@@ -13,6 +13,7 @@ import (
"xianyu-go/internal/xianyu/protocol"
)
// RateCreateAPI 保存RateCreateAPI,供当前处理流程使用
const (
RateCreateAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.rate.create/4.0/"
PendingRateListAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.merchant.rate.list/1.0/"
@@ -20,22 +21,26 @@ const (
PolishItemBackupAPI = "https://h5api.m.goofish.com/h5/mtop.idle.item.polish/1.0/"
)
// PendingRateOrder 保存PendingRate订单,供当前处理流程使用
type PendingRateOrder struct {
TradeID string `json:"trade_id"`
ItemID string `json:"item_id"`
}
// PendingRateResult 保存PendingRate结果,供当前处理流程使用
type PendingRateResult struct {
Orders []PendingRateOrder
UpdatedCookies string
}
// AccountTaskResult 保存账号任务结果,供当前处理流程使用
type AccountTaskResult struct {
Success bool
Message string
UpdatedCookies string
}
// FetchPendingRateOrders 负责FetchPendingRate订单列表相关处理。
func (c *ClientImpl) FetchPendingRateOrders(ctx context.Context, cookiesStr string, page, pageSize int) (*PendingRateResult, error) {
if page < 1 {
page = 1
@@ -43,23 +48,32 @@ func (c *ClientImpl) FetchPendingRateOrders(ctx context.Context, cookiesStr stri
if pageSize < 1 || pageSize > 100 {
pageSize = 50
}
// data 保存数据,供当前处理流程使用
data := map[string]any{"pageNumber": page, "rowsPerPage": pageSize, "queryType": "ORDER",
"rateSearchParam": map[string]any{"sellerRateStatus": "5"}}
// decoded、updated、err 保存decoded、updated、err,供当前处理流程使用
decoded, updated, err := c.accountTaskRequest(ctx, cookiesStr, firstNonEmptyURL(c.RateListURL, PendingRateListAPI),
"mtop.taobao.idle.merchant.rate.list", "1.0", data, "https://seller.goofish.com/")
if err != nil {
return nil, err
}
// module 保存module,供当前处理流程使用
module, _ := decoded.Data["module"].(map[string]any)
// items 保存商品列表,供当前处理流程使用
items, _ := module["items"].([]any)
// orders 保存订单列表,供当前处理流程使用
orders := make([]PendingRateOrder, 0, len(items))
// seen 保存seen,供当前处理流程使用
seen := make(map[string]struct{}, len(items))
// item 表示当前遍历过程中的商品
for _, item := range items {
// tradeID 保存tradeID,供当前处理流程使用
tradeID := findStringField(item, "tradeId", "trade_id", "orderId", "orderNo", "order_no")
if tradeID == "" {
continue
}
if _, ok := seen[tradeID]; ok {
if // ok 保存ok,供当前处理流程使用
_, ok := seen[tradeID]; ok {
continue
}
seen[tradeID] = struct{}{}
@@ -69,11 +83,13 @@ func (c *ClientImpl) FetchPendingRateOrders(ctx context.Context, cookiesStr stri
return &PendingRateResult{Orders: orders, UpdatedCookies: updated}, nil
}
// RateBuyer 负责Rate买家相关处理。
func (c *ClientImpl) RateBuyer(ctx context.Context, cookiesStr, tradeID, feedback string) (*AccountTaskResult, error) {
feedback = strings.TrimSpace(feedback)
if feedback == "" {
feedback = "不错的买家,交易愉快"
}
// decoded、updated、err 保存decoded、updated、err,供当前处理流程使用
decoded, updated, err := c.accountTaskRequest(ctx, cookiesStr, firstNonEmptyURL(c.RateCreateURL, RateCreateAPI),
"mtop.taobao.idle.rate.create", "4.0", map[string]any{
"tradeId": tradeID, "rate": 1, "feedback": feedback, "createOrAppend": 0,
@@ -84,7 +100,9 @@ func (c *ClientImpl) RateBuyer(ctx context.Context, cookiesStr, tradeID, feedbac
return &AccountTaskResult{Success: true, Message: firstRet(decoded.Ret), UpdatedCookies: updated}, nil
}
// PolishItem 负责Polish商品相关处理。
func (c *ClientImpl) PolishItem(ctx context.Context, cookiesStr, itemID string) (*AccountTaskResult, error) {
// decoded、updated、err 保存decoded、updated、err,供当前处理流程使用
decoded, updated, err := c.accountTaskRequest(ctx, cookiesStr, firstNonEmptyURL(c.PolishItemURL, PolishItemAPI),
"mtop.taobao.idle.item.polish", "2.0", map[string]any{"itemId": itemID}, "https://www.goofish.com/")
if err == nil {
@@ -96,10 +114,12 @@ func (c *ClientImpl) PolishItem(ctx context.Context, cookiesStr, itemID string)
if IsSessionExpiredErr(err) || IsRiskVerificationErr(err) {
return nil, err
}
// primaryErr 保存primaryErr,供当前处理流程使用
primaryErr := err
if strings.TrimSpace(updated) == "" {
updated = cookiesStr
}
// decoded、backupUpdated、backupErr 保存decoded、backupUpdated、backupErr,供当前处理流程使用
decoded, backupUpdated, backupErr := c.accountTaskRequest(ctx, updated,
firstNonEmptyURL(c.PolishItemBackupURL, PolishItemBackupAPI), "mtop.idle.item.polish", "1.0",
map[string]any{"itemId": itemID}, "https://www.goofish.com/")
@@ -112,27 +132,36 @@ func (c *ClientImpl) PolishItem(ctx context.Context, cookiesStr, itemID string)
return nil, fmt.Errorf("擦亮主接口失败: %v;备用接口失败: %w", primaryErr, backupErr)
}
// duplicatePolishError 负责duplicatePolish错误相关处理。
func duplicatePolishError(err error) bool {
if err == nil {
return false
}
// msg 保存msg,供当前处理流程使用
msg := err.Error()
return strings.Contains(msg, "IDLEITEM_POLISH_AGAIN") || strings.Contains(msg, "已经擦亮") ||
strings.Contains(msg, "POLISH_DUPLICATE") || strings.Contains(msg, "一天只能擦亮一次")
}
// accountTaskResponse 保存账号任务响应,供当前处理流程使用
type accountTaskResponse struct {
Ret []string `json:"ret"`
Data map[string]any `json:"data"`
}
// accountTaskRequest 负责账号任务请求相关处理。
func (c *ClientImpl) accountTaskRequest(ctx context.Context, cookiesStr, endpoint, api, version string, data map[string]any, referer string) (*accountTaskResponse, string, error) {
// current 保存current,供当前处理流程使用
current := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
current, _, _ = session.State()
}
// lastRet 保存lastRet,供当前处理流程使用
var lastRet []string
for attempt := 0; attempt < 3; attempt++ {
for // attempt 保存尝试次数,供当前处理流程使用
attempt := 0; attempt < 3; attempt++ {
// decoded、updated、err 保存decoded、updated、err,供当前处理流程使用
decoded, updated, err := c.accountTaskRequestOnce(ctx, current, endpoint, api, version, data, referer)
if err != nil {
return nil, current, err
@@ -152,38 +181,49 @@ func (c *ClientImpl) accountTaskRequest(ctx context.Context, cookiesStr, endpoin
}
current = updated
if current == cookiesStr {
// refreshed、refreshErr 保存refreshed、refreshErr,供当前处理流程使用
refreshed, refreshErr := c.RefreshTokenContext(ctx, current)
if refreshErr != nil {
return nil, current, fmt.Errorf("刷新 mtop token: %w", refreshErr)
}
current = refreshed.UpdatedCookies
}
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
if // err 保存err,供当前处理流程使用
err := sleepCtx(ctx, MTopRetryGap); err != nil {
return nil, current, err
}
}
return nil, current, fmt.Errorf("%s token 重试失败: %s", api, firstRet(lastRet))
}
// accountTaskRequestOnce 负责账号任务请求Once相关处理。
func (c *ClientImpl) accountTaskRequestOnce(ctx context.Context, cookiesStr, endpoint, api, version string, data map[string]any, referer string) (*accountTaskResponse, string, error) {
// signingCookies、requestCookies 保存signingCookies、requestCookies,供当前处理流程使用
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, referer, endpoint)
// token 保存令牌,供当前处理流程使用
token := protocol.SignToken(signingCookies)
if token == "" {
return nil, cookiesStr, fmt.Errorf("cookie 缺少 _m_h5_tk,无法调用 %s", api)
}
// rawData、err 保存原始Data、err,供当前处理流程使用
rawData, err := json.Marshal(data)
if err != nil {
return nil, cookiesStr, err
}
// dataVal 保存数据Val,供当前处理流程使用
dataVal := string(rawData)
// t 保存t,供当前处理流程使用
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
// sign 保存sign,供当前处理流程使用
sign := protocol.GenerateSign(t, token, dataVal)
// query 保存查询,供当前处理流程使用
query := url.Values{}
query.Set("jsv", "2.7.2")
query.Set("appKey", protocol.SignAppKey)
query.Set("t", t)
query.Set("sign", sign)
query.Set("v", version)
// responseType 保存响应类型,供当前处理流程使用
responseType := "originaljson"
if api == "mtop.taobao.idle.merchant.rate.list" {
responseType = "json"
@@ -200,6 +240,7 @@ func (c *ClientImpl) accountTaskRequestOnce(ctx context.Context, cookiesStr, end
query.Set("spm_pre", "a21ybx.home.sidebar.2.4c053da6MpVe1m")
query.Set("log_id", "4c053da6MpVe1m")
}
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+query.Encode(),
strings.NewReader("data="+url.QueryEscape(dataVal)))
if err != nil {
@@ -207,26 +248,33 @@ func (c *ClientImpl) accountTaskRequestOnce(ctx context.Context, cookiesStr, end
}
setCommonHeaders(req, requestCookies)
req.Header.Set("Referer", referer)
if parsedReferer, parseErr := url.Parse(referer); parseErr == nil && parsedReferer.Scheme != "" && parsedReferer.Host != "" {
if // parsedReferer、parseErr 保存解析结果Referer、parseErr,供当前处理流程使用
parsedReferer, parseErr := url.Parse(referer); parseErr == nil && parsedReferer.Scheme != "" && parsedReferer.Host != "" {
req.Header.Set("Origin", parsedReferer.Scheme+"://"+parsedReferer.Host)
}
// resp、err 保存resp、err,供当前处理流程使用
resp, err := c.httpClientWithTimeout(25 * time.Second).Do(req)
if err != nil {
return nil, cookiesStr, err
}
defer resp.Body.Close()
// updated 保存updated,供当前处理流程使用
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readMTopBody(resp)
if err != nil {
return nil, updated, err
}
// decoded 保存decoded,供当前处理流程使用
var decoded accountTaskResponse
if err := json.Unmarshal(raw, &decoded); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &decoded); err != nil {
return nil, updated, fmt.Errorf("解析 %s 响应: %w", api, err)
}
return &decoded, updated, nil
}
// firstRet 负责firstRet相关处理。
func firstRet(ret []string) string {
if len(ret) == 0 {
return "未知响应"
@@ -234,6 +282,7 @@ func firstRet(ret []string) string {
return ret[0]
}
// firstNonEmptyURL 负责firstNonEmptyURL相关处理。
func firstNonEmptyURL(configured, fallback string) string {
if strings.TrimSpace(configured) != "" {
return configured
@@ -241,30 +290,42 @@ func firstNonEmptyURL(configured, fallback string) string {
return fallback
}
// findStringField 负责findString字段相关处理。
func findStringField(value any, keys ...string) string {
// wanted 保存wanted,供当前处理流程使用
wanted := make(map[string]struct{}, len(keys))
// key 表示当前遍历过程中的key
for _, key := range keys {
wanted[key] = struct{}{}
}
// walk 保存walk,供当前处理流程使用
var walk func(any) string
walk = func(v any) string {
switch x := v.(type) {
switch // x 保存x,供当前处理流程使用
x := v.(type) {
case map[string]any:
// key、child 表示当前遍历过程中的key、child
for key, child := range x {
if _, ok := wanted[key]; ok {
if text := mtopString(child); text != "" {
if // ok 保存ok,供当前处理流程使用
_, ok := wanted[key]; ok {
if // text 保存文本,供当前处理流程使用
text := mtopString(child); text != "" {
return text
}
}
}
// child 表示当前遍历过程中的child
for _, child := range x {
if text := walk(child); text != "" {
if // text 保存文本,供当前处理流程使用
text := walk(child); text != "" {
return text
}
}
case []any:
// child 表示当前遍历过程中的child
for _, child := range x {
if text := walk(child); text != "" {
if // text 保存文本,供当前处理流程使用
text := walk(child); text != "" {
return text
}
}
@@ -11,37 +11,49 @@ import (
// TestLivePolishAccount is opt-in because it calls the real Xianyu APIs and
// changes the selected account's daily polish state. It never logs credentials.
// TestLivePolishAccount 负责TestLivePolish账号相关处理。
func TestLivePolishAccount(t *testing.T) {
if os.Getenv("TEST_XIANYU_LIVE") != "1" {
t.Skip("set TEST_XIANYU_LIVE=1 to run against a real account")
}
// dbURL 保存dbURL,供当前处理流程使用
dbURL := os.Getenv("TEST_XIANYU_DB_URL")
// accountID 保存账号ID,供当前处理流程使用
accountID := os.Getenv("TEST_XIANYU_ACCOUNT_ID")
if dbURL == "" || accountID == "" {
t.Fatal("TEST_XIANYU_DB_URL and TEST_XIANYU_ACCOUNT_ID are required")
}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
// database、dialect、err 保存database、dialect、err,供当前处理流程使用
database, dialect, err := db.Open(ctx, dbURL)
if err != nil {
t.Fatalf("open test database: %v", err)
}
defer database.Close()
// store 保存store,供当前处理流程使用
store := db.NewStore(database, dialect)
// cookies、err 保存cookies、err,供当前处理流程使用
cookies, err := store.Cookies.GetValue(ctx, accountID)
if err != nil {
t.Fatalf("read account credentials: %v", err)
}
// client 保存client,供当前处理流程使用
client := &ClientImpl{}
// items、err 保存items、err,供当前处理流程使用
items, err := client.FetchAllItems(ctx, cookies, 20, 20)
if err != nil {
t.Fatalf("fetch live items: %v", err)
}
// current 保存current,供当前处理流程使用
current := cookies
if items.UpdatedCookies != "" {
current = items.UpdatedCookies
}
// item 表示当前遍历过程中的商品
for _, item := range items.Items {
// result、polishErr 保存result、polishErr,供当前处理流程使用
result, polishErr := client.PolishItem(ctx, current, item.ID)
if polishErr != nil || result == nil || !result.Success {
t.Fatalf("polish item %s: result=%+v err=%v", item.ID, result, polishErr)
+34 -4
View File
@@ -9,13 +9,18 @@ import (
"testing"
)
// TestAccountTaskEndpointsAndParsing 负责Test账号任务EndpointsAndParsing相关处理。
func TestAccountTaskEndpointsAndParsing(t *testing.T) {
// received 保存received,供当前处理流程使用
var received map[string]any
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
if // err 保存err,供当前处理流程使用
err := r.ParseForm(); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal([]byte(r.Form.Get("data")), &received); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(r.Form.Get("data")), &received); err != nil {
t.Fatalf("decode data: %v", err)
}
w.Header().Set("Content-Type", "application/json")
@@ -32,27 +37,35 @@ func TestAccountTaskEndpointsAndParsing(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), RateListURL: server.URL, RateCreateURL: server.URL, PolishItemURL: server.URL}
// cookies 保存cookies,供当前处理流程使用
cookies := "unb=123; _m_h5_tk=token_1"
// pending、err 保存pending、err,供当前处理流程使用
pending, err := client.FetchPendingRateOrders(context.Background(), cookies, 1, 50)
if err != nil || len(pending.Orders) != 2 || pending.Orders[0].TradeID != "order-1" || pending.Orders[0].ItemID != "item-1" {
t.Fatalf("pending=%+v err=%v", pending, err)
}
// rate、err 保存rate、err,供当前处理流程使用
rate, err := client.RateBuyer(context.Background(), cookies, "order-1", "交易愉快")
if err != nil || !rate.Success || received["tradeId"] != "order-1" || received["feedback"] != "交易愉快" {
t.Fatalf("rate=%+v received=%+v err=%v", rate, received, err)
}
// polish、err 保存polish、err,供当前处理流程使用
polish, err := client.PolishItem(context.Background(), cookies, "item-1")
if err != nil || !polish.Success || received["itemId"] != "item-1" {
t.Fatalf("polish=%+v received=%+v err=%v", polish, received, err)
}
}
// TestAccountTaskRequestUsesSignedForm 负责Test账号任务请求UsesSigned表单相关处理。
func TestAccountTaskRequestUsesSignedForm(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.Header.Get("Cookie") == "" || r.URL.Query().Get("sign") == "" {
t.Fatalf("request method=%s cookie=%q query=%v", r.Method, r.Header.Get("Cookie"), r.URL.Query())
}
// body 保存请求体,供当前处理流程使用
body, _ := url.ParseQuery(func() string { _ = r.ParseForm(); return r.Form.Encode() }())
if body.Get("data") == "" {
t.Fatal("missing data form")
@@ -61,16 +74,22 @@ func TestAccountTaskRequestUsesSignedForm(t *testing.T) {
_, _ = w.Write([]byte(`{"ret":["FAIL_BIZ_IDLEITEM_POLISH_AGAIN::宝贝已经擦亮过了"],"data":{}}`))
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), PolishItemURL: server.URL}
// result、err 保存result、err,供当前处理流程使用
result, err := client.PolishItem(context.Background(), "unb=123; _m_h5_tk=token_1", "item-1")
if err != nil || !result.Success {
t.Fatalf("duplicate polish should be success: result=%+v err=%v", result, err)
}
}
// TestPolishItemFallsBackToAlternateAPI 负责TestPolish商品FallsBackToAlternateAPI相关处理。
func TestPolishItemFallsBackToAlternateAPI(t *testing.T) {
// calls 保存calls,供当前处理流程使用
var calls []string
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// api 保存api,供当前处理流程使用
api := r.URL.Query().Get("api")
calls = append(calls, api)
w.Header().Set("Content-Type", "application/json")
@@ -81,37 +100,48 @@ func TestPolishItemFallsBackToAlternateAPI(t *testing.T) {
if api != "mtop.idle.item.polish" || r.URL.Query().Get("v") != "1.0" {
t.Fatalf("unexpected backup request: api=%s version=%s", api, r.URL.Query().Get("v"))
}
if err := r.ParseForm(); err != nil {
if // err 保存err,供当前处理流程使用
err := r.ParseForm(); err != nil {
t.Fatal(err)
}
// data 保存数据,供当前处理流程使用
var data map[string]any
if err := json.Unmarshal([]byte(r.Form.Get("data")), &data); err != nil || data["itemId"] != "item-1" {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(r.Form.Get("data")), &data); err != nil || data["itemId"] != "item-1" {
t.Fatalf("backup data=%v err=%v", data, err)
}
_, _ = w.Write([]byte(`{"ret":["SUCCESS::调用成功"],"data":{}}`))
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), PolishItemURL: server.URL, PolishItemBackupURL: server.URL}
// result、err 保存result、err,供当前处理流程使用
result, err := client.PolishItem(context.Background(), "unb=123; _m_h5_tk=token_1", "item-1")
if err != nil || result == nil || !result.Success {
t.Fatalf("result=%+v err=%v", result, err)
}
// want 保存want,供当前处理流程使用
want := []string{"mtop.taobao.idle.item.polish", "mtop.idle.item.polish"}
if len(calls) != len(want) || calls[0] != want[0] || calls[1] != want[1] {
t.Fatalf("calls=%v want=%v", calls, want)
}
}
// TestPolishItemSessionExpiredDoesNotCallBackupOrTokenAPI 负责TestPolish商品会话ExpiredDoesNotCallBackupOr令牌API相关处理。
func TestPolishItemSessionExpiredDoesNotCallBackupOrTokenAPI(t *testing.T) {
// calls 保存calls,供当前处理流程使用
calls := 0
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls++
_, _ = w.Write([]byte(`{"ret":["FAIL_SYS_SESSION_EXPIRED::Session过期"],"data":{}}`))
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{
HTTPClient: server.Client(), PolishItemURL: server.URL, PolishItemBackupURL: server.URL, TokenURL: server.URL,
}
// err 保存err,供当前处理流程使用
_, err := client.PolishItem(context.Background(), "unb=123; _m_h5_tk=token_1", "item-1")
if err == nil || !IsSessionExpiredErr(err) {
t.Fatalf("err=%v want session expired", err)
+9
View File
@@ -6,14 +6,17 @@ import (
"strings"
)
// ChatUserQueryAPI 保存聊天用户查询API,供当前处理流程使用
const ChatUserQueryAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idlemessage.pc.user.query/4.0/"
// ChatUserInfo 保存聊天用户Info,供当前处理流程使用
type ChatUserInfo struct {
Nickname string
AvatarURL string
UpdatedCookies string
}
// ChatImageUpload 保存聊天图片Upload,供当前处理流程使用
type ChatImageUpload struct {
URL string
Width int
@@ -23,7 +26,9 @@ type ChatImageUpload struct {
// FetchChatUserInfo resolves the peer identity for a conversation. Xianyu's
// API expects the conversation id as sessionId rather than the user id.
// FetchChatUserInfo 负责Fetch聊天用户Info相关处理。
func (c *ClientImpl) FetchChatUserInfo(ctx context.Context, cookiesStr, chatID string) (*ChatUserInfo, error) {
// decoded、updated、err 保存decoded、updated、err,供当前处理流程使用
decoded, updated, err := c.accountTaskRequest(ctx, cookiesStr,
firstNonEmptyURL(c.ChatUserQueryURL, ChatUserQueryAPI), "mtop.taobao.idlemessage.pc.user.query", "4.0",
map[string]any{"type": 0, "sessionType": 1, "sessionId": strings.TrimSpace(chatID), "isOwner": false},
@@ -31,10 +36,12 @@ func (c *ClientImpl) FetchChatUserInfo(ctx context.Context, cookiesStr, chatID s
if err != nil {
return nil, err
}
// userInfo 保存用户Info,供当前处理流程使用
userInfo, _ := decoded.Data["userInfo"].(map[string]any)
if userInfo == nil {
return nil, fmt.Errorf("会话用户接口响应缺少 userInfo")
}
// nickname 保存nickname,供当前处理流程使用
nickname := strings.TrimSpace(mtopString(userInfo["fishNick"]))
if nickname == "" {
nickname = strings.TrimSpace(mtopString(userInfo["nick"]))
@@ -43,7 +50,9 @@ func (c *ClientImpl) FetchChatUserInfo(ctx context.Context, cookiesStr, chatID s
AvatarURL: strings.TrimSpace(mtopString(userInfo["logo"])), UpdatedCookies: updated}, nil
}
// UploadChatImage 负责Upload聊天图片相关处理。
func (c *ClientImpl) UploadChatImage(ctx context.Context, cookiesStr, filename, contentType string, data []byte) (*ChatImageUpload, error) {
// uploaded、updated、err 保存uploaded、updated、err,供当前处理流程使用
uploaded, updated, err := c.uploadPublishImage(ctx, cookiesStr, PublishImage{
Filename: filename, ContentType: contentType, Data: data,
})
+13 -2
View File
@@ -8,7 +8,9 @@ import (
"testing"
)
// TestFetchChatUserInfoUsesConversationAndParsesIdentity 负责TestFetch聊天用户InfoUsesConversationAndParsesIdentity相关处理。
func TestFetchChatUserInfoUsesConversationAndParsesIdentity(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("api") != "mtop.taobao.idlemessage.pc.user.query" || r.URL.Query().Get("v") != "4.0" {
t.Fatalf("query=%v", r.URL.Query())
@@ -16,31 +18,40 @@ func TestFetchChatUserInfoUsesConversationAndParsesIdentity(t *testing.T) {
if r.URL.Query().Get("spm_cnt") != "a21ybx.im.0.0" || r.URL.Query().Get("spm_pre") == "" || r.URL.Query().Get("log_id") == "" {
t.Fatalf("missing official IM query context: %v", r.URL.Query())
}
if err := r.ParseForm(); err != nil {
if // err 保存err,供当前处理流程使用
err := r.ParseForm(); err != nil {
t.Fatal(err)
}
// payload 保存请求载荷,供当前处理流程使用
var payload map[string]any
if err := json.Unmarshal([]byte(r.Form.Get("data")), &payload); err != nil || payload["sessionId"] != "chat-1" || payload["isOwner"] != false {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(r.Form.Get("data")), &payload); err != nil || payload["sessionId"] != "chat-1" || payload["isOwner"] != false {
t.Fatalf("payload=%v err=%v", payload, err)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ret":["SUCCESS::调用成功"],"data":{"userInfo":{"fishNick":"闲鱼真实昵称","nick":"x***3","logo":"https://cdn/avatar.jpg"}}}`))
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ChatUserQueryURL: server.URL}
// info、err 保存info、err,供当前处理流程使用
info, err := client.FetchChatUserInfo(context.Background(), "unb=123; _m_h5_tk=token_1", "chat-1")
if err != nil || info.Nickname != "闲鱼真实昵称" || info.AvatarURL != "https://cdn/avatar.jpg" {
t.Fatalf("info=%+v err=%v", info, err)
}
}
// TestFetchChatUserInfoFallsBackToNickWhenFishNickMissing 负责TestFetch聊天用户InfoFallsBackToNickWhenFishNickMissing相关处理。
func TestFetchChatUserInfoFallsBackToNickWhenFishNickMissing(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ret":["SUCCESS::调用成功"],"data":{"userInfo":{"nick":"兼容昵称","logo":"https://cdn/fallback.jpg"}}}`))
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ChatUserQueryURL: server.URL}
// info、err 保存info、err,供当前处理流程使用
info, err := client.FetchChatUserInfo(context.Background(), "unb=123; _m_h5_tk=token_1", "chat-2")
if err != nil || info.Nickname != "兼容昵称" {
t.Fatalf("info=%+v err=%v", info, err)
+57 -2
View File
@@ -42,6 +42,7 @@ const SoldOrdersAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.trade.mer
// ItemDetailAPI 是闲鱼 PC 商品详情端点。
const ItemDetailAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.pc.detail/1.0/"
// MTopRetryGap 保存MTop重试Gap,供当前处理流程使用
const (
MTopRetryGap = time.Second
ItemPageGap = time.Second
@@ -50,6 +51,7 @@ const (
// Client 是 mtop API 的最小契约,供 server/automation/engine 依赖注入与测试 mock。
// 具体实现 *ClientImpl 走 HTTP;测试可注入自定义实现以隔离网络。
// Client 保存Client,供当前处理流程使用
type Client interface {
FetchUserProfile(ctx context.Context, cookiesStr string) (*UserProfileResult, error)
ConsignContext(ctx context.Context, cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error)
@@ -61,6 +63,7 @@ type Client interface {
// ClientImpl 是 Client 接口的 HTTP 实现。零值可用;HTTP 超时默认 30s。
// 仍导出 HTTPClient/TokenURL 等字段以便调用方覆盖(如测试注入 RoundTripper)。
// ClientImpl 保存ClientImpl,供当前处理流程使用
type ClientImpl struct {
HTTPClient *http.Client
// Logger 记录 MTOP 请求的安全摘要(不会输出 Cookie、签名或响应正文)。
@@ -81,16 +84,21 @@ type ClientImpl struct {
// httpClient 返回带统一请求/响应日志的 HTTP 客户端副本。统一放在传输层,
// 确保 token、续期、订单、商品和发布等所有 MTOP 调用都具备一致的可观测性。
// httpClient 负责httpClient相关处理。
func (c *ClientImpl) httpClient() *http.Client {
return c.httpClientWithTimeout(30 * time.Second)
}
// httpClientWithTimeout 负责httpClientWithTimeout相关处理。
func (c *ClientImpl) httpClientWithTimeout(defaultTimeout time.Duration) *http.Client {
// hc 保存hc,供当前处理流程使用
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: defaultTimeout}
}
// clone 保存clone,供当前处理流程使用
clone := *hc
// transport 保存transport,供当前处理流程使用
transport := hc.Transport
if transport == nil {
transport = http.DefaultTransport
@@ -99,19 +107,25 @@ func (c *ClientImpl) httpClientWithTimeout(defaultTimeout time.Duration) *http.C
return &clone
}
// loggingTransport 保存loggingTransport,供当前处理流程使用
type loggingTransport struct {
base http.RoundTripper
logger *slog.Logger
}
// RoundTrip 负责RoundTrip相关处理。
func (t loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// logger 保存logger,供当前处理流程使用
logger := t.logger
if logger == nil {
logger = slog.Default()
}
// started 保存started,供当前处理流程使用
started := time.Now()
logger.Debug("MTOP 请求开始", "method", req.Method, "path", req.URL.Path)
// resp、err 保存resp、err,供当前处理流程使用
resp, err := t.base.RoundTrip(req)
// attrs 保存attrs,供当前处理流程使用
attrs := []any{"method", req.Method, "path", req.URL.Path, "duration", time.Since(started).Round(time.Millisecond)}
if err != nil {
if errors.Is(err, context.Canceled) {
@@ -121,6 +135,7 @@ func (t loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
}
return nil, err
}
// responseAttrs 保存响应Attrs,供当前处理流程使用
responseAttrs := append(attrs, "status", resp.StatusCode, "content_length", resp.ContentLength)
if resp.StatusCode >= http.StatusBadRequest {
logger.Warn("MTOP HTTP 响应异常", responseAttrs...)
@@ -132,6 +147,7 @@ func (t loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// NewClient 构造纯 Go HTTP 的 MTOP 客户端。Chromium 只用于读取本机指纹
// 和处理滑块,不能成为登录、续期、token 或 WebSocket 的传输层。
// NewClient 负责NewClient相关处理。
func NewClient() *ClientImpl {
return &ClientImpl{}
}
@@ -195,7 +211,9 @@ type ItemListItem struct {
IsMultiSpec bool
}
// hasMTopSuccess 负责hasMTopSuccess相关处理。
func hasMTopSuccess(ret []string) bool {
// r 表示当前遍历过程中的r
for _, r := range ret {
if strings.Contains(r, "SUCCESS::调用成功") {
return true
@@ -204,7 +222,9 @@ func hasMTopSuccess(ret []string) bool {
return false
}
// isTokenExpiredRet 负责is令牌ExpiredRet相关处理。
func isTokenExpiredRet(ret []string) bool {
// r 表示当前遍历过程中的r
for _, r := range ret {
if strings.Contains(r, "FAIL_SYS_TOKEN_EXOIRED") ||
strings.Contains(r, "FAIL_SYS_TOKEN_EXPIRED") ||
@@ -218,11 +238,13 @@ func isTokenExpiredRet(ret []string) bool {
// SessionExpiredError 表示平台已经明确判定整个登录 Session 失效。
// 它与可通过响应 Set-Cookie 重签的普通 MTOP token 过期不同:调用方必须
// 立刻停止业务 API 重试,转入账号级 Session 续期流程。
// SessionExpiredError 保存会话Expired错误,供当前处理流程使用
type SessionExpiredError struct {
API string
Ret []string
}
// Error 负责错误相关处理。
func (e *SessionExpiredError) Error() string {
if e == nil {
return ""
@@ -233,8 +255,11 @@ func (e *SessionExpiredError) Error() string {
return fmt.Sprintf("%s Session 过期: ret=%v", e.API, e.Ret)
}
// isSessionExpiredRet 负责is会话ExpiredRet相关处理。
func isSessionExpiredRet(ret []string) bool {
// value 表示当前遍历过程中的值
for _, value := range ret {
// lower 保存lower,供当前处理流程使用
lower := strings.ToLower(value)
if strings.Contains(lower, "fail_sys_session_expired") ||
strings.Contains(lower, "session过期") ||
@@ -246,17 +271,20 @@ func isSessionExpiredRet(ret []string) bool {
return false
}
// sessionExpiredError 负责会话Expired错误相关处理。
func sessionExpiredError(api string, ret []string) error {
return &SessionExpiredError{API: api, Ret: append([]string(nil), ret...)}
}
// RiskVerificationError 表示闲鱼服务端要求用户验证(滑块/人脸/风控页)。
// 这类错误不能按普通 token 过期快速重试,否则会持续打接口并放大风控。
// RiskVerificationError 保存RiskVerification错误,供当前处理流程使用
type RiskVerificationError struct {
Ret []string
VerificationURL string
}
// Error 负责错误相关处理。
func (e *RiskVerificationError) Error() string {
if e == nil {
return ""
@@ -269,6 +297,7 @@ func (e *RiskVerificationError) Error() string {
// IsRiskVerificationErr 判断错误是否是闲鱼风控验证要求。
func IsRiskVerificationErr(err error) bool {
// riskErr 保存riskErr,供当前处理流程使用
var riskErr *RiskVerificationError
if errors.As(err, &riskErr) {
return true
@@ -276,6 +305,7 @@ func IsRiskVerificationErr(err error) bool {
if err == nil {
return false
}
// msg 保存msg,供当前处理流程使用
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "fail_sys_user_validate") ||
strings.Contains(msg, "rgv587") ||
@@ -284,8 +314,11 @@ func IsRiskVerificationErr(err error) bool {
strings.Contains(msg, "x5secdata")
}
// isRiskVerificationRet 负责isRiskVerificationRet相关处理。
func isRiskVerificationRet(ret []string) bool {
// r 表示当前遍历过程中的r
for _, r := range ret {
// lower 保存lower,供当前处理流程使用
lower := strings.ToLower(r)
if strings.Contains(lower, "fail_sys_user_validate") ||
strings.Contains(lower, "rgv587") ||
@@ -303,10 +336,12 @@ func IsSessionExpiredErr(err error) bool {
if err == nil {
return false
}
// sessionErr 保存会话Err,供当前处理流程使用
var sessionErr *SessionExpiredError
if errors.As(err, &sessionErr) {
return true
}
// msg 保存msg,供当前处理流程使用
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "fail_sys_session_expired") ||
strings.Contains(msg, "session过期") ||
@@ -315,8 +350,10 @@ func IsSessionExpiredErr(err error) bool {
strings.Contains(msg, "登录凭证已失效")
}
// mtopString 负责mtopString相关处理。
func mtopString(v any) string {
switch x := v.(type) {
switch // x 保存x,供当前处理流程使用
x := v.(type) {
case string:
return x
case float64:
@@ -330,16 +367,20 @@ func mtopString(v any) string {
}
}
// mtopInt 负责mtopInt相关处理。
func mtopInt(v any) int {
switch x := v.(type) {
switch // x 保存x,供当前处理流程使用
x := v.(type) {
case float64:
return int(x)
case int:
return x
case string:
// n 保存n,供当前处理流程使用
n, _ := strconv.Atoi(x)
return n
case json.Number:
// n 保存n,供当前处理流程使用
n, _ := strconv.Atoi(x.String())
return n
default:
@@ -347,7 +388,9 @@ func mtopInt(v any) int {
}
}
// setCommonHeaders 负责setCommonHeaders相关处理。
func setCommonHeaders(req *http.Request, cookiesStr string) {
// h 保存h,供当前处理流程使用
h := req.Header
h.Set("accept", "application/json")
h.Set("accept-language", "zh-CN,zh;q=0.9,en;q=0.8")
@@ -364,7 +407,9 @@ func setCommonHeaders(req *http.Request, cookiesStr string) {
h.Set("cookie", cookiesStr)
}
// readMTopBody 负责readMTop请求体相关处理。
func readMTopBody(resp *http.Response) ([]byte, error) {
// raw、err 保存raw、err,供当前处理流程使用
raw, err := io.ReadAll(io.LimitReader(resp.Body, maxMTopResponseBytes+1))
if err != nil {
return nil, err
@@ -377,12 +422,16 @@ func readMTopBody(resp *http.Response) ([]byte, error) {
// mergeSetCookie 把响应的 Set-Cookie 合并回 cookie 字符串。
func mergeSetCookie(orig string, current map[string]string, resp *http.Response) string {
// setCookies 保存setCookies,供当前处理流程使用
setCookies := resp.Header["Set-Cookie"]
if len(setCookies) == 0 {
return orig
}
// changed 保存changed,供当前处理流程使用
changed := false
// sc 表示当前遍历过程中的sc
for _, sc := range setCookies {
// parsed、err 保存parsed、err,供当前处理流程使用
parsed, err := http.ParseSetCookie(sc)
if err != nil || strings.TrimSpace(parsed.Name) == "" {
continue
@@ -397,8 +446,11 @@ func mergeSetCookie(orig string, current map[string]string, resp *http.Response)
if !changed {
return orig
}
// b 保存b,供当前处理流程使用
var b strings.Builder
// first 保存first,供当前处理流程使用
first := true
// k、v 表示当前遍历过程中的k、v
for k, v := range current {
if !first {
b.WriteString("; ")
@@ -411,6 +463,7 @@ func mergeSetCookie(orig string, current map[string]string, resp *http.Response)
return b.String()
}
// truncate 负责truncate相关处理。
func truncate(s string, n int) string {
if len(s) <= n {
return s
@@ -418,10 +471,12 @@ func truncate(s string, n int) string {
return s[:n] + "..."
}
// sleepCtx 负责sleepCtx相关处理。
func sleepCtx(ctx context.Context, d time.Duration) error {
if d <= 0 {
return nil
}
// t 保存t,供当前处理流程使用
t := time.NewTimer(d)
defer t.Stop()
select {
+96 -12
View File
@@ -13,15 +13,21 @@ import (
"time"
)
// TestNewClientUsesGoHTTPByDefault 负责TestNewClientUsesGoHTTPByDefault相关处理。
func TestNewClientUsesGoHTTPByDefault(t *testing.T) {
if client := NewClient(); client == nil {
if // client 保存client,供当前处理流程使用
client := NewClient(); client == nil {
t.Fatal("默认 MTOP 客户端为空")
}
}
// TestRefreshTokenRetriesOnceWithUpdatedCookie 负责TestRefresh令牌RetriesOnceWithUpdated登录凭证相关处理。
func TestRefreshTokenRetriesOnceWithUpdatedCookie(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// attempt 保存尝试次数,供当前处理流程使用
attempt := requests.Add(1)
if attempt == 1 {
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "newtoken_999", Path: "/"})
@@ -35,9 +41,12 @@ func TestRefreshTokenRetriesOnceWithUpdatedCookie(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// result、err 保存result、err,供当前处理流程使用
result, err := client.RefreshTokenContext(ctx, "unb=123; _m_h5_tk=oldtoken_1;")
if err != nil {
t.Fatalf("RefreshTokenContext: %v", err)
@@ -50,23 +59,31 @@ func TestRefreshTokenRetriesOnceWithUpdatedCookie(t *testing.T) {
}
}
// TestReadMTopBodyRejectsOversizedResponse 负责TestReadMTop请求体RejectsOversized响应相关处理。
func TestReadMTopBodyRejectsOversizedResponse(t *testing.T) {
// resp 保存resp,供当前处理流程使用
resp := &http.Response{Body: io.NopCloser(strings.NewReader(strings.Repeat("x", maxMTopResponseBytes+1)))}
defer resp.Body.Close()
if _, err := readMTopBody(resp); err == nil {
if // err 保存err,供当前处理流程使用
_, err := readMTopBody(resp); err == nil {
t.Fatal("oversized mtop response should fail")
}
}
// TestRefreshTokenUsesOfficialAttemptLimitWithoutUpdatedCookie 负责TestRefresh令牌UsesOfficial尝试次数上限WithoutUpdated登录凭证相关处理。
func TestRefreshTokenUsesOfficialAttemptLimitWithoutUpdatedCookie(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"],"data":{}}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.RefreshTokenContext(context.Background(), "unb=123; _m_h5_tk=oldtoken_1;")
if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
t.Fatalf("err=%v", err)
@@ -76,9 +93,13 @@ func TestRefreshTokenUsesOfficialAttemptLimitWithoutUpdatedCookie(t *testing.T)
}
}
// TestConsignRetriesWithUpdatedTokenCookie 负责TestConsignRetriesWithUpdated令牌登录凭证相关处理。
func TestConsignRetriesWithUpdatedTokenCookie(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// attempt 保存尝试次数,供当前处理流程使用
attempt := requests.Add(1)
if attempt == 1 {
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "newtoken_999", Path: "/"})
@@ -92,9 +113,12 @@ func TestConsignRetriesWithUpdatedTokenCookie(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/"}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// ok、ret、updated、err 保存ok、ret、updated、err,供当前处理流程使用
ok, ret, updated, err := client.ConsignContext(ctx, "unb=123; _m_h5_tk=oldtoken_1;", "order-1")
if err != nil {
t.Fatalf("ConsignContext: %v", err)
@@ -110,15 +134,20 @@ func TestConsignRetriesWithUpdatedTokenCookie(t *testing.T) {
}
}
// TestConsignDoesNotRetryNonTokenFailure 负责TestConsignDoesNot重试Non令牌Failure相关处理。
func TestConsignDoesNotRetryNonTokenFailure(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
fmt.Fprint(w, `{"ret":["FAIL_BIZ_ORDER_STATUS_ERROR::订单状态错误"]}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/"}
// ok、ret、err 保存ok、ret、err,供当前处理流程使用
ok, ret, _, err := client.ConsignContext(context.Background(), "unb=123; _m_h5_tk=token_1;", "order-1")
if err != nil || ok || len(ret) == 0 {
t.Fatalf("ok=%v ret=%v err=%v", ok, ret, err)
@@ -128,13 +157,17 @@ func TestConsignDoesNotRetryNonTokenFailure(t *testing.T) {
}
}
// TestFetchOrderDetailParsesPaidAmountAndQuantity 负责TestFetch订单DetailParsesPaidAmountAndQuantity相关处理。
func TestFetchOrderDetailParsesPaidAmountAndQuantity(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"3"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2"},"priceInfo":{"amount":{"value":"12.50"}}}}]}}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/"}
// result、err 保存result、err,供当前处理流程使用
result, err := client.FetchOrderDetail(context.Background(), "unb=123; _m_h5_tk=token_1;", "order-1")
if err != nil {
t.Fatalf("FetchOrderDetail: %v", err)
@@ -144,7 +177,9 @@ func TestFetchOrderDetailParsesPaidAmountAndQuantity(t *testing.T) {
}
}
// TestHasMTopSuccess 负责TestHasMTopSuccess相关处理。
func TestHasMTopSuccess(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
ret []string
want bool
@@ -156,14 +191,18 @@ func TestHasMTopSuccess(t *testing.T) {
{[]string{}, false},
{[]string{"SUCCESS_OTHER::其他成功"}, false},
}
// i、c 表示当前遍历过程中的i、c
for i, c := range cases {
if got := hasMTopSuccess(c.ret); got != c.want {
if // got 保存got,供当前处理流程使用
got := hasMTopSuccess(c.ret); got != c.want {
t.Errorf("case %d: got %v want %v", i, got, c.want)
}
}
}
// TestIsTokenExpiredRet 负责TestIs令牌ExpiredRet相关处理。
func TestIsTokenExpiredRet(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
ret []string
want bool
@@ -177,14 +216,18 @@ func TestIsTokenExpiredRet(t *testing.T) {
{nil, false},
{[]string{}, false},
}
// i、c 表示当前遍历过程中的i、c
for i, c := range cases {
if got := isTokenExpiredRet(c.ret); got != c.want {
if // got 保存got,供当前处理流程使用
got := isTokenExpiredRet(c.ret); got != c.want {
t.Errorf("case %d: got %v want %v (ret=%v)", i, got, c.want, c.ret)
}
}
}
// TestSessionExpiredRetIsSeparateFromTokenExpiry 负责Test会话ExpiredRetIsSeparateFrom令牌Expiry相关处理。
func TestSessionExpiredRetIsSeparateFromTokenExpiry(t *testing.T) {
// ret 保存ret,供当前处理流程使用
ret := []string{"FAIL_SYS_SESSION_EXPIRED::会话过期"}
if !isSessionExpiredRet(ret) {
t.Fatal("session expiry must be recognized")
@@ -192,13 +235,16 @@ func TestSessionExpiredRetIsSeparateFromTokenExpiry(t *testing.T) {
if isTokenExpiredRet(ret) {
t.Fatal("session expiry must not enter token retry path")
}
// err 保存err,供当前处理流程使用
err := sessionExpiredError("test API", ret)
if !IsSessionExpiredErr(fmt.Errorf("wrapped: %w", err)) {
t.Fatalf("typed wrapped error not recognized: %v", err)
}
}
// TestIsSessionExpiredErr 负责TestIs会话ExpiredErr相关处理。
func TestIsSessionExpiredErr(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
err error
want bool
@@ -210,14 +256,18 @@ func TestIsSessionExpiredErr(t *testing.T) {
{nil, false},
{fmt.Errorf("consign 请求失败: connection refused"), false},
}
// i、c 表示当前遍历过程中的i、c
for i, c := range cases {
if got := IsSessionExpiredErr(c.err); got != c.want {
if // got 保存got,供当前处理流程使用
got := IsSessionExpiredErr(c.err); got != c.want {
t.Errorf("case %d: got %v want %v (err=%v)", i, got, c.want, c.err)
}
}
}
// TestMtopString 负责TestMtopString相关处理。
func TestMtopString(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
in any
want string
@@ -231,14 +281,18 @@ func TestMtopString(t *testing.T) {
{true, ""},
{[]string{"a"}, ""},
}
// i、c 表示当前遍历过程中的i、c
for i, c := range cases {
if got := mtopString(c.in); got != c.want {
if // got 保存got,供当前处理流程使用
got := mtopString(c.in); got != c.want {
t.Errorf("case %d: got %q want %q", i, got, c.want)
}
}
}
// TestMtopInt 负责TestMtopInt相关处理。
func TestMtopInt(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
in any
want int
@@ -252,14 +306,18 @@ func TestMtopInt(t *testing.T) {
{nil, 0},
{true, 0},
}
// i、c 表示当前遍历过程中的i、c
for i, c := range cases {
if got := mtopInt(c.in); got != c.want {
if // got 保存got,供当前处理流程使用
got := mtopInt(c.in); got != c.want {
t.Errorf("case %d: got %d want %d", i, got, c.want)
}
}
}
// TestTruncate 负责TestTruncate相关处理。
func TestTruncate(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
s string
n int
@@ -271,26 +329,33 @@ func TestTruncate(t *testing.T) {
{"", 5, ""},
{"abc", 0, "..."},
}
// i、c 表示当前遍历过程中的i、c
for i, c := range cases {
if got := truncate(c.s, c.n); got != c.want {
if // got 保存got,供当前处理流程使用
got := truncate(c.s, c.n); got != c.want {
t.Errorf("case %d: got %q want %q", i, got, c.want)
}
}
}
// TestMergeSetCookieMultiple 负责TestMergeSet登录凭证Multiple相关处理。
func TestMergeSetCookieMultiple(t *testing.T) {
// orig 保存orig,供当前处理流程使用
orig := "unb=123; _m_h5_tk=oldtoken_1; foo=bar"
// current 保存current,供当前处理流程使用
current := map[string]string{
"unb": "123",
"_m_h5_tk": "oldtoken_1",
"foo": "bar",
}
// resp 保存resp,供当前处理流程使用
resp := &http.Response{Header: http.Header{}}
resp.Header["Set-Cookie"] = []string{
"_m_h5_tk=newtoken_999; Path=/; Domain=.goofish.com",
"newkey=newval; Path=/",
"empty=; Path=/",
}
// got 保存got,供当前处理流程使用
got := mergeSetCookie(orig, current, resp)
// 必须含更新后的两个已知字段与新增字段
if !strings.Contains(got, "_m_h5_tk=newtoken_999") {
@@ -307,18 +372,27 @@ func TestMergeSetCookieMultiple(t *testing.T) {
}
}
// TestMergeSetCookieNoSetCookie 负责TestMergeSet登录凭证NoSet登录凭证相关处理。
func TestMergeSetCookieNoSetCookie(t *testing.T) {
// orig 保存orig,供当前处理流程使用
orig := "unb=123; _m_h5_tk=token_1"
// current 保存current,供当前处理流程使用
current := map[string]string{"unb": "123", "_m_h5_tk": "token_1"}
// resp 保存resp,供当前处理流程使用
resp := &http.Response{Header: http.Header{}}
if got := mergeSetCookie(orig, current, resp); got != orig {
if // got 保存got,供当前处理流程使用
got := mergeSetCookie(orig, current, resp); got != orig {
t.Errorf("no Set-Cookie should return orig, got %q", got)
}
}
// TestMergeSetCookieMalformedIgnored 负责TestMergeSet登录凭证MalformedIgnored相关处理。
func TestMergeSetCookieMalformedIgnored(t *testing.T) {
// orig 保存orig,供当前处理流程使用
orig := "unb=123"
// current 保存current,供当前处理流程使用
current := map[string]string{"unb": "123"}
// resp 保存resp,供当前处理流程使用
resp := &http.Response{Header: http.Header{}}
resp.Header["Set-Cookie"] = []string{
"; Path=/", // 无 name=value
@@ -330,23 +404,30 @@ func TestMergeSetCookieMalformedIgnored(t *testing.T) {
}
}
// TestMergeSetCookieMaxAgeOverridesPastExpires 负责TestMergeSet登录凭证MaxAgeOverridesPastExpires相关处理。
func TestMergeSetCookieMaxAgeOverridesPastExpires(t *testing.T) {
// orig 保存orig,供当前处理流程使用
orig := "session=old"
// current 保存current,供当前处理流程使用
current := map[string]string{"session": "old"}
// resp 保存resp,供当前处理流程使用
resp := &http.Response{Header: http.Header{
"Set-Cookie": {"session=fresh; Max-Age=3600; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/"},
}}
if got := mergeSetCookie(orig, current, resp); !strings.Contains(got, "session=fresh") {
if // got 保存got,供当前处理流程使用
got := mergeSetCookie(orig, current, resp); !strings.Contains(got, "session=fresh") {
t.Fatalf("positive Max-Age must override past Expires: %q", got)
}
}
// TestSleepCtx 负责TestSleepCtx相关处理。
func TestSleepCtx(t *testing.T) {
// d <= 0 直接返回
if err := sleepCtx(context.Background(), 0); err != nil {
t.Errorf("sleepCtx(0)=%v", err)
}
if err := sleepCtx(context.Background(), -1); err != nil {
if // err 保存err,供当前处理流程使用
err := sleepCtx(context.Background(), -1); err != nil {
t.Errorf("sleepCtx(-1)=%v", err)
}
// 正常 sleep
@@ -356,12 +437,15 @@ func TestSleepCtx(t *testing.T) {
// ctx 已取消立即返回 ctx.Err()
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := sleepCtx(ctx, time.Second); err != context.Canceled {
if // err 保存err,供当前处理流程使用
err := sleepCtx(ctx, time.Second); err != context.Canceled {
t.Errorf("sleepCtx(canceled)=%v want %v", err, context.Canceled)
}
}
// TestNewClient 负责TestNewClient相关处理。
func TestNewClient(t *testing.T) {
// c 保存c,供当前处理流程使用
c := NewClient()
if c == nil {
t.Fatal("NewClient returned nil")
+34 -4
View File
@@ -18,19 +18,26 @@ import (
// data_val 形如 {"orderId":"...","tradeText":"","picList":[],"newUnconsign":true}。
// 返回成功标志、响应 ret 列表、可能更新后的 cookie。
// 移植自 secure_confirm_decrypted.auto_confirm。
// Consign 负责Consign相关处理。
func (c *ClientImpl) Consign(cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error) {
return c.ConsignContext(context.Background(), cookiesStr, orderID)
}
// ConsignContext 确认发货;签名 token 过期时使用响应下发的新 Cookie 重签并重试。
func (c *ClientImpl) ConsignContext(ctx context.Context, cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error) {
// currentCookies 保存currentCookies,供当前处理流程使用
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
// lastRet 保存lastRet,供当前处理流程使用
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
for // attempt 保存尝试次数,供当前处理流程使用
attempt := 0; attempt < 4; attempt++ {
// previousCookies 保存previousCookies,供当前处理流程使用
previousCookies := currentCookies
// ok、ret、updated、requestErr 保存ok、ret、updated、requestErr,供当前处理流程使用
ok, ret, updated, requestErr := c.consignOnce(ctx, currentCookies, orderID)
if requestErr != nil {
return false, ret, currentCookies, requestErr
@@ -55,6 +62,7 @@ func (c *ClientImpl) ConsignContext(ctx context.Context, cookiesStr, orderID str
// MTop 通常会在 token 过期响应中通过 Set-Cookie 下发新签名 token。
// 若没有下发,则主动调用 token API 尝试刷新一次。
if currentCookies == previousCookies {
// refreshed、refreshErr 保存refreshed、refreshErr,供当前处理流程使用
refreshed, refreshErr := c.RefreshTokenContext(ctx, currentCookies)
if refreshErr != nil {
return false, ret, currentCookies, fmt.Errorf("consign token 过期且刷新失败: %w", refreshErr)
@@ -63,27 +71,39 @@ func (c *ClientImpl) ConsignContext(ctx context.Context, cookiesStr, orderID str
currentCookies = refreshed.UpdatedCookies
}
}
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
if // err 保存err,供当前处理流程使用
err := sleepCtx(ctx, MTopRetryGap); err != nil {
return false, ret, currentCookies, err
}
}
return false, lastRet, currentCookies, nil
}
// consignOnce 负责consignOnce相关处理。
func (c *ClientImpl) consignOnce(ctx context.Context, cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error) {
// hc 保存hc,供当前处理流程使用
hc := c.httpClient()
// consignURL 保存consignURL,供当前处理流程使用
consignURL := c.ConsignURL
if consignURL == "" {
consignURL = ConsignAPI
}
// signingCookies、requestCookies 保存signingCookies、requestCookies,供当前处理流程使用
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", consignURL)
// token 保存令牌,供当前处理流程使用
token := protocol.SignToken(signingCookies)
// t 保存t,供当前处理流程使用
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
// dataVal 保存数据Val,供当前处理流程使用
dataVal := `{"orderId":"` + orderID + `", "tradeText":"","picList":[],"newUnconsign":true}`
// sign 保存sign,供当前处理流程使用
sign := protocol.GenerateSign(t, token, dataVal)
// query 保存查询,供当前处理流程使用
query := buildConsignQuery(t, sign)
// body 保存请求体,供当前处理流程使用
body := "data=" + url.QueryEscape(dataVal)
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
consignURL+"?"+query,
strings.NewReader(body))
@@ -91,22 +111,28 @@ func (c *ClientImpl) consignOnce(ctx context.Context, cookiesStr, orderID string
return false, nil, cookiesStr, err
}
setCommonHeaders(req, requestCookies)
// resp、err 保存resp、err,供当前处理流程使用
resp, err := hc.Do(req)
if err != nil {
return false, nil, cookiesStr, fmt.Errorf("consign 请求失败: %w", err)
}
defer resp.Body.Close()
// updated 保存updated,供当前处理流程使用
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readMTopBody(resp)
if err != nil {
return false, nil, updated, err
}
// res 保存响应,供当前处理流程使用
var res struct {
Ret []string `json:"ret"`
}
if err := json.Unmarshal(raw, &res); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &res); err != nil {
return false, nil, updated, fmt.Errorf("解析 consign 响应失败: %w (body=%s)", err, truncate(string(raw), 300))
}
// r 表示当前遍历过程中的r
for _, r := range res.Ret {
if strings.Contains(r, "SUCCESS::调用成功") {
return true, res.Ret, updated, nil
@@ -115,7 +141,9 @@ func (c *ClientImpl) consignOnce(ctx context.Context, cookiesStr, orderID string
return false, res.Ret, updated, nil
}
// buildConsignQuery 负责buildConsign查询相关处理。
func buildConsignQuery(t, sign string) string {
// parts 保存parts,供当前处理流程使用
parts := [][2]string{
{"jsv", "2.7.2"},
{"appKey", protocol.SignAppKey},
@@ -129,7 +157,9 @@ func buildConsignQuery(t, sign string) string {
{"api", "mtop.taobao.idle.logistic.consign.dummy"},
{"sessionOption", "AutoLoginOnly"},
}
// b 保存b,供当前处理流程使用
var b strings.Builder
// i、p 表示当前遍历过程中的i、p
for i, p := range parts {
if i > 0 {
b.WriteByte('&')
+44
View File
@@ -12,18 +12,23 @@ import (
"time"
)
// consignCookies 保存consignCookies,供当前处理流程使用
const consignCookies = "unb=123; _m_h5_tk=token_1;"
// TestConsignSuccess: ret SUCCESS 直接成功,无需重试。
func TestConsignSuccess(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"]}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/"}
// ok、ret、updated、err 保存ok、ret、updated、err,供当前处理流程使用
ok, ret, updated, err := client.ConsignContext(context.Background(), consignCookies, "order-1")
if err != nil {
t.Fatalf("err=%v", err)
@@ -41,12 +46,15 @@ func TestConsignSuccess(t *testing.T) {
// TestConsignWrapper: Consign(无 Context)等价于 ConsignContext。
func TestConsignWrapper(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"]}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/"}
// ok、ret、err 保存ok、ret、err,供当前处理流程使用
ok, ret, _, err := client.Consign(consignCookies, "order-1")
if err != nil || !ok || len(ret) == 0 {
t.Fatalf("ok=%v ret=%v err=%v", ok, ret, err)
@@ -55,14 +63,18 @@ func TestConsignWrapper(t *testing.T) {
// TestConsignRetFailure: 非 token 过期的失败 ret,不重试,返回 ok=false。
func TestConsignRetFailure(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
fmt.Fprint(w, `{"ret":["FAIL_BIZ_ORDER_STATUS_ERROR::订单状态错误"]}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/"}
// ok、ret、err 保存ok、ret、err,供当前处理流程使用
ok, ret, _, err := client.ConsignContext(context.Background(), consignCookies, "order-1")
if err != nil || ok || len(ret) == 0 {
t.Fatalf("ok=%v ret=%v err=%v", ok, ret, err)
@@ -74,6 +86,7 @@ func TestConsignRetFailure(t *testing.T) {
// TestConsignMergesSetCookie: 成功响应里的 Set-Cookie 应合并进 updated。
func TestConsignMergesSetCookie(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "fresh_token", Path: "/"})
http.SetCookie(w, &http.Cookie{Name: "extra", Value: "v", Path: "/"})
@@ -81,7 +94,9 @@ func TestConsignMergesSetCookie(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/"}
// updated、err 保存updated、err,供当前处理流程使用
_, _, updated, err := client.ConsignContext(context.Background(), consignCookies, "order-1")
if err != nil {
t.Fatalf("err=%v", err)
@@ -93,10 +108,13 @@ func TestConsignMergesSetCookie(t *testing.T) {
// TestConsignRequestError: 网络错误直接返回 err。
func TestConsignRequestError(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, _, _, err := client.ConsignContext(context.Background(), consignCookies, "order-1")
if err == nil || !strings.Contains(err.Error(), "consign 请求失败") {
t.Fatalf("err=%v", err)
@@ -105,12 +123,15 @@ func TestConsignRequestError(t *testing.T) {
// TestConsignParseFailure: 响应非 JSON 解析失败。
func TestConsignParseFailure(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `not-json{`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, _, _, err := client.ConsignContext(context.Background(), consignCookies, "order-1")
if err == nil || !strings.Contains(err.Error(), "解析 consign 响应失败") {
t.Fatalf("err=%v", err)
@@ -119,8 +140,11 @@ func TestConsignParseFailure(t *testing.T) {
// TestConsignTokenExpiredNoCookieRefreshFails: token 过期且响应无 Set-Cookie 时,
// 会调用 RefreshTokenContext 刷新;刷新失败(凭证失效)应返回 err。
// TestConsignTokenExpiredNoCookieRefreshFails 负责TestConsign令牌ExpiredNo登录凭证RefreshFails相关处理。
func TestConsignTokenExpiredNoCookieRefreshFails(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
// token 过期,但不 Set-Cookie
@@ -128,6 +152,7 @@ func TestConsignTokenExpiredNoCookieRefreshFails(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/", TokenURL: server.URL + "/"}
// 使用 token 过期但无新 Cookie 的场景:RefreshTokenContext 会返回"登录凭证已失效"
_, _, _, err := client.ConsignContext(context.Background(), consignCookies, "order-1")
@@ -143,9 +168,13 @@ func TestConsignTokenExpiredNoCookieRefreshFails(t *testing.T) {
// TestConsignTokenExpiredThenRefreshSucceeds: token 过期无 Set-Cookie,
// 但 RefreshToken 刷新成功(返回新 Cookie),第二次 consign 成功。
// TestConsignTokenExpiredThenRefreshSucceeds 负责TestConsign令牌ExpiredThenRefreshSucceeds相关处理。
func TestConsignTokenExpiredThenRefreshSucceeds(t *testing.T) {
// consignReqs 保存consignReqs,供当前处理流程使用
var consignReqs atomic.Int32
// tokenReqs 保存令牌Reqs,供当前处理流程使用
var tokenReqs atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 通过 URL 路径区分 consign / token 请求
if strings.Contains(r.URL.Path, "token") || r.URL.Query().Get("api") == "mtop.taobao.idlemessage.pc.login.token" {
@@ -156,6 +185,7 @@ func TestConsignTokenExpiredThenRefreshSucceeds(t *testing.T) {
return
}
// consign
// attempt 保存尝试次数,供当前处理流程使用
attempt := consignReqs.Add(1)
if attempt == 1 {
// token 过期,不 Set-Cookie(强制走 RefreshToken)
@@ -166,9 +196,12 @@ func TestConsignTokenExpiredThenRefreshSucceeds(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/c", TokenURL: server.URL + "/t"}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// ok、updated、err 保存ok、updated、err,供当前处理流程使用
ok, _, updated, err := client.ConsignContext(ctx, consignCookies, "order-1")
if err != nil {
t.Fatalf("err=%v", err)
@@ -183,7 +216,9 @@ func TestConsignTokenExpiredThenRefreshSucceeds(t *testing.T) {
// TestConsignContextCanceled: ctx 取消应中止重试。
func TestConsignContextCanceled(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
// 不 Set-Cookie,触发 RefreshToken 重试路径
@@ -191,7 +226,9 @@ func TestConsignContextCanceled(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/", TokenURL: server.URL + "/"}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
cancel() // 已取消
_, _, _, err := client.ConsignContext(ctx, consignCookies, "order-1")
@@ -206,17 +243,23 @@ func TestConsignContextCanceled(t *testing.T) {
// TestConsignRetryExhausted: token 过期但每次下发不同 Set-Cookie,4 次重试耗尽返回 ok=false。
func TestConsignRetryExhausted(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// n 保存n,供当前处理流程使用
n := requests.Add(1)
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: fmt.Sprintf("tok_%d", n), Path: "/"})
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/"}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// ok、ret、err 保存ok、ret、err,供当前处理流程使用
ok, ret, _, err := client.ConsignContext(ctx, consignCookies, "order-1")
if err != nil || ok {
t.Fatalf("ok=%v err=%v want ok=false err=nil", ok, err)
@@ -231,6 +274,7 @@ func TestConsignRetryExhausted(t *testing.T) {
// TestBuildConsignQuery: 验证 query 拼接顺序与字段。
func TestBuildConsignQuery(t *testing.T) {
// q 保存q,供当前处理流程使用
q := buildConsignQuery("123", "SIGN")
if !strings.Contains(q, "t=123") || !strings.Contains(q, "sign=SIGN") ||
!strings.Contains(q, "api=mtop.taobao.idle.logistic.consign.dummy") ||
+44 -1
View File
@@ -12,11 +12,13 @@ import (
"xianyu-go/internal/xianyu/protocol"
)
// mtopDocumentURL 保存mtopDocumentURL,供当前处理流程使用
const (
mtopDocumentURL = "https://www.goofish.com/im"
goofishTopSite = "https://goofish.com"
)
// cookieSessionContextKey 保存登录凭证会话上下文Key,供当前处理流程使用
type cookieSessionContextKey struct{}
// CookieSession carries an authoritative Cookie Jar through one MTOP workflow.
@@ -24,6 +26,7 @@ type cookieSessionContextKey struct{}
// document cookies used for signing and cookies scoped to the request URL.
// The same session absorbs every Set-Cookie before response-body processing,
// so callers can persist rotations and deletions even when parsing later fails.
// CookieSession 保存登录凭证会话,供当前处理流程使用
type CookieSession struct {
mu sync.Mutex
snapshot []cookierefresh.BrowserCookie
@@ -35,11 +38,14 @@ type CookieSession struct {
// WithCookieSnapshot installs an authoritative Cookie Jar on ctx. A nil input
// is normalized to an explicitly empty Jar; callers should invoke this only
// when metadata confirms that a complete snapshot exists.
// WithCookieSnapshot 负责With登录凭证Snapshot相关处理。
func WithCookieSnapshot(ctx context.Context, snapshot []cookierefresh.BrowserCookie) (context.Context, *CookieSession) {
// normalized 保存normalized,供当前处理流程使用
normalized := cookierefresh.NormalizeSnapshot(snapshot)
if normalized == nil {
normalized = []cookierefresh.BrowserCookie{}
}
// session 保存会话,供当前处理流程使用
session := &CookieSession{snapshot: normalized, authoritative: true}
return context.WithValue(ctx, cookieSessionContextKey{}, session), session
}
@@ -48,13 +54,16 @@ func WithCookieSnapshot(ctx context.Context, snapshot []cookierefresh.BrowserCoo
// that it is a complete Cookie Jar. Response Set-Cookie values are still
// observable and persistable, but callers must keep metadata snapshot-free
// until a protocol flow supplies an authoritative Jar.
// WithFlatCookieSession 负责WithFlat登录凭证会话相关处理。
func WithFlatCookieSession(ctx context.Context, cookies string) (context.Context, *CookieSession) {
// session 保存会话,供当前处理流程使用
session := &CookieSession{flat: cookies}
return context.WithValue(ctx, cookieSessionContextKey{}, session), session
}
// State returns the /im canonical Cookie header, a copy of the complete Jar,
// and whether the workflow observed an authoritative update.
// State 负责状态相关处理。
func (s *CookieSession) State() (string, []cookierefresh.BrowserCookie, bool) {
if s == nil {
return "", nil, false
@@ -64,27 +73,34 @@ func (s *CookieSession) State() (string, []cookierefresh.BrowserCookie, bool) {
if !s.authoritative {
return s.flat, nil, s.changed
}
// snapshot 保存snapshot,供当前处理流程使用
snapshot := normalizedCompleteSnapshot(s.snapshot)
// value 保存值,供当前处理流程使用
value, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, mtopDocumentURL, goofishTopSite, time.Now())
return value, snapshot, s.changed
}
// cookieSessionFromContext 负责登录凭证会话From上下文相关处理。
func cookieSessionFromContext(ctx context.Context) *CookieSession {
if ctx == nil {
return nil
}
// session 保存会话,供当前处理流程使用
session, _ := ctx.Value(cookieSessionContextKey{}).(*CookieSession)
return session
}
// CookieSessionFromContext exposes the operation-scoped session to legacy
// helpers that may replace it with a final authoritative Jar.
// CookieSessionFromContext 负责登录凭证会话From上下文相关处理。
func CookieSessionFromContext(ctx context.Context) *CookieSession {
return cookieSessionFromContext(ctx)
}
// Snapshot returns a copy of the current complete Jar.
// Snapshot 负责Snapshot相关处理。
func (s *CookieSession) Snapshot() []cookierefresh.BrowserCookie {
// snapshot、authoritative 保存snapshot、authoritative,供当前处理流程使用
snapshot, authoritative, _ := s.requestState()
if !authoritative {
return nil
@@ -93,6 +109,7 @@ func (s *CookieSession) Snapshot() []cookierefresh.BrowserCookie {
}
// ReplaceSnapshot records a final complete Jar, including an explicitly empty one.
// ReplaceSnapshot 负责ReplaceSnapshot相关处理。
func (s *CookieSession) ReplaceSnapshot(snapshot []cookierefresh.BrowserCookie) {
if snapshot == nil {
snapshot = []cookierefresh.BrowserCookie{}
@@ -100,6 +117,7 @@ func (s *CookieSession) ReplaceSnapshot(snapshot []cookierefresh.BrowserCookie)
s.replace(snapshot)
}
// requestState 负责请求状态相关处理。
func (s *CookieSession) requestState() ([]cookierefresh.BrowserCookie, bool, string) {
if s == nil {
return nil, false, ""
@@ -112,10 +130,12 @@ func (s *CookieSession) requestState() ([]cookierefresh.BrowserCookie, bool, str
return normalizedCompleteSnapshot(s.snapshot), true, ""
}
// replace 负责replace相关处理。
func (s *CookieSession) replace(snapshot []cookierefresh.BrowserCookie) {
if s == nil || snapshot == nil {
return
}
// normalized 保存normalized,供当前处理流程使用
normalized := cookierefresh.NormalizeSnapshot(snapshot)
if normalized == nil {
normalized = []cookierefresh.BrowserCookie{}
@@ -128,6 +148,7 @@ func (s *CookieSession) replace(snapshot []cookierefresh.BrowserCookie) {
s.mu.Unlock()
}
// replaceFlat 负责replaceFlat相关处理。
func (s *CookieSession) replaceFlat(flat string) {
if s == nil {
return
@@ -143,6 +164,7 @@ func (s *CookieSession) replaceFlat(flat string) {
}
}
// absorb 负责absorb相关处理。
func (s *CookieSession) absorb(requestURL string, setCookies []string) string {
if s == nil {
return ""
@@ -150,15 +172,18 @@ func (s *CookieSession) absorb(requestURL string, setCookies []string) string {
s.mu.Lock()
defer s.mu.Unlock()
if len(setCookies) > 0 && s.authoritative {
// updated 保存updated,供当前处理流程使用
updated := normalizedCompleteSnapshot(cookierefresh.ApplySetCookies(s.snapshot, requestURL, setCookies, time.Now(), goofishTopSite))
if !slices.Equal(s.snapshot, updated) {
s.snapshot = updated
s.changed = true
}
// value 保存值,供当前处理流程使用
value, _ := cookierefresh.ScopedCookieHeaderForRequest(s.snapshot, mtopDocumentURL, goofishTopSite, time.Now())
return value
}
if len(setCookies) > 0 {
// updated、changed 保存updated、changed,供当前处理流程使用
updated, changed := applyFlatSetCookies(s.flat, setCookies, time.Now())
if changed {
s.flat = updated
@@ -170,27 +195,36 @@ func (s *CookieSession) absorb(requestURL string, setCookies []string) string {
// mtopRequestCookies returns the document-visible cookies used by lib-mtop for
// token/sign generation and the URL-scoped Cookie header sent on the request.
// mtopRequestCookies 负责mtop请求Cookies相关处理。
func mtopRequestCookies(ctx context.Context, fallback, documentURL, requestURL string) (string, string) {
// session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx)
if session == nil {
return fallback, fallback
}
// snapshot、authoritative、flat 保存snapshot、authoritative、flat,供当前处理流程使用
snapshot, authoritative, flat := session.requestState()
if !authoritative {
return flat, flat
}
// documentCookies 保存documentCookies,供当前处理流程使用
documentCookies := make([]cookierefresh.BrowserCookie, 0, len(snapshot))
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range snapshot {
if !cookie.HTTPOnly {
documentCookies = append(documentCookies, cookie)
}
}
// signing 保存signing,供当前处理流程使用
signing, _ := cookierefresh.ScopedCookieHeaderForRequest(documentCookies, documentURL, goofishTopSite, time.Now())
// requestCookies 保存请求Cookies,供当前处理流程使用
requestCookies, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, goofishTopSite, time.Now())
return signing, requestCookies
}
// normalizedCompleteSnapshot 负责normalizedCompleteSnapshot相关处理。
func normalizedCompleteSnapshot(snapshot []cookierefresh.BrowserCookie) []cookierefresh.BrowserCookie {
// normalized 保存normalized,供当前处理流程使用
normalized := cookierefresh.NormalizeSnapshot(snapshot)
if normalized == nil {
return []cookierefresh.BrowserCookie{}
@@ -198,10 +232,15 @@ func normalizedCompleteSnapshot(snapshot []cookierefresh.BrowserCookie) []cookie
return normalized
}
// applyFlatSetCookies 负责applyFlatSetCookies相关处理。
func applyFlatSetCookies(original string, setCookies []string, now time.Time) (string, bool) {
// values 保存values,供当前处理流程使用
values := protocol.TransCookies(original)
// changed 保存changed,供当前处理流程使用
changed := false
// raw 表示当前遍历过程中的原始
for _, raw := range setCookies {
// parsed、err 保存parsed、err,供当前处理流程使用
parsed, err := http.ParseSetCookie(raw)
if err != nil || strings.TrimSpace(parsed.Name) == "" {
continue
@@ -221,15 +260,19 @@ func applyFlatSetCookies(original string, setCookies []string, now time.Time) (s
// absorbMTopResponseCookies applies response cookies before body reads. Without
// an authoritative session it preserves the historical flat-cookie fallback.
// absorbMTopResponseCookies 负责absorbMTop响应Cookies相关处理。
func absorbMTopResponseCookies(ctx context.Context, fallback string, resp *http.Response) string {
if resp == nil {
return fallback
}
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
// setCookies 保存setCookies,供当前处理流程使用
setCookies := resp.Header.Values("Set-Cookie")
if len(setCookies) == 0 {
return fallback
}
// requestURL 保存请求URL,供当前处理流程使用
requestURL := ""
if resp.Request != nil && resp.Request.URL != nil {
requestURL = resp.Request.URL.String()
+79 -7
View File
@@ -14,13 +14,17 @@ import (
"xianyu-go/internal/xianyu/protocol"
)
// cookieSessionRoundTripFunc 保存登录凭证会话RoundTripFunc,供当前处理流程使用
type cookieSessionRoundTripFunc func(*http.Request) (*http.Response, error)
// RoundTrip 负责RoundTrip相关处理。
func (fn cookieSessionRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return fn(req)
}
// TestMTopRequestCookiesSeparatesDocumentAndRequestScopes 负责TestMTop请求CookiesSeparatesDocumentAnd请求Scopes相关处理。
func TestMTopRequestCookiesSeparatesDocumentAndRequestScopes(t *testing.T) {
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "token_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "doc_only", Value: "doc", Domain: "www.goofish.com", Path: "/im", Secure: true},
@@ -28,23 +32,29 @@ func TestMTopRequestCookiesSeparatesDocumentAndRequestScopes(t *testing.T) {
{Name: "partitioned", Value: "part", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
{Name: "foreign_partition", Value: "no", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: "https://example.com"},
}
// ctx 保存ctx,供当前处理流程使用
ctx, _ := WithCookieSnapshot(context.Background(), snapshot)
// signing、request 保存signing、request,供当前处理流程使用
signing, request := mtopRequestCookies(ctx, "fallback=1", mtopDocumentURL, TokenAPI)
// want 表示当前遍历过程中的want
for _, want := range []string{"_m_h5_tk=token_1", "doc_only=doc", "partitioned=part"} {
if !strings.Contains(signing, want) {
t.Fatalf("document cookies %q missing %q", signing, want)
}
}
// unwanted 表示当前遍历过程中的unwanted
for _, unwanted := range []string{"api_only=", "foreign_partition="} {
if strings.Contains(signing, unwanted) {
t.Fatalf("document cookies %q unexpectedly contain %q", signing, unwanted)
}
}
// want 表示当前遍历过程中的want
for _, want := range []string{"_m_h5_tk=token_1", "api_only=api", "partitioned=part"} {
if !strings.Contains(request, want) {
t.Fatalf("request cookies %q missing %q", request, want)
}
}
// unwanted 表示当前遍历过程中的unwanted
for _, unwanted := range []string{"doc_only=", "foreign_partition="} {
if strings.Contains(request, unwanted) {
t.Fatalf("request cookies %q unexpectedly contain %q", request, unwanted)
@@ -52,16 +62,21 @@ func TestMTopRequestCookiesSeparatesDocumentAndRequestScopes(t *testing.T) {
}
}
// TestCookieSessionAbsorbsScopedSetCookieAndDeletion 负责Test登录凭证会话AbsorbsScopedSet登录凭证AndDeletion相关处理。
func TestCookieSessionAbsorbsScopedSetCookieAndDeletion(t *testing.T) {
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "same", Value: "root", Domain: ".goofish.com", Path: "/"},
{Name: "same", Value: "api-old", Domain: "h5api.m.goofish.com", Path: "/h5"},
}
// session 保存会话,供当前处理流程使用
_, session := WithCookieSnapshot(context.Background(), snapshot)
// requestURL、err 保存请求URL、err,供当前处理流程使用
requestURL, err := url.Parse(TokenAPI)
if err != nil {
t.Fatal(err)
}
// resp 保存resp,供当前处理流程使用
resp := &http.Response{
Request: &http.Request{URL: requestURL},
Header: http.Header{"Set-Cookie": {
@@ -70,11 +85,14 @@ func TestCookieSessionAbsorbsScopedSetCookieAndDeletion(t *testing.T) {
}},
}
session.absorb(requestURL.String(), resp.Header.Values("Set-Cookie"))
// got、changed 保存got、changed,供当前处理流程使用
_, got, changed := session.State()
if !changed {
t.Fatal("Set-Cookie must mark session changed")
}
// values 保存values,供当前处理流程使用
values := make(map[string]string)
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range got {
values[cookie.Name+"|"+cookie.Domain+"|"+cookie.Path+"|"+cookie.PartitionKey] = cookie.Value
}
@@ -90,6 +108,7 @@ func TestCookieSessionAbsorbsScopedSetCookieAndDeletion(t *testing.T) {
session.absorb(requestURL.String(), []string{"same=; Max-Age=-1; Path=/h5"})
_, got, _ = session.State()
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range got {
if cookie.Name == "same" && cookie.Domain == "h5api.m.goofish.com" && cookie.Path == "/h5" {
t.Fatalf("scoped deletion was not applied: %+v", got)
@@ -97,20 +116,27 @@ func TestCookieSessionAbsorbsScopedSetCookieAndDeletion(t *testing.T) {
}
}
// TestCookieSessionAuthoritativeEmptyJar 负责Test登录凭证会话AuthoritativeEmptyJar相关处理。
func TestCookieSessionAuthoritativeEmptyJar(t *testing.T) {
// ctx、session 保存ctx、session,供当前处理流程使用
ctx, session := WithCookieSnapshot(context.Background(), nil)
// signing、request 保存signing、request,供当前处理流程使用
signing, request := mtopRequestCookies(ctx, "fallback=must-not-leak", mtopDocumentURL, TokenAPI)
if signing != "" || request != "" {
t.Fatalf("authoritative empty jar leaked fallback: signing=%q request=%q", signing, request)
}
// canonical、snapshot、changed 保存canonical、snapshot、changed,供当前处理流程使用
canonical, snapshot, changed := session.State()
if canonical != "" || snapshot == nil || len(snapshot) != 0 || changed {
t.Fatalf("empty state canonical=%q snapshot=%#v changed=%v", canonical, snapshot, changed)
}
}
// TestFlatCookieSessionCapturesUpdatesWithoutInventingSnapshot 负责TestFlat登录凭证会话CapturesUpdatesWithoutInventingSnapshot相关处理。
func TestFlatCookieSessionCapturesUpdatesWithoutInventingSnapshot(t *testing.T) {
// ctx、session 保存ctx、session,供当前处理流程使用
ctx, session := WithFlatCookieSession(context.Background(), "sid=old; keep=1")
// signing、request 保存signing、request,供当前处理流程使用
signing, request := mtopRequestCookies(ctx, "fallback=must-not-leak", mtopDocumentURL, TokenAPI)
if signing != "sid=old; keep=1" || request != signing {
t.Fatalf("legacy flat session signing=%q request=%q", signing, request)
@@ -119,25 +145,31 @@ func TestFlatCookieSessionCapturesUpdatesWithoutInventingSnapshot(t *testing.T)
"sid=new; Domain=.goofish.com; Path=/; Secure",
"keep=; Max-Age=0; Domain=.goofish.com; Path=/; Secure",
})
// value、snapshot、changed 保存value、snapshot、changed,供当前处理流程使用
value, snapshot, changed := session.State()
if !changed || snapshot != nil || value != "sid=new" {
t.Fatalf("flat update value=%q snapshot=%#v changed=%v", value, snapshot, changed)
}
}
// TestScopedCookieHeaderForRequestIncludesMatchingPartitionAndUnpartitioned 负责TestScoped登录凭证HeaderFor请求IncludesMatchingPartitionAndUnpartitioned相关处理。
func TestScopedCookieHeaderForRequestIncludesMatchingPartitionAndUnpartitioned(t *testing.T) {
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "plain", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "part", Value: "2", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
{Name: "other", Value: "3", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: "https://example.com"},
}
// header、ok 保存header、ok,供当前处理流程使用
header, ok := cookierefresh.ScopedCookieHeaderForRequest(snapshot, TokenAPI, goofishTopSite, time.Now())
if !ok || !strings.Contains(header, "plain=1") || !strings.Contains(header, "part=2") || strings.Contains(header, "other=3") {
t.Fatalf("partition-scoped header=%q ok=%v", header, ok)
}
}
// TestLoginStatusUsesDocumentSigningAndURLScopedRequestCookies 负责Test登录状态UsesDocumentSigningAndURLScoped请求Cookies相关处理。
func TestLoginStatusUsesDocumentSigningAndURLScopedRequestCookies(t *testing.T) {
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "im-token_1", Domain: "www.goofish.com", Path: "/im", Secure: true},
{Name: "_m_h5_tk", Value: "root-token_1", Domain: ".goofish.com", Path: "/", Secure: true},
@@ -145,25 +177,34 @@ func TestLoginStatusUsesDocumentSigningAndURLScopedRequestCookies(t *testing.T)
{Name: "document_only", Value: "visible", Domain: "www.goofish.com", Path: "/im", Secure: true},
{Name: "api_http_only", Value: "secret", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
}
// ctx、session 保存ctx、session,供当前处理流程使用
ctx, session := WithCookieSnapshot(context.Background(), snapshot)
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
// requestCookies 保存请求Cookies,供当前处理流程使用
requestCookies := req.Header.Get("Cookie")
// want 表示当前遍历过程中的want
for _, want := range []string{"_m_h5_tk=root-token_1", "unb=123", "api_http_only=secret"} {
if !strings.Contains(requestCookies, want) {
t.Errorf("URL scoped Cookie %q missing %q", requestCookies, want)
}
}
// unwanted 表示当前遍历过程中的unwanted
for _, unwanted := range []string{"document_only=", "fallback_only="} {
if strings.Contains(requestCookies, unwanted) {
t.Errorf("URL scoped Cookie %q unexpectedly contains %q", requestCookies, unwanted)
}
}
if got := req.Header.Get("Referer"); got != mtopDocumentURL {
if // got 保存got,供当前处理流程使用
got := req.Header.Get("Referer"); got != mtopDocumentURL {
t.Errorf("Referer=%q want %q", got, mtopDocumentURL)
}
// timestamp 保存timestamp,供当前处理流程使用
timestamp := req.URL.Query().Get("t")
// wantSign 保存wantSign,供当前处理流程使用
wantSign := protocol.GenerateSign(timestamp, "im-token", `{}`)
if got := req.URL.Query().Get("sign"); got != wantSign {
if // got 保存got,供当前处理流程使用
got := req.URL.Query().Get("sign"); got != wantSign {
t.Errorf("sign=%q want %q", got, wantSign)
}
return &http.Response{
@@ -176,33 +217,44 @@ func TestLoginStatusUsesDocumentSigningAndURLScopedRequestCookies(t *testing.T)
}, nil
})}}
// err 保存err,供当前处理流程使用
_, err := client.CheckLoginStatusContext(ctx, "_m_h5_tk=fallback_1; fallback_only=leak")
if err == nil || !strings.Contains(err.Error(), "解析 loginuser.get 响应失败") {
t.Fatalf("err=%v", err)
}
// canonical、gotSnapshot、changed 保存canonical、gotSnapshot、changed,供当前处理流程使用
canonical, gotSnapshot, changed := session.State()
if !changed || !strings.Contains(canonical, "_m_h5_tk=rotated-token_9") {
t.Fatalf("response Cookie was not absorbed before body parse: canonical=%q changed=%v snapshot=%+v", canonical, changed, gotSnapshot)
}
}
// TestOrderDetailUsesOrderDocumentForSigningAndReferer 负责Test订单DetailUses订单DocumentForSigningAndReferer相关处理。
func TestOrderDetailUsesOrderDocumentForSigningAndReferer(t *testing.T) {
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "order-token_1", Domain: "www.goofish.com", Path: "/order-detail", Secure: true},
{Name: "_m_h5_tk", Value: "root-token_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
}
// ctx 保存ctx,供当前处理流程使用
ctx, _ := WithCookieSnapshot(context.Background(), snapshot)
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
if got := req.Header.Get("Referer"); got != "https://www.goofish.com/order-detail?orderId=order-1&role=seller" {
if // got 保存got,供当前处理流程使用
got := req.Header.Get("Referer"); got != "https://www.goofish.com/order-detail?orderId=order-1&role=seller" {
t.Errorf("Referer=%q", got)
}
if got := req.Header.Get("Cookie"); !strings.Contains(got, "_m_h5_tk=root-token_1") || strings.Contains(got, "order-token_1") {
if // got 保存got,供当前处理流程使用
got := req.Header.Get("Cookie"); !strings.Contains(got, "_m_h5_tk=root-token_1") || strings.Contains(got, "order-token_1") {
t.Errorf("request Cookie=%q", got)
}
// timestamp 保存timestamp,供当前处理流程使用
timestamp := req.URL.Query().Get("t")
// wantSign 保存wantSign,供当前处理流程使用
wantSign := protocol.GenerateSign(timestamp, "order-token", `{"tid":"order-1"}`)
if got := req.URL.Query().Get("sign"); got != wantSign {
if // got 保存got,供当前处理流程使用
got := req.URL.Query().Get("sign"); got != wantSign {
t.Errorf("sign=%q want %q", got, wantSign)
}
return &http.Response{
@@ -212,12 +264,15 @@ func TestOrderDetailUsesOrderDocumentForSigningAndReferer(t *testing.T) {
Request: req,
}, nil
})}}
if _, err := client.FetchOrderDetail(ctx, "fallback=must-not-leak", "order-1"); err != nil {
if // err 保存err,供当前处理流程使用
_, err := client.FetchOrderDetail(ctx, "fallback=must-not-leak", "order-1"); err != nil {
t.Fatal(err)
}
}
// TestPublishWorkflowUsesCookieSessionForEveryRequest 负责Test发布WorkflowUses登录凭证会话ForEvery请求相关处理。
func TestPublishWorkflowUsesCookieSessionForEveryRequest(t *testing.T) {
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "token0_1", Domain: ".goofish.com", Path: "/", Secure: true},
@@ -225,45 +280,59 @@ func TestPublishWorkflowUsesCookieSessionForEveryRequest(t *testing.T) {
{Name: "api_http_only", Value: "api", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
{Name: "upload_http_only", Value: "upload", Domain: "stream-upload.goofish.com", Path: "/api", Secure: true, HTTPOnly: true},
}
// ctx、session 保存ctx、session,供当前处理流程使用
ctx, session := WithCookieSnapshot(context.Background(), snapshot)
// requestCount 保存请求数量,供当前处理流程使用
requestCount := 0
// assertCookies 保存assertCookies,供当前处理流程使用
assertCookies := func(req *http.Request, token, scoped string) {
t.Helper()
requestCount++
// cookieHeader 保存登录凭证Header,供当前处理流程使用
cookieHeader := req.Header.Get("Cookie")
// want 表示当前遍历过程中的want
for _, want := range []string{"unb=123", "_m_h5_tk=" + token + "_1", scoped} {
if !strings.Contains(cookieHeader, want) {
t.Errorf("%s Cookie %q missing %q", req.URL.Host, cookieHeader, want)
}
}
// unwanted 表示当前遍历过程中的unwanted
for _, unwanted := range []string{"document_only=", "fallback_only="} {
if strings.Contains(cookieHeader, unwanted) {
t.Errorf("%s Cookie %q unexpectedly contains %q", req.URL.Host, cookieHeader, unwanted)
}
}
}
// assertSign 保存assertSign,供当前处理流程使用
assertSign := func(req *http.Request, token string) {
t.Helper()
// body、err 保存body、err,供当前处理流程使用
body, err := io.ReadAll(req.Body)
if err != nil {
t.Errorf("read request body: %v", err)
return
}
// form、err 保存form、err,供当前处理流程使用
form, err := url.ParseQuery(string(body))
if err != nil {
t.Errorf("parse request body: %v", err)
return
}
// timestamp 保存timestamp,供当前处理流程使用
timestamp := req.URL.Query().Get("t")
// want 保存want,供当前处理流程使用
want := protocol.GenerateSign(timestamp, token, form.Get("data"))
if got := req.URL.Query().Get("sign"); got != want {
if // got 保存got,供当前处理流程使用
got := req.URL.Query().Get("sign"); got != want {
t.Errorf("%s sign=%q want %q", req.URL.Query().Get("api"), got, want)
}
}
// rotate 保存rotate,供当前处理流程使用
rotate := func(w http.ResponseWriter, value string) {
w.Header().Add("Set-Cookie", "_m_h5_tk="+value+"_1; Domain=.goofish.com; Path=/; Secure")
}
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, req *http.Request) {
assertCookies(req, "token0", "upload_http_only=upload")
@@ -286,7 +355,9 @@ func TestPublishWorkflowUsesCookieSessionForEveryRequest(t *testing.T) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"new-item"}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// result、err 保存result、err,供当前处理流程使用
result, err := client.PublishItem(ctx, "_m_h5_tk=fallback_1; fallback_only=leak", PublishItemRequest{
Title: "T",
PriceCents: 100,
@@ -300,6 +371,7 @@ func TestPublishWorkflowUsesCookieSessionForEveryRequest(t *testing.T) {
if requestCount != 3 || result.ItemID != "new-item" || !strings.Contains(result.UpdatedCookies, "_m_h5_tk=token4_1") {
t.Fatalf("requests=%d result=%+v", requestCount, result)
}
// canonical、changed 保存canonical、changed,供当前处理流程使用
canonical, _, changed := session.State()
if !changed || !strings.Contains(canonical, "_m_h5_tk=token4_1") {
t.Fatalf("final session canonical=%q changed=%v", canonical, changed)
+31 -5
View File
@@ -23,24 +23,33 @@ var _ ItemDetailFetcher = (*ClientImpl)(nil)
// DetectItemMultiSpec 查询商品详情并识别多规格结构。该调用不主动刷新 token;
// 当 ctx 携带 CookieSession 时会像浏览器一样吸收响应 Cookie。
// DetectItemMultiSpec 负责Detect商品MultiSpec相关处理。
func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID string) (bool, error) {
itemID = strings.TrimSpace(itemID)
if itemID == "" {
return false, fmt.Errorf("item_id 不能为空")
}
// endpoint 保存endpoint,供当前处理流程使用
endpoint := c.ItemDetailURL
if endpoint == "" {
endpoint = ItemDetailAPI
}
// documentURL 保存documentURL,供当前处理流程使用
documentURL := "https://www.goofish.com/item?id=" + url.QueryEscape(itemID)
// signingCookies、requestCookies 保存signingCookies、requestCookies,供当前处理流程使用
signingCookies, requestCookies := mtopRequestCookies(ctx, cookies, documentURL, endpoint)
// token 保存令牌,供当前处理流程使用
token := protocol.SignToken(signingCookies)
if token == "" {
return false, fmt.Errorf("cookie 缺少 _m_h5_tk,无法获取商品详情")
}
// dataVal 保存数据Val,供当前处理流程使用
dataVal := `{"itemId":` + strconv.Quote(itemID) + `}`
// timestamp 保存timestamp,供当前处理流程使用
timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
// sign 保存sign,供当前处理流程使用
sign := protocol.GenerateSign(timestamp, token, dataVal)
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildItemDetailQuery(timestamp, sign), strings.NewReader("data="+url.QueryEscape(dataVal)))
if err != nil {
return false, err
@@ -49,22 +58,27 @@ func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID st
req.Header.Set("Origin", "https://www.goofish.com")
req.Header.Set("Referer", documentURL)
// hc 保存hc,供当前处理流程使用
hc := c.httpClient()
// resp、err 保存resp、err,供当前处理流程使用
resp, err := hc.Do(req)
if err != nil {
return false, fmt.Errorf("商品详情请求失败: %w", err)
}
defer resp.Body.Close()
absorbMTopResponseCookies(ctx, cookies, resp)
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readMTopBody(resp)
if err != nil {
return false, err
}
// decoded 保存decoded,供当前处理流程使用
var decoded struct {
Ret []string `json:"ret"`
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(raw, &decoded); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &decoded); err != nil {
return false, fmt.Errorf("解析商品详情响应失败: %w (body=%s)", err, truncate(string(raw), 300))
}
if isSessionExpiredRet(decoded.Ret) {
@@ -76,7 +90,9 @@ func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID st
return detectItemMultiSpec(decoded.Data), nil
}
// buildItemDetailQuery 负责build商品Detail查询相关处理。
func buildItemDetailQuery(timestamp, sign string) string {
// values 保存values,供当前处理流程使用
values := url.Values{
"jsv": {"2.7.2"},
"appKey": {protocol.SignAppKey},
@@ -94,17 +110,22 @@ func buildItemDetailQuery(timestamp, sign string) string {
return values.Encode()
}
// detectItemMultiSpec 负责detect商品MultiSpec相关处理。
func detectItemMultiSpec(value any) bool {
return detectMultiSpecValue(value, false, 0)
}
// detectMultiSpecValue 负责detectMultiSpec值相关处理。
func detectMultiSpecValue(value any, skuContext bool, depth int) bool {
if depth > 16 {
return false
}
switch typed := value.(type) {
switch // typed 保存typed,供当前处理流程使用
typed := value.(type) {
case map[string]any:
// key、child 表示当前遍历过程中的key、child
for key, child := range typed {
// normalized 保存normalized,供当前处理流程使用
normalized := strings.ToLower(strings.NewReplacer("_", "", "-", "").Replace(key))
switch normalized {
case "multisku", "ismultisku", "ismultispec", "multiplesku":
@@ -112,26 +133,31 @@ func detectMultiSpecValue(value any, skuContext bool, depth int) bool {
return true
}
case "skulist", "skus":
if list, ok := child.([]any); ok && len(list) > 1 {
if // list、ok 保存list、ok,供当前处理流程使用
list, ok := child.([]any); ok && len(list) > 1 {
return true
}
case "skuprops", "skuproperties", "specprops", "specifications":
if list, ok := child.([]any); ok && len(list) > 0 {
if // list、ok 保存list、ok,供当前处理流程使用
list, ok := child.([]any); ok && len(list) > 0 {
return true
}
case "props", "properties":
if skuContext {
if list, ok := child.([]any); ok && len(list) > 0 {
if // list、ok 保存list、ok,供当前处理流程使用
list, ok := child.([]any); ok && len(list) > 0 {
return true
}
}
}
// nextSKUContext 保存nextSKU上下文,供当前处理流程使用
nextSKUContext := skuContext || normalized == "skudo" || normalized == "skubase" || normalized == "skumodel"
if detectMultiSpecValue(child, nextSKUContext, depth+1) {
return true
}
}
case []any:
// child 表示当前遍历过程中的child
for _, child := range typed {
if detectMultiSpecValue(child, skuContext, depth+1) {
return true
+15 -2
View File
@@ -10,12 +10,16 @@ import (
"testing"
)
// TestDetectItemMultiSpec 负责TestDetect商品MultiSpec相关处理。
func TestDetectItemMultiSpec(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("api") != "mtop.taobao.idle.pc.detail" {
t.Errorf("query=%s", r.URL.RawQuery)
}
// rawBody 保存原始请求体,供当前处理流程使用
rawBody, _ := io.ReadAll(r.Body)
// form 保存表单,供当前处理流程使用
form, _ := url.ParseQuery(string(rawBody))
if form.Get("data") != `{"itemId":"item-1"}` {
t.Errorf("data=%q", form.Get("data"))
@@ -23,14 +27,18 @@ func TestDetectItemMultiSpec(t *testing.T) {
_, _ = io.WriteString(w, `{"ret":["SUCCESS::调用成功"],"data":{"skuDO":{"skuProperties":[{"name":"颜色"}],"skuList":[{"id":"1"},{"id":"2"}]}}}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), ItemDetailURL: server.URL}
// got、err 保存got、err,供当前处理流程使用
got, err := client.DetectItemMultiSpec(context.Background(), "_m_h5_tk=token_1", "item-1")
if err != nil || !got {
t.Fatalf("got=%v err=%v", got, err)
}
}
// TestDetectItemMultiSpecSignals 负责TestDetect商品MultiSpecSignals相关处理。
func TestDetectItemMultiSpecSignals(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
data any
@@ -41,18 +49,23 @@ func TestDetectItemMultiSpecSignals(t *testing.T) {
{name: "sku props", data: map[string]any{"skuDO": map[string]any{"props": []any{"颜色"}}}, want: true},
{name: "single", data: map[string]any{"multiSKU": false, "skuList": []any{1}}, want: false},
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := detectItemMultiSpec(tc.data); got != tc.want {
if // got 保存got,供当前处理流程使用
got := detectItemMultiSpec(tc.data); got != tc.want {
t.Fatalf("got=%v want=%v", got, tc.want)
}
})
}
}
// TestDetectItemMultiSpecRejectsMissingToken 负责TestDetect商品MultiSpecRejectsMissing令牌相关处理。
func TestDetectItemMultiSpecRejectsMissingToken(t *testing.T) {
// client 保存client,供当前处理流程使用
client := &ClientImpl{}
if _, err := client.DetectItemMultiSpec(context.Background(), "unb=1", "item-1"); err == nil || !strings.Contains(err.Error(), "_m_h5_tk") {
if // err 保存err,供当前处理流程使用
_, err := client.DetectItemMultiSpec(context.Background(), "unb=1", "item-1"); err == nil || !strings.Contains(err.Error(), "_m_h5_tk") {
t.Fatalf("err=%v", err)
}
}
+69 -9
View File
@@ -22,12 +22,17 @@ func (c *ClientImpl) FetchItemsPage(ctx context.Context, cookiesStr string, page
if pageSize < 1 {
pageSize = 20
}
// currentCookies 保存currentCookies,供当前处理流程使用
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
// lastRet 保存lastRet,供当前处理流程使用
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
for // attempt 保存尝试次数,供当前处理流程使用
attempt := 0; attempt < 4; attempt++ {
// res、ret、updatedCookies、err 保存res、ret、updatedCookies、err,供当前处理流程使用
res, ret, updatedCookies, err := c.fetchItemsPageOnce(ctx, currentCookies, pageNumber, pageSize)
if err != nil {
return nil, err
@@ -44,14 +49,17 @@ func (c *ClientImpl) FetchItemsPage(ctx context.Context, cookiesStr string, page
}
if updatedCookies != "" && updatedCookies != currentCookies {
currentCookies = updatedCookies
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
if // err 保存err,供当前处理流程使用
err := sleepCtx(ctx, MTopRetryGap); err != nil {
return nil, err
}
continue
}
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
if // err 保存err,供当前处理流程使用
err := sleepCtx(ctx, MTopRetryGap); err != nil {
return nil, err
}
// refreshed、err 保存refreshed、err,供当前处理流程使用
refreshed, err := c.RefreshTokenContext(ctx, currentCookies)
if err != nil {
return nil, fmt.Errorf("刷新 mtop token 失败: %w", err)
@@ -61,15 +69,21 @@ func (c *ClientImpl) FetchItemsPage(ctx context.Context, cookiesStr string, page
return nil, fmt.Errorf("商品列表接口 token 重试失败: ret=%v", lastRet)
}
// fetchItemsPageOnce 负责fetch商品列表页码Once相关处理。
func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string, pageNumber, pageSize int) (*ItemListResult, []string, string, error) {
// hc 保存hc,供当前处理流程使用
hc := c.httpClient()
// signingCookies、requestCookies 保存signingCookies、requestCookies,供当前处理流程使用
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", ItemListAPI)
// cookies 保存cookies,供当前处理流程使用
cookies := protocol.TransCookies(signingCookies)
// userID 保存用户ID,供当前处理流程使用
userID := cookies["unb"]
if userID == "" {
return nil, nil, cookiesStr, fmt.Errorf("cookie 缺少 unb 字段,无法获取商品列表")
}
// data 保存数据,供当前处理流程使用
data := map[string]any{
"needGroupInfo": false,
"pageNumber": pageNumber,
@@ -79,41 +93,55 @@ func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string,
"defaultGroup": true,
"userId": userID,
}
// rawData 保存原始数据,供当前处理流程使用
rawData, _ := json.Marshal(data)
// dataVal 保存数据Val,供当前处理流程使用
dataVal := string(rawData)
// t 保存t,供当前处理流程使用
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
// sign 保存sign,供当前处理流程使用
sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
// query 保存查询,供当前处理流程使用
query := buildItemListQuery(t, sign)
// body 保存请求体,供当前处理流程使用
body := "data=" + url.QueryEscape(dataVal)
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost, ItemListAPI+"?"+query, strings.NewReader(body))
if err != nil {
return nil, nil, cookiesStr, err
}
setCommonHeaders(req, requestCookies)
// resp、err 保存resp、err,供当前处理流程使用
resp, err := hc.Do(req)
if err != nil {
return nil, nil, cookiesStr, fmt.Errorf("商品列表请求失败: %w", err)
}
defer resp.Body.Close()
// updated 保存updated,供当前处理流程使用
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readMTopBody(resp)
if err != nil {
return nil, nil, updated, err
}
// decoded 保存decoded,供当前处理流程使用
var decoded struct {
Ret []string `json:"ret"`
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(raw, &decoded); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &decoded); err != nil {
return nil, nil, updated, fmt.Errorf("解析商品列表响应失败: %w (body=%s)", err, truncate(string(raw), 300))
}
if !hasMTopSuccess(decoded.Ret) {
return nil, decoded.Ret, updated, nil
}
// items 保存商品列表,供当前处理流程使用
items := parseItemList(decoded.Data)
// totalCount、totalPages 保存总数Count、totalPages,供当前处理流程使用
totalCount, totalPages := itemListPagination(decoded.Data, pageNumber, pageSize)
return &ItemListResult{
Items: items,
@@ -132,14 +160,20 @@ func (c *ClientImpl) FetchAllItems(ctx context.Context, cookiesStr string, pageS
if pageSize <= 0 {
pageSize = 20
}
// currentCookies 保存currentCookies,供当前处理流程使用
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
// page 保存页码,供当前处理流程使用
page := 1
// fetchedPages 保存fetchedPages,供当前处理流程使用
fetchedPages := 0
// all 保存all,供当前处理流程使用
var all []ItemListItem
for maxPages <= 0 || page <= maxPages {
// res、err 保存res、err,供当前处理流程使用
res, err := c.FetchItemsPage(ctx, currentCookies, page, pageSize)
if err != nil {
return nil, err
@@ -154,7 +188,8 @@ func (c *ClientImpl) FetchAllItems(ctx context.Context, cookiesStr string, pageS
break
}
page++
if err := sleepCtx(ctx, ItemPageGap); err != nil {
if // err 保存err,供当前处理流程使用
err := sleepCtx(ctx, ItemPageGap); err != nil {
return nil, err
}
}
@@ -170,15 +205,20 @@ func (c *ClientImpl) FetchAllItems(ctx context.Context, cookiesStr string, pageS
}, nil
}
// itemListPagination 负责商品ListPagination相关处理。
func itemListPagination(data map[string]any, pageNumber, pageSize int) (totalCount, totalPages int) {
// key 表示当前遍历过程中的key
for _, key := range []string{"totalCount", "total_count", "total"} {
if value := mtopInt(data[key]); value > 0 {
if // value 保存值,供当前处理流程使用
value := mtopInt(data[key]); value > 0 {
totalCount = value
break
}
}
// key 表示当前遍历过程中的key
for _, key := range []string{"pageCount", "page_count", "totalPages", "total_pages"} {
if value := mtopInt(data[key]); value > 0 {
if // value 保存值,供当前处理流程使用
value := mtopInt(data[key]); value > 0 {
totalPages = value
break
}
@@ -195,7 +235,9 @@ func itemListPagination(data map[string]any, pageNumber, pageSize int) (totalCou
return totalCount, totalPages
}
// buildItemListQuery 负责build商品List查询相关处理。
func buildItemListQuery(t, sign string) string {
// parts 保存parts,供当前处理流程使用
parts := [][2]string{
{"jsv", "2.7.2"},
{"appKey", protocol.SignAppKey},
@@ -211,7 +253,9 @@ func buildItemListQuery(t, sign string) string {
{"spm_cnt", "a21ybx.im.0.0"},
{"spm_pre", "a21ybx.collection.menu.1.272b5141NafCNK"},
}
// b 保存b,供当前处理流程使用
var b strings.Builder
// i、p 表示当前遍历过程中的i、p
for i, p := range parts {
if i > 0 {
b.WriteByte('&')
@@ -223,19 +267,27 @@ func buildItemListQuery(t, sign string) string {
return b.String()
}
// parseItemList 负责parse商品List相关处理。
func parseItemList(data map[string]any) []ItemListItem {
// cardList 保存卡密List,供当前处理流程使用
cardList, _ := data["cardList"].([]any)
// items 保存商品列表,供当前处理流程使用
items := make([]ItemListItem, 0, len(cardList))
// rawCard 表示当前遍历过程中的原始卡密
for _, rawCard := range cardList {
// card、ok 保存card、ok,供当前处理流程使用
card, ok := rawCard.(map[string]any)
if !ok {
continue
}
// cardData 保存卡密数据,供当前处理流程使用
cardData, _ := card["cardData"].(map[string]any)
if cardData == nil {
continue
}
// detailParams 保存detailParams,供当前处理流程使用
detailParams, _ := cardData["detailParams"].(map[string]any)
// itemID 保存商品ID,供当前处理流程使用
itemID := mtopString(detailParams["itemId"])
if itemID == "" {
itemID = mtopString(cardData["id"])
@@ -243,12 +295,19 @@ func parseItemList(data map[string]any) []ItemListItem {
if itemID == "" || strings.HasPrefix(itemID, "auto_") {
continue
}
// priceInfo 保存priceInfo,供当前处理流程使用
priceInfo, _ := cardData["priceInfo"].(map[string]any)
// price 保存price,供当前处理流程使用
price := mtopString(priceInfo["price"])
// priceText 保存price文本,供当前处理流程使用
priceText := mtopString(priceInfo["preText"]) + price
// picInfo 保存picInfo,供当前处理流程使用
picInfo, _ := cardData["picInfo"].(map[string]any)
// picURL 保存picURL,供当前处理流程使用
picURL := mtopString(picInfo["picUrl"])
// detailURL 保存detailURL,供当前处理流程使用
detailURL := mtopString(cardData["detailUrl"])
// detail 保存detail,供当前处理流程使用
detail := map[string]any{
"title": mtopString(cardData["title"]),
"price": price,
@@ -264,6 +323,7 @@ func parseItemList(data map[string]any) []ItemListItem {
"item_label_data": cardData["itemLabelDataVO"],
"card_type": mtopInt(card["cardType"]),
}
// detailJSON 保存detailJSON,供当前处理流程使用
detailJSON, _ := json.Marshal(detail)
items = append(items, ItemListItem{
ID: itemID,
+103 -5
View File
@@ -14,6 +14,7 @@ import (
// items.go 的 fetchItemsPageOnce 硬编码 ItemListAPI 常量,用 rewriteTransport 改写到本地 server。
// itemsPage1JSON 保存商品列表Page1JSON,供当前处理流程使用
const itemsPage1JSON = `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[
{"cardType":1,"cardData":{"id":"item-1","title":"商品A","categoryId":"cat-1","auctionType":"b","itemStatus":0,
"priceInfo":{"price":"12.50","preText":"¥"},
@@ -28,13 +29,17 @@ const itemsPage1JSON = `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[
// TestFetchItemsPageSuccess: 解析多商品,含 pageCount/字段映射。
func TestFetchItemsPageSuccess(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, itemsPage1JSON)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchItemsPage(context.Background(), consignCookies, 1, 20)
if err != nil {
t.Fatalf("err=%v", err)
@@ -42,6 +47,7 @@ func TestFetchItemsPageSuccess(t *testing.T) {
if len(res.Items) != 2 {
t.Fatalf("items=%d want 2", len(res.Items))
}
// it 保存it,供当前处理流程使用
it := res.Items[0]
if it.ID != "item-1" || it.Title != "商品A" || it.Price != "12.50" ||
it.PriceText != "¥12.50" || it.CategoryID != "cat-1" ||
@@ -55,7 +61,8 @@ func TestFetchItemsPageSuccess(t *testing.T) {
}
// ItemDetail 应为合法 JSON
var detail map[string]any
if err := json.Unmarshal([]byte(it.ItemDetail), &detail); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(it.ItemDetail), &detail); err != nil {
t.Fatalf("ItemDetail 非 JSON: %v (%s)", err, it.ItemDetail)
}
if detail["card_type"].(float64) != 1 {
@@ -65,13 +72,17 @@ func TestFetchItemsPageSuccess(t *testing.T) {
// TestFetchItemsPageMissingUnbCookie: cookie 缺 unb 报错。
func TestFetchItemsPageMissingUnbCookie(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("不应发请求")
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// err 保存err,供当前处理流程使用
_, err := client.FetchItemsPage(context.Background(), "_m_h5_tk=t_1;", 1, 20)
if err == nil || !strings.Contains(err.Error(), "cookie 缺少 unb") {
t.Fatalf("err=%v", err)
@@ -80,13 +91,17 @@ func TestFetchItemsPageMissingUnbCookie(t *testing.T) {
// TestFetchItemsPageEmptyCardList: SUCCESS 但 cardList 为空。
func TestFetchItemsPageEmptyCardList(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{}}`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchItemsPage(context.Background(), consignCookies, 1, 20)
if err != nil {
t.Fatalf("err=%v", err)
@@ -98,6 +113,7 @@ func TestFetchItemsPageEmptyCardList(t *testing.T) {
// TestFetchItemsPageAutoPrefixFiltered: auto_ 前缀商品被过滤。
func TestFetchItemsPageAutoPrefixFiltered(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[
{"cardData":{"title":"auto商品","detailParams":{"itemId":"auto_123"}}},
@@ -106,8 +122,11 @@ func TestFetchItemsPageAutoPrefixFiltered(t *testing.T) {
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchItemsPage(context.Background(), consignCookies, 1, 20)
if err != nil {
t.Fatalf("err=%v", err)
@@ -119,13 +138,17 @@ func TestFetchItemsPageAutoPrefixFiltered(t *testing.T) {
// TestFetchItemsPageNonSuccessRet: 非 token 过期失败 ret。
func TestFetchItemsPageNonSuccessRet(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["FAIL_BIZ_LIST_ERROR::列表错误"]}`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// err 保存err,供当前处理流程使用
_, err := client.FetchItemsPage(context.Background(), consignCookies, 1, 20)
if err == nil || !strings.Contains(err.Error(), "商品列表接口返回非成功") {
t.Fatalf("err=%v", err)
@@ -134,13 +157,17 @@ func TestFetchItemsPageNonSuccessRet(t *testing.T) {
// TestFetchItemsPageParseFailure: 响应非 JSON。
func TestFetchItemsPageParseFailure(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `bad{`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// err 保存err,供当前处理流程使用
_, err := client.FetchItemsPage(context.Background(), consignCookies, 1, 20)
if err == nil || !strings.Contains(err.Error(), "解析商品列表响应失败") {
t.Fatalf("err=%v", err)
@@ -149,13 +176,17 @@ func TestFetchItemsPageParseFailure(t *testing.T) {
// TestFetchItemsPageDefaultsInvalidPage: pageNumber<1 / pageSize<1 兜底。
func TestFetchItemsPageDefaultsInvalidPage(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{}}`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchItemsPage(context.Background(), consignCookies, 0, 0)
if err != nil {
t.Fatalf("err=%v", err)
@@ -167,8 +198,11 @@ func TestFetchItemsPageDefaultsInvalidPage(t *testing.T) {
// TestFetchItemsPageTokenExpiredRetriesWithSetCookie: token 过期 + Set-Cookie,二次成功。
func TestFetchItemsPageTokenExpiredRetriesWithSetCookie(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// attempt 保存尝试次数,供当前处理流程使用
attempt := requests.Add(1)
if attempt == 1 {
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "newtoken_3", Path: "/"})
@@ -179,10 +213,14 @@ func TestFetchItemsPageTokenExpiredRetriesWithSetCookie(t *testing.T) {
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// err 保存err,供当前处理流程使用
_, err := client.FetchItemsPage(ctx, consignCookies, 1, 20)
if err != nil {
t.Fatalf("err=%v", err)
@@ -194,8 +232,11 @@ func TestFetchItemsPageTokenExpiredRetriesWithSetCookie(t *testing.T) {
// TestFetchAllItemsMultiPage: 多页翻页(pageCount 驱动 / len < pageSize 终止)。
func TestFetchAllItemsMultiPage(t *testing.T) {
// pageReqs 保存页码Reqs,供当前处理流程使用
var pageReqs atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// page 保存页码,供当前处理流程使用
page := pageReqs.Add(1)
// 第 1 页 2 条(pageSize=2,满页),第 2 页 1 条(不满,终止)
if page == 1 {
@@ -211,10 +252,14 @@ func TestFetchAllItemsMultiPage(t *testing.T) {
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchAllItems(ctx, consignCookies, 2, 10)
if err != nil {
t.Fatalf("err=%v", err)
@@ -227,9 +272,13 @@ func TestFetchAllItemsMultiPage(t *testing.T) {
}
}
// TestFetchAllItemsUsesRemotePageCountWhenPageIsShort 负责TestFetchAll商品列表UsesRemote页码数量When页码IsShort相关处理。
func TestFetchAllItemsUsesRemotePageCountWhenPageIsShort(t *testing.T) {
// pageReqs 保存页码Reqs,供当前处理流程使用
var pageReqs atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// page 保存页码,供当前处理流程使用
page := pageReqs.Add(1)
if page == 1 {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"pageCount":2,"cardList":[
@@ -243,8 +292,11 @@ func TestFetchAllItemsUsesRemotePageCountWhenPageIsShort(t *testing.T) {
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchAllItems(context.Background(), consignCookies, 20, 10)
if err != nil {
t.Fatalf("err=%v", err)
@@ -256,7 +308,9 @@ func TestFetchAllItemsUsesRemotePageCountWhenPageIsShort(t *testing.T) {
// TestFetchAllItemsMaxPagesCap: maxPages 限制最大页数。
func TestFetchAllItemsMaxPagesCap(t *testing.T) {
// pageReqs 保存页码Reqs,供当前处理流程使用
var pageReqs atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pageReqs.Add(1)
// 每页满(pageSize=1),但 maxPages=2 应只取 2 页
@@ -266,10 +320,14 @@ func TestFetchAllItemsMaxPagesCap(t *testing.T) {
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchAllItems(ctx, consignCookies, 1, 2)
if err != nil {
t.Fatalf("err=%v", err)
@@ -284,15 +342,20 @@ func TestFetchAllItemsMaxPagesCap(t *testing.T) {
// TestFetchAllItemsEmptyFirstPage: 首页空立即终止。
func TestFetchAllItemsEmptyFirstPage(t *testing.T) {
// pageReqs 保存页码Reqs,供当前处理流程使用
var pageReqs atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pageReqs.Add(1)
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{}}`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchAllItems(context.Background(), consignCookies, 20, 5)
if err != nil {
t.Fatalf("err=%v", err)
@@ -307,13 +370,17 @@ func TestFetchAllItemsEmptyFirstPage(t *testing.T) {
// TestFetchAllItemsDefaultPageSize: pageSize<=0 默认 20。
func TestFetchAllItemsDefaultPageSize(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{}}`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchAllItems(context.Background(), consignCookies, 0, 5)
if err != nil {
t.Fatalf("err=%v", err)
@@ -325,13 +392,17 @@ func TestFetchAllItemsDefaultPageSize(t *testing.T) {
// TestFetchAllItemsPropagatesError: 子页失败透传。
func TestFetchAllItemsPropagatesError(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["FAIL_BIZ_LIST_ERROR::错误"]}`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// err 保存err,供当前处理流程使用
_, err := client.FetchAllItems(context.Background(), consignCookies, 20, 5)
if err == nil || !strings.Contains(err.Error(), "商品列表接口返回非成功") {
t.Fatalf("err=%v", err)
@@ -340,18 +411,25 @@ func TestFetchAllItemsPropagatesError(t *testing.T) {
// TestFetchItemsPageRetryExhausted: token 过期但每次下发不同 Set-Cookie,4 次重试耗尽。
func TestFetchItemsPageRetryExhausted(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// n 保存n,供当前处理流程使用
n := requests.Add(1)
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: fmt.Sprintf("tok_%d", n), Path: "/"})
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 15 * time.Second}}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// err 保存err,供当前处理流程使用
_, err := client.FetchItemsPage(ctx, consignCookies, 1, 20)
if err == nil || !strings.Contains(err.Error(), "商品列表接口 token 重试失败") {
t.Fatalf("err=%v", err)
@@ -363,13 +441,17 @@ func TestFetchItemsPageRetryExhausted(t *testing.T) {
// TestFetchItemsPageRefreshTokenFailure: token 过期无 Set-Cookie,RefreshToken 失败。
func TestFetchItemsPageRefreshTokenFailure(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// err 保存err,供当前处理流程使用
_, err := client.FetchItemsPage(context.Background(), consignCookies, 1, 20)
if err == nil || !strings.Contains(err.Error(), "刷新 mtop token 失败") {
t.Fatalf("err=%v", err)
@@ -378,27 +460,35 @@ func TestFetchItemsPageRefreshTokenFailure(t *testing.T) {
// ---- parseItemList 边缘字段 ----
// TestParseItemListEmpty 负责TestParse商品ListEmpty相关处理。
func TestParseItemListEmpty(t *testing.T) {
if got := parseItemList(map[string]any{}); len(got) != 0 {
if // got 保存got,供当前处理流程使用
got := parseItemList(map[string]any{}); len(got) != 0 {
t.Fatalf("got=%v want empty", got)
}
}
// TestParseItemListNonMapCardSkipped 负责TestParse商品ListNonMap卡密Skipped相关处理。
func TestParseItemListNonMapCardSkipped(t *testing.T) {
// data 保存数据,供当前处理流程使用
data := map[string]any{"cardList": []any{"not-a-map", 123, nil}}
if got := parseItemList(data); len(got) != 0 {
if // got 保存got,供当前处理流程使用
got := parseItemList(data); len(got) != 0 {
t.Fatalf("got=%v", got)
}
}
// TestParseItemListNilCardDataSkipped 负责TestParse商品ListNil卡密数据Skipped相关处理。
func TestParseItemListNilCardDataSkipped(t *testing.T) {
// card 是 map 但 cardData 为 nil,应跳过
data := map[string]any{"cardList": []any{map[string]any{"cardType": 1}}}
if got := parseItemList(data); len(got) != 0 {
if // got 保存got,供当前处理流程使用
got := parseItemList(data); len(got) != 0 {
t.Fatalf("got=%v", got)
}
}
// TestParseItemListIdFallsBackToCardDataId 负责TestParse商品List标识FallsBackTo卡密数据标识相关处理。
func TestParseItemListIdFallsBackToCardDataId(t *testing.T) {
// detailParams.itemId 为空,回退到 cardData.id
data := map[string]any{
@@ -412,12 +502,14 @@ func TestParseItemListIdFallsBackToCardDataId(t *testing.T) {
},
},
}
// items 保存商品列表,供当前处理流程使用
items := parseItemList(data)
if len(items) != 1 || items[0].ID != "fallback-id" {
t.Fatalf("items=%+v", items)
}
}
// TestParseItemListEmptyIdSkipped 负责TestParse商品ListEmpty标识Skipped相关处理。
func TestParseItemListEmptyIdSkipped(t *testing.T) {
// 两个 id 都空,跳过
data := map[string]any{
@@ -430,11 +522,13 @@ func TestParseItemListEmptyIdSkipped(t *testing.T) {
},
},
}
if got := parseItemList(data); len(got) != 0 {
if // got 保存got,供当前处理流程使用
got := parseItemList(data); len(got) != 0 {
t.Fatalf("got=%v", got)
}
}
// TestParseItemListNumericFields 负责TestParse商品ListNumeric字段列表相关处理。
func TestParseItemListNumericFields(t *testing.T) {
// price / auctionType 为数字,itemStatus 为数字
data := map[string]any{
@@ -452,17 +546,21 @@ func TestParseItemListNumericFields(t *testing.T) {
},
},
}
// items 保存商品列表,供当前处理流程使用
items := parseItemList(data)
if len(items) != 1 {
t.Fatalf("items=%d", len(items))
}
// it 保存it,供当前处理流程使用
it := items[0]
if it.Price != "99" || it.PriceText != "$99" || it.CategoryID != "7" || it.ItemStatus != 2 {
t.Fatalf("item=%+v", it)
}
}
// TestBuildItemListQuery 负责TestBuild商品List查询相关处理。
func TestBuildItemListQuery(t *testing.T) {
// q 保存q,供当前处理流程使用
q := buildItemListQuery("T", "SIGN")
if !strings.Contains(q, "t=T") || !strings.Contains(q, "sign=SIGN") ||
!strings.Contains(q, "api=mtop.idle.web.xyh.item.list") ||
+25 -2
View File
@@ -12,8 +12,10 @@ import (
"xianyu-go/internal/xianyu/protocol"
)
// LoginUserAPI 保存登录用户API,供当前处理流程使用
const LoginUserAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idlemessage.pc.loginuser.get/1.0/"
// LoginStatusSuccess 保存登录状态Success,供当前处理流程使用
const (
LoginStatusSuccess = "success"
LoginStatusTokenRefreshed = "token_refreshed"
@@ -34,20 +36,29 @@ type LoginStatusResult struct {
// CheckLoginStatusContext 调用 loginuser.get 做低成本登录态检查。
// 它不会做浏览器动作;只负责分类响应和合并 Set-Cookie。
// CheckLoginStatusContext 检查登录状态上下文。
func (c *ClientImpl) CheckLoginStatusContext(ctx context.Context, cookiesStr string) (*LoginStatusResult, error) {
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
cookiesStr, _, _ = session.State()
}
// hc 保存hc,供当前处理流程使用
hc := c.httpClientWithTimeout(20 * time.Second)
// loginURL 保存登录URL,供当前处理流程使用
loginURL := c.LoginUserURL
if loginURL == "" {
loginURL = LoginUserAPI
}
// signingCookies、requestCookies 保存signingCookies、requestCookies,供当前处理流程使用
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, mtopDocumentURL, loginURL)
// t 保存t,供当前处理流程使用
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
// dataVal 保存数据Val,供当前处理流程使用
dataVal := `{}`
// query 保存查询,供当前处理流程使用
query := buildLoginStatusQuery(t, protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal))
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost, loginURL+"?"+query, strings.NewReader("data=%7B%7D"))
if err != nil {
return nil, err
@@ -55,26 +66,32 @@ func (c *ClientImpl) CheckLoginStatusContext(ctx context.Context, cookiesStr str
setCommonHeaders(req, requestCookies)
req.Header.Set("Referer", mtopDocumentURL)
// resp、err 保存resp、err,供当前处理流程使用
resp, err := hc.Do(req)
if err != nil {
return nil, fmt.Errorf("loginuser.get 请求失败: %w", err)
}
defer resp.Body.Close()
// updated 保存updated,供当前处理流程使用
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readMTopBody(resp)
if err != nil {
return nil, err
}
// payload 保存请求载荷,供当前处理流程使用
var payload struct {
Ret []string `json:"ret"`
Data struct {
URL string `json:"url"`
} `json:"data"`
}
if err := json.Unmarshal(raw, &payload); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &payload); err != nil {
return nil, fmt.Errorf("解析 loginuser.get 响应失败: %w (body=%s)", err, truncate(string(raw), 300))
}
// status、msg 保存status、msg,供当前处理流程使用
status, msg := classifyLoginStatus(payload.Ret, updated != cookiesStr)
return &LoginStatusResult{
Status: status,
@@ -85,7 +102,9 @@ func (c *ClientImpl) CheckLoginStatusContext(ctx context.Context, cookiesStr str
}, nil
}
// buildLoginStatusQuery 负责build登录状态查询相关处理。
func buildLoginStatusQuery(t, sign string) string {
// parts 保存parts,供当前处理流程使用
parts := [][2]string{
{"jsv", "2.7.2"},
{"appKey", protocol.SignAppKey},
@@ -102,7 +121,9 @@ func buildLoginStatusQuery(t, sign string) string {
{"spm_pre", "a21ybx.item.want.1.12523da6waCtUp"},
{"log_id", "12523da6waCtUp"},
}
// b 保存b,供当前处理流程使用
var b strings.Builder
// i、p 表示当前遍历过程中的i、p
for i, p := range parts {
if i > 0 {
b.WriteByte('&')
@@ -114,6 +135,7 @@ func buildLoginStatusQuery(t, sign string) string {
return b.String()
}
// classifyLoginStatus 负责classify登录状态相关处理。
func classifyLoginStatus(ret []string, cookieUpdated bool) (string, string) {
if hasMTopSuccess(ret) {
return LoginStatusSuccess, "登录状态正常"
@@ -121,6 +143,7 @@ func classifyLoginStatus(ret []string, cookieUpdated bool) (string, string) {
if isRiskVerificationRet(ret) {
return LoginStatusRiskRequired, "闲鱼要求安全验证"
}
// retStr 保存retStr,供当前处理流程使用
retStr := strings.Join(ret, " ")
switch {
case strings.Contains(retStr, "TOKEN_EMPTY") || strings.Contains(retStr, "令牌为空"):
+14
View File
@@ -9,7 +9,9 @@ import (
"testing"
)
// TestRiskVerificationClassification 负责TestRiskVerificationClassification相关处理。
func TestRiskVerificationClassification(t *testing.T) {
// ret 保存ret,供当前处理流程使用
ret := []string{"FAIL_SYS_USER_VALIDATE::用户校验失败"}
if !isRiskVerificationRet(ret) {
t.Fatal("FAIL_SYS_USER_VALIDATE 应识别为风控")
@@ -17,20 +19,25 @@ func TestRiskVerificationClassification(t *testing.T) {
if isTokenExpiredRet(ret) {
t.Fatal("FAIL_SYS_USER_VALIDATE 不应再被当作普通 token 过期")
}
// err 保存err,供当前处理流程使用
err := &RiskVerificationError{Ret: ret, VerificationURL: "https://passport.goofish.com/punish?x5secdata=1"}
if !IsRiskVerificationErr(err) {
t.Fatal("RiskVerificationError 应被识别")
}
}
// TestRefreshTokenReturnsRiskVerificationError 负责TestRefresh令牌ReturnsRiskVerification错误相关处理。
func TestRefreshTokenReturnsRiskVerificationError(t *testing.T) {
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "newtk_1"})
fmt.Fprint(w, `{"ret":["FAIL_SYS_USER_VALIDATE::用户校验失败"],"data":{"url":"https://passport.goofish.com/punish?x5secdata=1"}}`)
}))
defer srv.Close()
// c 保存c,供当前处理流程使用
c := &ClientImpl{HTTPClient: srv.Client(), TokenURL: srv.URL}
// res、err 保存res、err,供当前处理流程使用
res, err := c.RefreshTokenWithDeviceIDContext(context.Background(), "unb=123; _m_h5_tk=old_1", "device-1")
if err == nil || !IsRiskVerificationErr(err) {
t.Fatalf("应返回风控错误: res=%#v err=%v", res, err)
@@ -38,20 +45,25 @@ func TestRefreshTokenReturnsRiskVerificationError(t *testing.T) {
if res == nil || !strings.Contains(res.UpdatedCookies, "_m_h5_tk=newtk_1") {
t.Fatalf("风控时仍应保留 Set-Cookie: %#v", res)
}
// riskErr 保存riskErr,供当前处理流程使用
var riskErr *RiskVerificationError
if !strings.Contains(err.Error(), "x5secdata") {
t.Fatalf("风控 URL 未进入错误信息: %v", riskErr)
}
}
// TestCheckLoginStatusTokenRefreshed 负责TestCheck登录状态令牌Refreshed相关处理。
func TestCheckLoginStatusTokenRefreshed(t *testing.T) {
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "newtk_1"})
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"],"data":{}}`)
}))
defer srv.Close()
// c 保存c,供当前处理流程使用
c := &ClientImpl{HTTPClient: srv.Client(), LoginUserURL: srv.URL}
// res、err 保存res、err,供当前处理流程使用
res, err := c.CheckLoginStatusContext(context.Background(), "unb=123; _m_h5_tk=old_1")
if err != nil {
t.Fatalf("CheckLoginStatusContext: %v", err)
@@ -64,7 +76,9 @@ func TestCheckLoginStatusTokenRefreshed(t *testing.T) {
}
}
// TestClassifyLoginStatusRisk 负责TestClassify登录状态Risk相关处理。
func TestClassifyLoginStatusRisk(t *testing.T) {
// status、msg 保存status、msg,供当前处理流程使用
status, msg := classifyLoginStatus([]string{"RGV587_ERROR::哎哟喂,被挤爆啦"}, false)
if status != LoginStatusRiskRequired || msg == "" {
t.Fatalf("status=%s msg=%q", status, msg)
+42 -9
View File
@@ -26,13 +26,19 @@ type OrderDetailResult struct {
// FetchOrderDetail 获取订单真实成交价、数量、状态和规格;token 过期时自动重签重试。
func (c *ClientImpl) FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*OrderDetailResult, error) {
// currentCookies 保存currentCookies,供当前处理流程使用
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
// lastRet 保存lastRet,供当前处理流程使用
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
for // attempt 保存尝试次数,供当前处理流程使用
attempt := 0; attempt < 4; attempt++ {
// previousCookies 保存previousCookies,供当前处理流程使用
previousCookies := currentCookies
// result、ret、updated、err 保存result、ret、updated、err,供当前处理流程使用
result, ret, updated, err := c.fetchOrderDetailOnce(ctx, currentCookies, orderID)
if err != nil {
return nil, err
@@ -55,76 +61,102 @@ func (c *ClientImpl) FetchOrderDetail(ctx context.Context, cookiesStr, orderID s
break
}
if currentCookies == previousCookies {
// refreshed、refreshErr 保存refreshed、refreshErr,供当前处理流程使用
refreshed, refreshErr := c.RefreshTokenContext(ctx, currentCookies)
if refreshErr != nil {
return nil, fmt.Errorf("订单详情 token 刷新失败: %w", refreshErr)
}
currentCookies = refreshed.UpdatedCookies
}
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
if // err 保存err,供当前处理流程使用
err := sleepCtx(ctx, MTopRetryGap); err != nil {
return nil, err
}
}
return nil, fmt.Errorf("订单详情 token 重试失败: ret=%v", lastRet)
}
// fetchOrderDetailOnce 负责fetch订单DetailOnce相关处理。
func (c *ClientImpl) fetchOrderDetailOnce(ctx context.Context, cookiesStr, orderID string) (*OrderDetailResult, []string, string, error) {
// hc 保存hc,供当前处理流程使用
hc := c.httpClient()
// endpoint 保存endpoint,供当前处理流程使用
endpoint := c.OrderDetailURL
if endpoint == "" {
endpoint = OrderDetailAPI
}
// documentURL 保存documentURL,供当前处理流程使用
documentURL := "https://www.goofish.com/order-detail?orderId=" + url.QueryEscape(orderID) + "&role=seller"
// signingCookies、requestCookies 保存signingCookies、requestCookies,供当前处理流程使用
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, documentURL, endpoint)
// t 保存t,供当前处理流程使用
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
// dataVal 保存数据Val,供当前处理流程使用
dataVal := `{"tid":"` + orderID + `"}`
// sign 保存sign,供当前处理流程使用
sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildOrderDetailQuery(t, sign), strings.NewReader("data="+url.QueryEscape(dataVal)))
if err != nil {
return nil, nil, cookiesStr, err
}
setCommonHeaders(req, requestCookies)
req.Header.Set("Referer", documentURL)
// resp、err 保存resp、err,供当前处理流程使用
resp, err := hc.Do(req)
if err != nil {
return nil, nil, cookiesStr, fmt.Errorf("订单详情请求失败: %w", err)
}
defer resp.Body.Close()
// updated 保存updated,供当前处理流程使用
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readMTopBody(resp)
if err != nil {
return nil, nil, updated, err
}
// decoded 保存decoded,供当前处理流程使用
var decoded struct {
Ret []string `json:"ret"`
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(raw, &decoded); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &decoded); err != nil {
return nil, nil, updated, fmt.Errorf("解析订单详情响应失败: %w (body=%s)", err, truncate(string(raw), 300))
}
if !hasMTopSuccess(decoded.Ret) {
return nil, decoded.Ret, updated, nil
}
// result 保存结果,供当前处理流程使用
result := &OrderDetailResult{Quantity: "1"}
if utArgs, ok := decoded.Data["utArgs"].(map[string]any); ok {
if // utArgs、ok 保存utArgs、ok,供当前处理流程使用
utArgs, ok := decoded.Data["utArgs"].(map[string]any); ok {
result.OrderStatus = mtopString(utArgs["orderStatus"])
}
// components 保存components,供当前处理流程使用
components, _ := decoded.Data["components"].([]any)
// component 表示当前遍历过程中的component
for _, component := range components {
// cm 保存cm,供当前处理流程使用
cm, _ := component.(map[string]any)
if cm["render"] != "orderInfoVO" {
continue
}
// componentData 保存component数据,供当前处理流程使用
componentData, _ := cm["data"].(map[string]any)
if itemInfo, ok := componentData["itemInfo"].(map[string]any); ok {
if value := mtopString(itemInfo["buyAmount"]); value != "" {
if // itemInfo、ok 保存商品Info、ok,供当前处理流程使用
itemInfo, ok := componentData["itemInfo"].(map[string]any); ok {
if // value 保存值,供当前处理流程使用
value := mtopString(itemInfo["buyAmount"]); value != "" {
result.Quantity = value
}
result.SpecName = mtopString(itemInfo["specName"])
result.SpecValue = mtopString(itemInfo["specValue"])
}
if priceInfo, ok := componentData["priceInfo"].(map[string]any); ok {
if amount, ok := priceInfo["amount"].(map[string]any); ok {
if // priceInfo、ok 保存priceInfo、ok,供当前处理流程使用
priceInfo, ok := componentData["priceInfo"].(map[string]any); ok {
if // amount、ok 保存amount、ok,供当前处理流程使用
amount, ok := priceInfo["amount"].(map[string]any); ok {
result.Amount = mtopString(amount["value"])
}
}
@@ -132,6 +164,7 @@ func (c *ClientImpl) fetchOrderDetailOnce(ctx context.Context, cookiesStr, order
return result, decoded.Ret, updated, nil
}
// buildOrderDetailQuery 负责build订单Detail查询相关处理。
func buildOrderDetailQuery(t, sign string) string {
return "jsv=2.7.2&appKey=" + protocol.SignAppKey +
"&t=" + t + "&sign=" + sign +
+44
View File
@@ -13,12 +13,15 @@ import (
// TestFetchOrderDetailSuccessWithSpecAndStatus: 完整解析 utArgs/components,含 spec。
func TestFetchOrderDetailSuccessWithSpecAndStatus(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"4"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"3","specName":"颜色","specValue":"红色"},"priceInfo":{"amount":{"value":"88.00"}}}}]}}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/"}
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchOrderDetail(context.Background(), consignCookies, "order-1")
if err != nil {
t.Fatalf("err=%v", err)
@@ -31,12 +34,15 @@ func TestFetchOrderDetailSuccessWithSpecAndStatus(t *testing.T) {
// TestFetchOrderDetailMissingBuyAmountDefaultsTo1: components 无 buyAmount 时 Quantity 默认 "1"。
func TestFetchOrderDetailMissingBuyAmountDefaultsTo1(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"components":[{"render":"orderInfoVO","data":{"itemInfo":{}}}]}}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/"}
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchOrderDetail(context.Background(), consignCookies, "order-1")
if err != nil {
t.Fatalf("err=%v", err)
@@ -48,14 +54,18 @@ func TestFetchOrderDetailMissingBuyAmountDefaultsTo1(t *testing.T) {
// TestFetchOrderDetailNonSuccessRet: 非 token 过期的失败 ret。
func TestFetchOrderDetailNonSuccessRet(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
fmt.Fprint(w, `{"ret":["FAIL_BIZ_ORDER_NOT_FOUND::订单不存在"]}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.FetchOrderDetail(context.Background(), consignCookies, "order-1")
if err == nil || !strings.Contains(err.Error(), "订单详情接口返回非成功") {
t.Fatalf("err=%v", err)
@@ -67,12 +77,15 @@ func TestFetchOrderDetailNonSuccessRet(t *testing.T) {
// TestFetchOrderDetailParseFailure: 响应非 JSON。
func TestFetchOrderDetailParseFailure(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `broken{`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.FetchOrderDetail(context.Background(), consignCookies, "order-1")
if err == nil || !strings.Contains(err.Error(), "解析订单详情响应失败") {
t.Fatalf("err=%v", err)
@@ -81,10 +94,13 @@ func TestFetchOrderDetailParseFailure(t *testing.T) {
// TestFetchOrderDetailRequestError: 网络层错误。
func TestFetchOrderDetailRequestError(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.FetchOrderDetail(context.Background(), consignCookies, "order-1")
if err == nil || !strings.Contains(err.Error(), "订单详情请求失败") {
t.Fatalf("err=%v", err)
@@ -93,8 +109,11 @@ func TestFetchOrderDetailRequestError(t *testing.T) {
// TestFetchOrderDetailTokenExpiredRetriesWithSetCookie: token 过期 + Set-Cookie,二次成功。
func TestFetchOrderDetailTokenExpiredRetriesWithSetCookie(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// attempt 保存尝试次数,供当前处理流程使用
attempt := requests.Add(1)
if attempt == 1 {
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "newtoken_5", Path: "/"})
@@ -105,9 +124,12 @@ func TestFetchOrderDetailTokenExpiredRetriesWithSetCookie(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/"}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchOrderDetail(ctx, consignCookies, "order-1")
if err != nil {
t.Fatalf("err=%v", err)
@@ -125,14 +147,18 @@ func TestFetchOrderDetailTokenExpiredRetriesWithSetCookie(t *testing.T) {
// TestFetchOrderDetailTokenExpiredNoCookieRefreshes: token 过期无 Set-Cookie,
// 走 RefreshToken 刷新成功后重试成功。
// TestFetchOrderDetailTokenExpiredNoCookieRefreshes 负责TestFetch订单Detail令牌ExpiredNo登录凭证Refreshes相关处理。
func TestFetchOrderDetailTokenExpiredNoCookieRefreshes(t *testing.T) {
// orderReqs 保存订单Reqs,供当前处理流程使用
var orderReqs atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("api") == "mtop.taobao.idlemessage.pc.login.token" {
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "refreshed_7", Path: "/"})
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"a"}}`)
return
}
// attempt 保存尝试次数,供当前处理流程使用
attempt := orderReqs.Add(1)
if attempt == 1 {
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`)
@@ -142,9 +168,12 @@ func TestFetchOrderDetailTokenExpiredNoCookieRefreshes(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/o", TokenURL: server.URL + "/t"}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchOrderDetail(ctx, consignCookies, "order-1")
if err != nil {
t.Fatalf("err=%v", err)
@@ -156,13 +185,17 @@ func TestFetchOrderDetailTokenExpiredNoCookieRefreshes(t *testing.T) {
// TestFetchOrderDetailNoOrderInfoComponent: SUCCESS 但无 orderInfoVO component,
// Quantity 默认 1,其他字段空。
// TestFetchOrderDetailNoOrderInfoComponent 负责TestFetch订单DetailNo订单InfoComponent相关处理。
func TestFetchOrderDetailNoOrderInfoComponent(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"components":[{"render":"otherVO","data":{}}]}}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/"}
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchOrderDetail(context.Background(), consignCookies, "order-1")
if err != nil {
t.Fatalf("err=%v", err)
@@ -174,13 +207,17 @@ func TestFetchOrderDetailNoOrderInfoComponent(t *testing.T) {
// TestFetchOrderDetailTruncateInParseError: 解析失败时 body 截断 300 字符。
func TestFetchOrderDetailTruncateInParseError(t *testing.T) {
// longBody 保存long请求体,供当前处理流程使用
longBody := strings.Repeat("a", 500)
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, longBody)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.FetchOrderDetail(context.Background(), consignCookies, "order-1")
if err == nil {
t.Fatalf("expected err")
@@ -196,17 +233,23 @@ func TestFetchOrderDetailTruncateInParseError(t *testing.T) {
// TestFetchOrderDetailRetryExhausted: token 过期但每次下发不同 Set-Cookie,4 次重试耗尽。
func TestFetchOrderDetailRetryExhausted(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// n 保存n,供当前处理流程使用
n := requests.Add(1)
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: fmt.Sprintf("tok_%d", n), Path: "/"})
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/"}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// err 保存err,供当前处理流程使用
_, err := client.FetchOrderDetail(ctx, consignCookies, "order-1")
if err == nil || !strings.Contains(err.Error(), "订单详情 token 重试失败") {
t.Fatalf("err=%v", err)
@@ -218,6 +261,7 @@ func TestFetchOrderDetailRetryExhausted(t *testing.T) {
// TestBuildOrderDetailQuery: 验证 query 拼接。
func TestBuildOrderDetailQuery(t *testing.T) {
// q 保存q,供当前处理流程使用
q := buildOrderDetailQuery("T", "SIGN")
if !strings.Contains(q, "t=T") || !strings.Contains(q, "sign=SIGN") ||
!strings.Contains(q, "api=mtop.idle.web.trade.order.detail") ||
+160 -14
View File
@@ -23,6 +23,7 @@ import (
"xianyu-go/internal/xianyu/protocol"
)
// UploadMediaAPI 保存UploadMediaAPI,供当前处理流程使用
const (
UploadMediaAPI = "https://stream-upload.goofish.com/api/upload.api"
PublishItemAPI = "https://h5api.m.goofish.com/h5/mtop.idle.pc.idleitem.publish/1.0/"
@@ -31,22 +32,27 @@ const (
// ErrPublishCategoryUnrecognized 表示闲鱼类目推荐接口调用成功,但没有给出可发布类目。
// 这是发生在最终发布接口之前的确定性结果,调用方可以安全地改用人工指定类目。
// ErrPublishCategoryUnrecognized 保存Err发布分类Unrecognized,供当前处理流程使用
var ErrPublishCategoryUnrecognized = errors.New("未能自动识别商品类目,请调整标题或图片后重试")
// PublishErrorCode 保存发布错误Code,供当前处理流程使用
type PublishErrorCode string
// PublishErrorUnknown 保存发布错误Unknown,供当前处理流程使用
const (
PublishErrorUnknown PublishErrorCode = "publish_failed"
PublishErrorTokenExpired PublishErrorCode = "auth_expired"
PublishErrorStockPermissionMissing PublishErrorCode = "stock_permission_missing"
)
// PublishError 保存发布错误,供当前处理流程使用
type PublishError struct {
Code PublishErrorCode
Ret []string
Body string
}
// Error 负责错误相关处理。
func (e *PublishError) Error() string {
if len(e.Ret) > 0 {
return strings.Join(e.Ret, "; ")
@@ -57,6 +63,7 @@ func (e *PublishError) Error() string {
return string(e.Code)
}
// PublishImage 保存发布图片,供当前处理流程使用
type PublishImage struct {
Filename string
ContentType string
@@ -65,6 +72,7 @@ type PublishImage struct {
// PublishCategory 是发布商品时可使用的人工兜底类目。
// CatID、CatName 和 ChannelCatID 必填;部分闲鱼类目没有 TBCatID。
// PublishCategory 保存发布分类,供当前处理流程使用
type PublishCategory struct {
CatID string `json:"cat_id"`
CatName string `json:"cat_name"`
@@ -86,6 +94,7 @@ type PublishLocation struct {
// DefaultVirtualPublishCategory 是从闲鱼类目推荐响应中核实的“电子资料”类目。
// 该类目没有 tbCatId,发布时必须保留为空而不是伪造淘宝类目 ID。
// DefaultVirtualPublishCategory 负责DefaultVirtual发布分类相关处理。
func DefaultVirtualPublishCategory() PublishCategory {
return PublishCategory{
CatID: "50023914",
@@ -94,6 +103,7 @@ func DefaultVirtualPublishCategory() PublishCategory {
}
}
// PublishItemRequest 保存发布商品请求,供当前处理流程使用
type PublishItemRequest struct {
Title string
Description string
@@ -109,6 +119,7 @@ type PublishItemRequest struct {
Images []PublishImage
}
// PublishItemResult 保存发布商品结果,供当前处理流程使用
type PublishItemResult struct {
ItemID string
ItemURL string
@@ -122,12 +133,14 @@ type PublishItemResult struct {
UpdatedCookies string
}
// uploadedImage 保存uploaded图片,供当前处理流程使用
type uploadedImage struct {
URL string
Width int
Height int
}
// PublishItem 负责发布商品相关处理。
func (c *ClientImpl) PublishItem(ctx context.Context, cookiesStr string, req PublishItemRequest) (*PublishItemResult, error) {
if strings.TrimSpace(req.Title) == "" {
return nil, errors.New("商品标题不能为空")
@@ -150,12 +163,17 @@ func (c *ClientImpl) PublishItem(ctx context.Context, cookiesStr string, req Pub
if req.PreferredCategory != nil && !validPublishCategory(*req.PreferredCategory) {
return nil, errors.New("默认类目必须同时包含类目 ID、类目名称和频道类目 ID")
}
// currentCookies 保存currentCookies,供当前处理流程使用
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
// uploaded 保存uploaded,供当前处理流程使用
uploaded := make([]uploadedImage, 0, len(req.Images))
// img 表示当前遍历过程中的img
for _, img := range req.Images {
// res、updated、err 保存res、updated、err,供当前处理流程使用
res, updated, err := c.uploadPublishImage(ctx, currentCookies, img)
if err != nil {
return nil, err
@@ -165,8 +183,11 @@ func (c *ClientImpl) PublishItem(ctx context.Context, cookiesStr string, req Pub
}
uploaded = append(uploaded, res)
}
// category 保存分类,供当前处理流程使用
var category map[string]any
// updated 保存updated,供当前处理流程使用
var updated string
// err 保存err,供当前处理流程使用
var err error
if req.PreferredCategory != nil {
category = fallbackPublishCategory(*req.PreferredCategory)
@@ -192,11 +213,14 @@ func (c *ClientImpl) RecommendPublishCategory(ctx context.Context, cookiesStr, k
if keyword == "" {
return PublishCategory{}, cookiesStr, errors.New("类目关键词不能为空")
}
// data、updated、err 保存data、updated、err,供当前处理流程使用
data, updated, err := c.recommendPublishCategory(ctx, cookiesStr, keyword, keyword, nil)
if err != nil {
return PublishCategory{}, updated, err
}
// cat 保存cat,供当前处理流程使用
cat := mapFromAny(data["categoryPredictResult"])
// category 保存分类,供当前处理流程使用
category := PublishCategory{
CatID: strings.TrimSpace(mtopString(cat["catId"])),
CatName: strings.TrimSpace(mtopString(cat["catName"])),
@@ -209,7 +233,9 @@ func (c *ClientImpl) RecommendPublishCategory(ctx context.Context, cookiesStr, k
return category, updated, nil
}
// uploadPublishImage 负责upload发布图片相关处理。
func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string, img PublishImage) (uploadedImage, string, error) {
// hc 保存hc,供当前处理流程使用
hc := c.httpClientWithTimeout(60 * time.Second)
if img.ContentType == "" {
img.ContentType = "application/octet-stream"
@@ -217,41 +243,54 @@ func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string,
if img.Filename == "" {
img.Filename = "image"
}
// body 保存请求体,供当前处理流程使用
var body bytes.Buffer
// mw 保存mw,供当前处理流程使用
mw := multipart.NewWriter(&body)
// header 保存header,供当前处理流程使用
header := make(textproto.MIMEHeader)
header.Set("Content-Disposition", fmt.Sprintf("form-data; name=\"file\"; filename=\"%s\"", escapeMultipartFilename(filepath.Base(img.Filename))))
header.Set("Content-Type", img.ContentType)
// part、err 保存part、err,供当前处理流程使用
part, err := mw.CreatePart(header)
if err != nil {
return uploadedImage{}, cookiesStr, err
}
if _, err := part.Write(img.Data); err != nil {
if // err 保存err,供当前处理流程使用
_, err := part.Write(img.Data); err != nil {
return uploadedImage{}, cookiesStr, err
}
if err := mw.Close(); err != nil {
if // err 保存err,供当前处理流程使用
err := mw.Close(); err != nil {
return uploadedImage{}, cookiesStr, err
}
// u 保存u,供当前处理流程使用
u, _ := url.Parse(UploadMediaAPI)
// q 保存q,供当前处理流程使用
q := u.Query()
q.Set("floderId", "0")
q.Set("appkey", "xy_chat")
q.Set("_input_charset", "utf-8")
u.RawQuery = q.Encode()
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), &body)
if err != nil {
return uploadedImage{}, cookiesStr, err
}
// requestCookies 保存请求Cookies,供当前处理流程使用
_, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", u.String())
req.Header.Set("content-type", mw.FormDataContentType())
setBrowserHeaders(req, requestCookies)
req.Header.Set("accept", "*/*")
// resp、err 保存resp、err,供当前处理流程使用
resp, err := hc.Do(req)
if err != nil {
return uploadedImage{}, cookiesStr, fmt.Errorf("上传商品图片失败: %w", err)
}
defer resp.Body.Close()
// updated 保存updated,供当前处理流程使用
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readMTopBody(resp)
if err != nil {
return uploadedImage{}, updated, err
@@ -259,14 +298,18 @@ func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string,
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return uploadedImage{}, updated, fmt.Errorf("上传商品图片失败: http=%d body=%s", resp.StatusCode, truncate(string(raw), 240))
}
// decoded 保存decoded,供当前处理流程使用
var decoded map[string]any
if err := json.Unmarshal(raw, &decoded); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &decoded); err != nil {
return uploadedImage{}, updated, fmt.Errorf("解析图片上传响应失败: %w (body=%s)", err, truncate(string(raw), 240))
}
// obj 保存obj,供当前处理流程使用
obj := mapFromAny(decoded["object"])
if obj == nil {
obj = mapFromAny(decoded["data"])
}
// imageURL 保存图片URL,供当前处理流程使用
imageURL := mtopString(obj["url"])
if imageURL == "" {
imageURL = mtopString(decoded["url"])
@@ -274,9 +317,11 @@ func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string,
if imageURL == "" {
return uploadedImage{}, updated, fmt.Errorf("图片上传响应缺少 url: %s", truncate(string(raw), 240))
}
// width、height 保存width、height,供当前处理流程使用
width, height := parsePix(mtopString(obj["pix"]))
if width == 0 || height == 0 {
if cfg, _, err := image.DecodeConfig(bytes.NewReader(img.Data)); err == nil {
if // cfg、err 保存cfg、err,供当前处理流程使用
cfg, _, err := image.DecodeConfig(bytes.NewReader(img.Data)); err == nil {
width, height = cfg.Width, cfg.Height
}
}
@@ -289,11 +334,15 @@ func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string,
return uploadedImage{URL: imageURL, Width: width, Height: height}, updated, nil
}
// recommendPublishCategory 负责recommend发布分类相关处理。
func (c *ClientImpl) recommendPublishCategory(ctx context.Context, cookiesStr, title, desc string, images []uploadedImage) (map[string]any, string, error) {
// imageInfos 保存图片Infos,供当前处理流程使用
imageInfos := make([]any, 0, len(images))
// i、img 表示当前遍历过程中的i、img
for i, img := range images {
imageInfos = append(imageInfos, publishImagePayload(img, i == 0))
}
// data 保存数据,供当前处理流程使用
data := map[string]any{
"title": title,
"lockCpv": false,
@@ -306,6 +355,7 @@ func (c *ClientImpl) recommendPublishCategory(ctx context.Context, cookiesStr, t
if len(imageInfos) > 0 {
data["imageInfos"] = imageInfos
}
// decoded、updated、err 保存decoded、updated、err,供当前处理流程使用
decoded, updated, err := c.callMTop(ctx, cookiesStr, RecommendItemAPI, "mtop.taobao.idle.kgraph.property.recommend", "2.0", "a21ybx.publish.0.0", "a21ybx.item.sidebar.1.67321598K9Vgx8", "67321598K9Vgx8", data)
if err != nil {
return nil, updated, err
@@ -313,15 +363,18 @@ func (c *ClientImpl) recommendPublishCategory(ctx context.Context, cookiesStr, t
if !hasMTopSuccess(retFromDecoded(decoded)) {
return nil, updated, classifyPublishError(retFromDecoded(decoded), decoded)
}
// dataMap 保存数据Map,供当前处理流程使用
dataMap := mapFromAny(decoded["data"])
if dataMap == nil {
return nil, updated, fmt.Errorf("%w: 类目推荐响应缺少 data", ErrPublishCategoryUnrecognized)
}
// cat 保存cat,供当前处理流程使用
cat := mapFromAny(dataMap["categoryPredictResult"])
if !validPublishCategoryMap(cat) {
// 部分账号/场景仅在 cardList 的“分类”卡片返回已选中的类目,
// 不返回 categoryPredictResult。将其转换为统一的发布类目结构。
if selected := selectedCategoryFromCards(dataMap); selected != nil {
if // selected 保存selected,供当前处理流程使用
selected := selectedCategoryFromCards(dataMap); selected != nil {
cat = selected
dataMap["categoryPredictResult"] = selected
}
@@ -332,6 +385,7 @@ func (c *ClientImpl) recommendPublishCategory(ctx context.Context, cookiesStr, t
return dataMap, updated, nil
}
// validPublishCategoryMap 负责有效发布分类Map相关处理。
func validPublishCategoryMap(category map[string]any) bool {
return category != nil &&
strings.TrimSpace(mtopString(category["catId"])) != "" &&
@@ -339,15 +393,22 @@ func validPublishCategoryMap(category map[string]any) bool {
strings.TrimSpace(mtopString(category["channelCatId"])) != ""
}
// selectedCategoryFromCards 负责selected分类From卡密列表相关处理。
func selectedCategoryFromCards(data map[string]any) map[string]any {
// cards 保存卡密列表,供当前处理流程使用
cards, _ := data["cardList"].([]any)
// rawCard 表示当前遍历过程中的原始卡密
for _, rawCard := range cards {
// cardData 保存卡密数据,供当前处理流程使用
cardData := mapFromAny(mapFromAny(rawCard)["cardData"])
if cardData == nil || mtopString(cardData["propertyId"]) != "-10000" {
continue
}
// values 保存values,供当前处理流程使用
values, _ := cardData["valuesList"].([]any)
// rawValue 表示当前遍历过程中的原始值
for _, rawValue := range values {
// value 保存值,供当前处理流程使用
value := mapFromAny(rawValue)
if value == nil || !publishLabelSelected(value["isClicked"]) || mtopString(value["catId"]) == "" {
continue
@@ -363,12 +424,14 @@ func selectedCategoryFromCards(data map[string]any) map[string]any {
return nil
}
// validPublishCategory 负责有效发布分类相关处理。
func validPublishCategory(category PublishCategory) bool {
return strings.TrimSpace(category.CatID) != "" &&
strings.TrimSpace(category.CatName) != "" &&
strings.TrimSpace(category.ChannelCatID) != ""
}
// fallbackPublishCategory 负责fallback发布分类相关处理。
func fallbackPublishCategory(category PublishCategory) map[string]any {
category = PublishCategory{
CatID: strings.TrimSpace(category.CatID),
@@ -400,16 +463,22 @@ func fallbackPublishCategory(category PublishCategory) map[string]any {
}
}
// validPublishLocation 负责有效发布地址相关处理。
func validPublishLocation(loc PublishLocation) bool {
return loc.DivisionID != "" && loc.Province != "" && loc.City != "" && loc.Longitude >= -180 && loc.Longitude <= 180 && loc.Latitude >= -90 && loc.Latitude <= 90 && !(loc.Longitude == 0 && loc.Latitude == 0)
}
// publishItemOnce 负责发布商品Once相关处理。
func (c *ClientImpl) publishItemOnce(ctx context.Context, cookiesStr string, req PublishItemRequest, images []uploadedImage, category map[string]any) (*PublishItemResult, error) {
// imagePayloads 保存图片Payloads,供当前处理流程使用
imagePayloads := make([]any, 0, len(images))
// i、img 表示当前遍历过程中的i、img
for i, img := range images {
imagePayloads = append(imagePayloads, publishImagePayload(img, i == 0))
}
// cat 保存cat,供当前处理流程使用
cat := mapFromAny(category["categoryPredictResult"])
// data 保存数据,供当前处理流程使用
data := map[string]any{
"freebies": false,
"itemTypeStr": "b",
@@ -448,19 +517,24 @@ func (c *ClientImpl) publishItemOnce(ctx context.Context, cookiesStr string, req
} else if !req.Virtual {
return nil, errors.New("发布实物商品前必须选择发货地")
}
// decoded、updated、err 保存decoded、updated、err,供当前处理流程使用
decoded, updated, err := c.callMTop(ctx, cookiesStr, PublishItemAPI, "mtop.idle.pc.idleitem.publish", "1.0", "a21ybx.publish.0.0", "a21ybx.home.sidebar.1.46413da6EPl7v5", "46413da6EPl7v5", data)
if err != nil {
return nil, err
}
// ret 保存ret,供当前处理流程使用
ret := retFromDecoded(decoded)
if !hasMTopSuccess(ret) {
return nil, classifyPublishError(ret, decoded)
}
// dataMap 保存数据Map,供当前处理流程使用
dataMap := mapFromAny(decoded["data"])
// itemID 保存商品ID,供当前处理流程使用
itemID := findStringDeep(dataMap, "itemId", "item_id", "id", "itemID")
if itemID == "" {
itemID = findStringDeep(decoded, "itemId", "item_id", "itemID")
}
// result 保存结果,供当前处理流程使用
result := &PublishItemResult{
ItemID: itemID,
Title: req.Title,
@@ -478,38 +552,55 @@ func (c *ClientImpl) publishItemOnce(ctx context.Context, cookiesStr string, req
return result, nil
}
// callMTop 负责callMTop相关处理。
func (c *ClientImpl) callMTop(ctx context.Context, cookiesStr, endpoint, api, version, spmCnt, spmPre, logID string, data any) (map[string]any, string, error) {
// hc 保存hc,供当前处理流程使用
hc := c.httpClient()
// rawData 保存原始数据,供当前处理流程使用
rawData, _ := json.Marshal(data)
// dataVal 保存数据Val,供当前处理流程使用
dataVal := string(rawData)
// signingCookies、requestCookies 保存signingCookies、requestCookies,供当前处理流程使用
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", endpoint)
// t 保存t,供当前处理流程使用
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
// sign 保存sign,供当前处理流程使用
sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
// query 保存查询,供当前处理流程使用
query := buildMTopQuery(api, version, t, sign, spmCnt, spmPre, logID)
// body 保存请求体,供当前处理流程使用
body := "data=" + url.QueryEscape(dataVal)
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+query, strings.NewReader(body))
if err != nil {
return nil, cookiesStr, err
}
setCommonHeaders(req, requestCookies)
// resp、err 保存resp、err,供当前处理流程使用
resp, err := hc.Do(req)
if err != nil {
return nil, cookiesStr, fmt.Errorf("%s 请求失败: %w", api, err)
}
defer resp.Body.Close()
// updated 保存updated,供当前处理流程使用
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readMTopBody(resp)
if err != nil {
return nil, updated, err
}
// decoded 保存decoded,供当前处理流程使用
var decoded map[string]any
if err := json.Unmarshal(raw, &decoded); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &decoded); err != nil {
return nil, updated, fmt.Errorf("解析 %s 响应失败: %w (body=%s)", api, err, truncate(string(raw), 300))
}
return decoded, updated, nil
}
// buildMTopQuery 负责buildMTop查询相关处理。
func buildMTopQuery(api, version, t, sign, spmCnt, spmPre, logID string) string {
// parts 保存parts,供当前处理流程使用
parts := [][2]string{
{"jsv", "2.7.2"},
{"appKey", protocol.SignAppKey},
@@ -526,7 +617,9 @@ func buildMTopQuery(api, version, t, sign, spmCnt, spmPre, logID string) string
{"spm_pre", spmPre},
{"log_id", logID},
}
// b 保存b,供当前处理流程使用
var b strings.Builder
// i、p 表示当前遍历过程中的i、p
for i, p := range parts {
if i > 0 {
b.WriteByte('&')
@@ -538,6 +631,7 @@ func buildMTopQuery(api, version, t, sign, spmCnt, spmPre, logID string) string
return b.String()
}
// setBrowserHeaders 负责set浏览器Headers相关处理。
func setBrowserHeaders(req *http.Request, cookiesStr string) {
xianyu.ApplyBrowserFingerprint(req.Header)
req.Header.Set("accept-language", "zh-CN,zh;q=0.9,en;q=0.8")
@@ -548,6 +642,7 @@ func setBrowserHeaders(req *http.Request, cookiesStr string) {
req.Header.Set("cookie", cookiesStr)
}
// publishImagePayload 负责发布图片请求载荷相关处理。
func publishImagePayload(img uploadedImage, major bool) map[string]any {
return map[string]any{
"extraInfo": map[string]any{"isH": "false", "isT": "false", "raw": "false"},
@@ -561,7 +656,9 @@ func publishImagePayload(img uploadedImage, major bool) map[string]any {
}
}
// publishPriceDTO 负责发布PriceDTO相关处理。
func publishPriceDTO(req PublishItemRequest) map[string]any {
// out 保存out,供当前处理流程使用
out := map[string]any{"priceInCent": strconv.FormatInt(req.PriceCents, 10)}
if req.OriginalPriceCents > 0 {
out["origPriceInCent"] = strconv.FormatInt(req.OriginalPriceCents, 10)
@@ -569,7 +666,9 @@ func publishPriceDTO(req PublishItemRequest) map[string]any {
return out
}
// postageDTO 负责postageDTO相关处理。
func postageDTO(req PublishItemRequest) map[string]any {
// out 保存out,供当前处理流程使用
out := map[string]any{"canFreeShipping": false, "supportFreight": false, "onlyTakeSelf": false}
switch req.PostageMode {
case "free", "":
@@ -591,24 +690,37 @@ func postageDTO(req PublishItemRequest) map[string]any {
return out
}
// publishLabels 负责发布Labels相关处理。
func publishLabels(category map[string]any) []any {
// cards 保存卡密列表,供当前处理流程使用
cards, _ := category["cardList"].([]any)
// out 保存out,供当前处理流程使用
out := []any{}
// rawCard 表示当前遍历过程中的原始卡密
for _, rawCard := range cards {
// card 保存卡密,供当前处理流程使用
card := mapFromAny(rawCard)
// cardData 保存卡密数据,供当前处理流程使用
cardData := mapFromAny(card["cardData"])
if cardData == nil {
continue
}
// values 保存values,供当前处理流程使用
values, _ := cardData["valuesList"].([]any)
// rawValue 表示当前遍历过程中的原始值
for _, rawValue := range values {
// value 保存值,供当前处理流程使用
value := mapFromAny(rawValue)
if !publishLabelSelected(value["isClicked"]) {
continue
}
// propertyID 保存propertyID,供当前处理流程使用
propertyID := mtopString(cardData["propertyId"])
// propertyName 保存property名称,供当前处理流程使用
propertyName := mtopString(cardData["propertyName"])
// channelCatID 保存渠道CatID,供当前处理流程使用
channelCatID := mtopString(value["channelCatId"])
// catName 保存cat名称,供当前处理流程使用
catName := mtopString(value["catName"])
out = append(out, map[string]any{
"channelCateName": catName,
@@ -635,8 +747,10 @@ func publishLabels(category map[string]any) []any {
return out
}
// publishLabelSelected 负责发布LabelSelected相关处理。
func publishLabelSelected(value any) bool {
if selected, ok := value.(bool); ok {
if // selected、ok 保存selected、ok,供当前处理流程使用
selected, ok := value.(bool); ok {
return selected
}
switch strings.ToLower(strings.TrimSpace(mtopString(value))) {
@@ -647,14 +761,20 @@ func publishLabelSelected(value any) bool {
}
}
// classifyPublishError 负责classify发布错误相关处理。
func classifyPublishError(ret []string, decoded map[string]any) error {
// bodyBytes 保存请求体Bytes,供当前处理流程使用
bodyBytes, _ := json.Marshal(decoded)
// body 保存请求体,供当前处理流程使用
body := string(bodyBytes)
// joined 保存joined,供当前处理流程使用
joined := strings.ToLower(strings.Join(append(ret, body), " "))
if isTokenExpiredRet(ret) || strings.Contains(joined, "login") || strings.Contains(joined, "session") {
return &PublishError{Code: PublishErrorTokenExpired, Ret: ret, Body: body}
}
// stockTerms 保存stockTerms,供当前处理流程使用
stockTerms := []string{"库存", "数量", "多库存", "多件", "quantity", "stock", "inventory"}
// permissionTerms 保存permissionTerms,供当前处理流程使用
permissionTerms := []string{"权限", "未开通", "不支持", "没有", "无法", "permission", "forbidden", "not allow", "not support"}
if containsAny(joined, stockTerms) && containsAny(joined, permissionTerms) {
return &PublishError{Code: PublishErrorStockPermissionMissing, Ret: ret, Body: body}
@@ -662,7 +782,9 @@ func classifyPublishError(ret []string, decoded map[string]any) error {
return &PublishError{Code: PublishErrorUnknown, Ret: ret, Body: body}
}
// containsAny 负责containsAny相关处理。
func containsAny(s string, terms []string) bool {
// term 表示当前遍历过程中的term
for _, term := range terms {
if strings.Contains(s, strings.ToLower(term)) {
return true
@@ -671,56 +793,78 @@ func containsAny(s string, terms []string) bool {
return false
}
// retFromDecoded 负责retFromDecoded相关处理。
func retFromDecoded(decoded map[string]any) []string {
// raw 保存原始,供当前处理流程使用
raw, _ := decoded["ret"].([]any)
// out 保存out,供当前处理流程使用
out := make([]string, 0, len(raw))
// r 表示当前遍历过程中的r
for _, r := range raw {
out = append(out, mtopString(r))
}
return out
}
// mapFromAny 负责mapFromAny相关处理。
func mapFromAny(v any) map[string]any {
if m, ok := v.(map[string]any); ok {
if // m、ok 保存m、ok,供当前处理流程使用
m, ok := v.(map[string]any); ok {
return m
}
return nil
}
// parsePix 负责parsePix相关处理。
func parsePix(pix string) (int, int) {
// parts 保存parts,供当前处理流程使用
parts := strings.Split(pix, "x")
if len(parts) != 2 {
return 0, 0
}
// w 保存w,供当前处理流程使用
w, _ := strconv.Atoi(parts[0])
// h 保存h,供当前处理流程使用
h, _ := strconv.Atoi(parts[1])
return w, h
}
// findStringDeep 负责findStringDeep相关处理。
func findStringDeep(v any, keys ...string) string {
// keySet 保存keySet,供当前处理流程使用
keySet := map[string]struct{}{}
// k 表示当前遍历过程中的k
for _, k := range keys {
keySet[k] = struct{}{}
}
// walk 保存walk,供当前处理流程使用
var walk func(any) string
walk = func(cur any) string {
switch x := cur.(type) {
switch // x 保存x,供当前处理流程使用
x := cur.(type) {
case map[string]any:
// k、v 表示当前遍历过程中的k、v
for k, v := range x {
if _, ok := keySet[k]; ok {
if s := mtopString(v); s != "" {
if // ok 保存ok,供当前处理流程使用
_, ok := keySet[k]; ok {
if // s 保存s,供当前处理流程使用
s := mtopString(v); s != "" {
return s
}
}
}
// v 表示当前遍历过程中的v
for _, v := range x {
if s := walk(v); s != "" {
if // s 保存s,供当前处理流程使用
s := walk(v); s != "" {
return s
}
}
case []any:
// v 表示当前遍历过程中的v
for _, v := range x {
if s := walk(v); s != "" {
if // s 保存s,供当前处理流程使用
s := walk(v); s != "" {
return s
}
}
@@ -730,10 +874,12 @@ func findStringDeep(v any, keys ...string) string {
return walk(v)
}
// centsText 负责cents文本相关处理。
func centsText(cents int64) string {
return strconv.FormatFloat(float64(cents)/100, 'f', 2, 64)
}
// escapeMultipartFilename 负责escapeMultipartFilename相关处理。
func escapeMultipartFilename(s string) string {
return strings.NewReplacer("\\", "\\\\", "\"", "\\\"").Replace(s)
}
+199 -16
View File
@@ -19,14 +19,18 @@ import (
// publish.go 用常量 URL(UploadMediaAPI / RecommendItemAPI / PublishItemAPI),
// 通过 dispatchTransport 按 api query 参数分发到不同本地 handler,覆盖各 mtop 调用路径。
// dispatchTransport 保存dispatchTransport,供当前处理流程使用
type dispatchTransport struct {
handlers map[string]http.HandlerFunc
}
// RoundTrip 负责RoundTrip相关处理。
func (d *dispatchTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
// 选 handler:upload 走 stream-upload 域名(无 api query),其它用 api query 区分
api := req.URL.Query().Get("api")
// h、ok 保存h、ok,供当前处理流程使用
h, ok := d.handlers[api]
if !ok {
// upload 的请求路径不含 api=mtop.* ;用 "_upload" key
@@ -40,6 +44,7 @@ func (d *dispatchTransport) RoundTrip(req *http.Request) (*http.Response, error)
}
}
h(rec, req)
// resp 保存resp,供当前处理流程使用
resp := &http.Response{
StatusCode: rec.Code,
Header: rec.Header().Clone(),
@@ -51,6 +56,7 @@ func (d *dispatchTransport) RoundTrip(req *http.Request) (*http.Response, error)
// TestPublishItemValidationFailures: 各参数校验分支。
func TestPublishItemValidationFailures(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
req PublishItemRequest
@@ -63,9 +69,12 @@ func TestPublishItemValidationFailures(t *testing.T) {
{"too many images", PublishItemRequest{Title: "T", PriceCents: 100, Quantity: 1, Images: make([]PublishImage, 10)}, "商品图片最多 9 张"},
{"incomplete preferred category", PublishItemRequest{Title: "T", PriceCents: 100, Quantity: 1, PreferredCategory: &PublishCategory{CatID: "5001"}, Images: []PublishImage{{}}}, "默认类目必须同时包含"},
}
// c 表示当前遍历过程中的c
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
// client 保存client,供当前处理流程使用
client := &ClientImpl{}
// err 保存err,供当前处理流程使用
_, err := client.PublishItem(context.Background(), consignCookies, c.req)
if err == nil || !strings.Contains(err.Error(), c.want) {
t.Fatalf("err=%v want %q", err, c.want)
@@ -76,15 +85,21 @@ func TestPublishItemValidationFailures(t *testing.T) {
// TestPublishItemDescriptionDefaultsToTitle: description 为空时回退为 title。
func TestPublishItemDescriptionDefaultsToTitle(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// gotDesc 保存gotDesc,供当前处理流程使用
var gotDesc string
// publishedData 保存published数据,供当前处理流程使用
var publishedData map[string]any
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
},
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
// body 保存请求体,供当前处理流程使用
body := readBody(r)
// decoded 保存decoded,供当前处理流程使用
var decoded struct {
Data struct {
Desc string `json:"description"`
@@ -102,7 +117,9 @@ func TestPublishItemDescriptionDefaultsToTitle(t *testing.T) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"new-item-1"}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// req 保存req,供当前处理流程使用
req := PublishItemRequest{
Title: "测试商品",
PriceCents: 1000,
@@ -112,6 +129,7 @@ func TestPublishItemDescriptionDefaultsToTitle(t *testing.T) {
Location: &PublishLocation{Area: "X", City: "Y", DivisionID: "1", Longitude: 118.7, Latitude: 31.9, POIID: "p1", POIName: "P", Province: "Z"},
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
}
// res、err 保存res、err,供当前处理流程使用
res, err := client.PublishItem(context.Background(), consignCookies, req)
if err != nil {
t.Fatalf("err=%v", err)
@@ -128,6 +146,7 @@ func TestPublishItemDescriptionDefaultsToTitle(t *testing.T) {
if res.ImageURL != "https://cdn/a.jpg" {
t.Fatalf("ImageURL=%q", res.ImageURL)
}
// addr、ok 保存addr、ok,供当前处理流程使用
addr, ok := publishedData["itemAddrDTO"].(map[string]any)
if !ok || addr["gps"] != "31.9,118.7" {
t.Fatalf("itemAddrDTO=%+v, gps should be latitude,longitude", publishedData["itemAddrDTO"])
@@ -136,19 +155,24 @@ func TestPublishItemDescriptionDefaultsToTitle(t *testing.T) {
// TestPublishItemUploadImageFailure: 图片上传失败导致 PublishItem 失败。
func TestPublishItemUploadImageFailure(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{}}`) // 缺 url
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// req 保存req,供当前处理流程使用
req := PublishItemRequest{
Title: "T",
PriceCents: 1000,
Quantity: 1,
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
}
// err 保存err,供当前处理流程使用
_, err := client.PublishItem(context.Background(), consignCookies, req)
if err == nil || !strings.Contains(err.Error(), "图片上传响应缺少 url") {
t.Fatalf("err=%v", err)
@@ -157,7 +181,9 @@ func TestPublishItemUploadImageFailure(t *testing.T) {
// TestPublishItemRecommendCategoryFailure: 类目推荐失败。
func TestPublishItemRecommendCategoryFailure(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
@@ -166,17 +192,21 @@ func TestPublishItemRecommendCategoryFailure(t *testing.T) {
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXPIRED::令牌过期"]}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// req 保存req,供当前处理流程使用
req := PublishItemRequest{
Title: "T",
PriceCents: 1000,
Quantity: 1,
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
}
// err 保存err,供当前处理流程使用
_, err := client.PublishItem(context.Background(), consignCookies, req)
if err == nil {
t.Fatalf("expected err")
}
// pe 保存pe,供当前处理流程使用
var pe *PublishError
if !errors.As(err, &pe) || pe.Code != PublishErrorTokenExpired {
t.Fatalf("err=%v want PublishErrorTokenExpired", err)
@@ -185,7 +215,9 @@ func TestPublishItemRecommendCategoryFailure(t *testing.T) {
// TestPublishItemRecommendCategoryMissingData: ret 成功但 data 缺 categoryPredictResult。
func TestPublishItemRecommendCategoryMissingDataUsesElectronicMaterials(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
@@ -197,7 +229,9 @@ func TestPublishItemRecommendCategoryMissingDataUsesElectronicMaterials(t *testi
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"fallback-item"}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// req 保存req,供当前处理流程使用
req := PublishItemRequest{
Title: "T",
PriceCents: 1000,
@@ -205,6 +239,7 @@ func TestPublishItemRecommendCategoryMissingDataUsesElectronicMaterials(t *testi
Virtual: true,
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
}
// result、err 保存result、err,供当前处理流程使用
result, err := client.PublishItem(context.Background(), consignCookies, req)
if err != nil {
t.Fatalf("err=%v", err)
@@ -216,7 +251,9 @@ func TestPublishItemRecommendCategoryMissingDataUsesElectronicMaterials(t *testi
// TestPublishItemLocationFailure: 实物发布没有选择发货地。
func TestPublishItemLocationFailure(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
@@ -225,13 +262,16 @@ func TestPublishItemLocationFailure(t *testing.T) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"c1","catName":"类目"}}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// req 保存req,供当前处理流程使用
req := PublishItemRequest{
Title: "T",
PriceCents: 1000,
Quantity: 1,
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
}
// err 保存err,供当前处理流程使用
_, err := client.PublishItem(context.Background(), consignCookies, req)
if err == nil || !strings.Contains(err.Error(), "必须选择发货地") {
t.Fatalf("err=%v", err)
@@ -240,8 +280,11 @@ func TestPublishItemLocationFailure(t *testing.T) {
// TestPublishVirtualItemSkipsLocation 虚拟商品不查询默认地址,也不发送实物地址字段。
func TestPublishVirtualItemSkipsLocation(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// publishedData 保存published数据,供当前处理流程使用
var publishedData map[string]any
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
@@ -254,7 +297,9 @@ func TestPublishVirtualItemSkipsLocation(t *testing.T) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"virtual-item-1"}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// res、err 保存res、err,供当前处理流程使用
res, err := client.PublishItem(context.Background(), consignCookies, PublishItemRequest{
Title: "虚拟商品",
PriceCents: 1000,
@@ -271,15 +316,21 @@ func TestPublishVirtualItemSkipsLocation(t *testing.T) {
if publishedData == nil {
t.Fatal("未解析到发布请求 data")
}
if _, exists := publishedData["itemAddrDTO"]; exists {
if // exists 保存exists,供当前处理流程使用
_, exists := publishedData["itemAddrDTO"]; exists {
t.Fatalf("虚拟商品不应发送 itemAddrDTO: %+v", publishedData["itemAddrDTO"])
}
}
// TestPublishVirtualItemUsesPreferredCategoryWithoutRecommendation 负责Test发布Virtual商品UsesPreferred分类WithoutRecommendation相关处理。
func TestPublishVirtualItemUsesPreferredCategoryWithoutRecommendation(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// publishedData 保存published数据,供当前处理流程使用
var publishedData map[string]any
// recommendCalled 保存recommendCalled,供当前处理流程使用
recommendCalled := false
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
@@ -293,7 +344,9 @@ func TestPublishVirtualItemUsesPreferredCategoryWithoutRecommendation(t *testing
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"fallback-item-1"}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// res、err 保存res、err,供当前处理流程使用
res, err := client.PublishItem(context.Background(), consignCookies, PublishItemRequest{
Title: "虚拟商品",
PriceCents: 1000,
@@ -311,18 +364,24 @@ func TestPublishVirtualItemUsesPreferredCategoryWithoutRecommendation(t *testing
if res.CategoryID != "5001" || res.CategoryName != "虚拟服务" {
t.Fatalf("category result=%+v", res)
}
// category 保存分类,供当前处理流程使用
category, _ := publishedData["itemCatDTO"].(map[string]any)
if category["catId"] != "5001" || category["catName"] != "虚拟服务" || category["channelCatId"] != "6001" || category["tbCatId"] != "7001" {
t.Fatalf("published category=%+v", category)
}
if _, exists := publishedData["itemAddrDTO"]; exists {
if // exists 保存exists,供当前处理流程使用
_, exists := publishedData["itemAddrDTO"]; exists {
t.Fatalf("虚拟商品不应发送 itemAddrDTO: %+v", publishedData["itemAddrDTO"])
}
}
// TestPublishVirtualItemUsesElectronicMaterialsWhenRecommendationIsEmpty 负责Test发布Virtual商品UsesElectronicMaterialsWhenRecommendationIsEmpty相关处理。
func TestPublishVirtualItemUsesElectronicMaterialsWhenRecommendationIsEmpty(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// publishedData 保存published数据,供当前处理流程使用
var publishedData map[string]any
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
@@ -335,7 +394,9 @@ func TestPublishVirtualItemUsesElectronicMaterialsWhenRecommendationIsEmpty(t *t
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"electronic-item-1"}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// res、err 保存res、err,供当前处理流程使用
res, err := client.PublishItem(context.Background(), consignCookies, PublishItemRequest{
Title: "无法识别的虚拟商品",
PriceCents: 1000,
@@ -349,6 +410,7 @@ func TestPublishVirtualItemUsesElectronicMaterialsWhenRecommendationIsEmpty(t *t
if res.CategoryID != "50023914" || res.CategoryName != "电子资料" {
t.Fatalf("category result=%+v", res)
}
// category 保存分类,供当前处理流程使用
category, _ := publishedData["itemCatDTO"].(map[string]any)
if category["channelCatId"] != "202036301" {
t.Fatalf("published category=%+v", category)
@@ -357,7 +419,9 @@ func TestPublishVirtualItemUsesElectronicMaterialsWhenRecommendationIsEmpty(t *t
// TestPublishItemFinalPublishFailure: 发布接口返回 token 过期错误。
func TestPublishItemFinalPublishFailure(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
@@ -369,7 +433,9 @@ func TestPublishItemFinalPublishFailure(t *testing.T) {
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXPIRED::令牌过期"]}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// req 保存req,供当前处理流程使用
req := PublishItemRequest{
Title: "T",
PriceCents: 1000,
@@ -379,10 +445,12 @@ func TestPublishItemFinalPublishFailure(t *testing.T) {
Location: &PublishLocation{Area: "X", City: "Y", DivisionID: "1", Longitude: 118.7, Latitude: 31.9, POIID: "p1", POIName: "P", Province: "Z"},
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
}
// err 保存err,供当前处理流程使用
_, err := client.PublishItem(context.Background(), consignCookies, req)
if err == nil {
t.Fatalf("expected err")
}
// pe 保存pe,供当前处理流程使用
var pe *PublishError
if !errors.As(err, &pe) || pe.Code != PublishErrorTokenExpired {
t.Fatalf("err=%v want PublishErrorTokenExpired", err)
@@ -391,7 +459,9 @@ func TestPublishItemFinalPublishFailure(t *testing.T) {
// TestPublishItemStockPermissionError: 库存权限错误分类。
func TestPublishItemStockPermissionError(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
@@ -403,7 +473,9 @@ func TestPublishItemStockPermissionError(t *testing.T) {
fmt.Fprint(w, `{"ret":["账号没有库存发布权限"]}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// req 保存req,供当前处理流程使用
req := PublishItemRequest{
Title: "T",
PriceCents: 1000,
@@ -411,10 +483,12 @@ func TestPublishItemStockPermissionError(t *testing.T) {
Location: &PublishLocation{Area: "X", City: "Y", DivisionID: "1", Longitude: 118.7, Latitude: 31.9, POIID: "p1", POIName: "P", Province: "Z"},
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
}
// err 保存err,供当前处理流程使用
_, err := client.PublishItem(context.Background(), consignCookies, req)
if err == nil {
t.Fatalf("expected err")
}
// pe 保存pe,供当前处理流程使用
var pe *PublishError
if !errors.As(err, &pe) || pe.Code != PublishErrorStockPermissionMissing {
t.Fatalf("err=%v want PublishErrorStockPermissionMissing", err)
@@ -423,8 +497,11 @@ func TestPublishItemStockPermissionError(t *testing.T) {
// ---- uploadPublishImage 直接测试 ----
// TestUploadPublishImageSuccess 负责TestUpload发布图片Success相关处理。
func TestUploadPublishImageSuccess(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
// 验证 multipart 包含文件
@@ -435,8 +512,11 @@ func TestUploadPublishImageSuccess(t *testing.T) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/x.jpg","pix":"640x480"}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// img 保存img,供当前处理流程使用
img := PublishImage{Filename: "x.png", ContentType: "image/png", Data: png1}
// res、updated、err 保存res、updated、err,供当前处理流程使用
res, updated, err := client.uploadPublishImage(context.Background(), consignCookies, img)
if err != nil {
t.Fatalf("err=%v", err)
@@ -449,57 +529,77 @@ func TestUploadPublishImageSuccess(t *testing.T) {
}
}
// TestUploadPublishImageHTTPError 负责TestUpload发布图片HTTP错误相关处理。
func TestUploadPublishImageHTTPError(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "boom", http.StatusInternalServerError)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// err 保存err,供当前处理流程使用
_, _, err := client.uploadPublishImage(context.Background(), consignCookies, PublishImage{Data: png1})
if err == nil || !strings.Contains(err.Error(), "上传商品图片失败: http=500") {
t.Fatalf("err=%v", err)
}
}
// TestUploadPublishImageParseFailure 负责TestUpload发布图片ParseFailure相关处理。
func TestUploadPublishImageParseFailure(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `not-json{`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// err 保存err,供当前处理流程使用
_, _, err := client.uploadPublishImage(context.Background(), consignCookies, PublishImage{Data: png1})
if err == nil || !strings.Contains(err.Error(), "解析图片上传响应失败") {
t.Fatalf("err=%v", err)
}
}
// TestUploadPublishImageMissingURL 负责TestUpload发布图片MissingURL相关处理。
func TestUploadPublishImageMissingURL(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"pix":"800x600"}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// err 保存err,供当前处理流程使用
_, _, err := client.uploadPublishImage(context.Background(), consignCookies, PublishImage{Data: png1})
if err == nil || !strings.Contains(err.Error(), "图片上传响应缺少 url") {
t.Fatalf("err=%v", err)
}
}
// TestUploadPublishImageFallbackURL 负责TestUpload发布图片FallbackURL相关处理。
func TestUploadPublishImageFallbackURL(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
// object.url 为空,回退到 decoded["url"]
fmt.Fprint(w, `{"object":{},"url":"https://cdn/fallback.jpg"}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// res、err 保存res、err,供当前处理流程使用
res, _, err := client.uploadPublishImage(context.Background(), consignCookies, PublishImage{Data: png1})
if err != nil {
t.Fatalf("err=%v", err)
@@ -509,15 +609,19 @@ func TestUploadPublishImageFallbackURL(t *testing.T) {
}
}
// TestUploadPublishImageDecodeConfigFallback 负责TestUpload发布图片Decode配置Fallback相关处理。
func TestUploadPublishImageDecodeConfigFallback(t *testing.T) {
// pix 字段空,但图片是合法 PNG,走 image.DecodeConfig 回退。
png1 := tinyPNG(t)
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"object":{"url":"https://cdn/y.jpg"}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// res、err 保存res、err,供当前处理流程使用
res, _, err := client.uploadPublishImage(context.Background(), consignCookies, PublishImage{Filename: "y.png", ContentType: "image/png", Data: png1})
if err != nil {
t.Fatalf("err=%v", err)
@@ -530,19 +634,26 @@ func TestUploadPublishImageDecodeConfigFallback(t *testing.T) {
// ---- recommendPublishCategory 直接测试 ----
// TestRecommendPublishCategorySuccess 负责TestRecommend发布分类Success相关处理。
func TestRecommendPublishCategorySuccess(t *testing.T) {
// png1 保存png1,供当前处理流程使用
png1 := tinyPNG(t)
// imgs 保存imgs,供当前处理流程使用
imgs := []uploadedImage{{URL: "https://cdn/a.jpg", Width: 800, Height: 600}}
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"c1","catName":"类目","channelCatId":"cc1","tbCatId":"tc1"}}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// cat、err 保存cat、err,供当前处理流程使用
cat, _, err := client.recommendPublishCategory(context.Background(), consignCookies, "T", "D", imgs)
if err != nil {
t.Fatalf("err=%v", err)
}
// sub 保存sub,供当前处理流程使用
sub := cat["categoryPredictResult"].(map[string]any)
if sub["catId"] != "c1" {
t.Fatalf("cat=%+v", cat)
@@ -550,65 +661,87 @@ func TestRecommendPublishCategorySuccess(t *testing.T) {
_ = png1
}
// TestRecommendPublishCategoryUsesSelectedCategoryCard 负责TestRecommend发布分类UsesSelected分类卡密相关处理。
func TestRecommendPublishCategoryUsesSelectedCategoryCard(t *testing.T) {
// imgs 保存imgs,供当前处理流程使用
imgs := []uploadedImage{{URL: "https://cdn/a.jpg", Width: 800, Height: 600}}
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"propertyId":"-10000","propertyName":"分类","valuesList":[{"catId":"50023914","catName":"电子资料","channelCatId":"202036301","isClicked":"1"}]}}]}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// category、err 保存category、err,供当前处理流程使用
category, _, err := client.recommendPublishCategory(context.Background(), consignCookies, "其他虚拟资料", "其他虚拟资料", imgs)
if err != nil {
t.Fatalf("err=%v", err)
}
// selected 保存selected,供当前处理流程使用
selected := category["categoryPredictResult"].(map[string]any)
if selected["catId"] != "50023914" || selected["catName"] != "电子资料" || selected["channelCatId"] != "202036301" {
t.Fatalf("selected=%+v", selected)
}
if labels := publishLabels(category); len(labels) != 1 {
if // labels 保存labels,供当前处理流程使用
labels := publishLabels(category); len(labels) != 1 {
t.Fatalf("labels=%+v", labels)
}
}
// TestDefaultVirtualPublishCategoryIncludesSelectedCategoryLabel 负责TestDefaultVirtual发布分类IncludesSelected分类Label相关处理。
func TestDefaultVirtualPublishCategoryIncludesSelectedCategoryLabel(t *testing.T) {
// category 保存分类,供当前处理流程使用
category := DefaultVirtualPublishCategory()
if category.CatID != "50023914" || category.CatName != "电子资料" || category.ChannelCatID != "202036301" || category.TBCatID != "" {
t.Fatalf("default category=%+v", category)
}
// fallback 保存fallback,供当前处理流程使用
fallback := fallbackPublishCategory(category)
// labels 保存labels,供当前处理流程使用
labels := publishLabels(fallback)
if len(labels) != 1 {
t.Fatalf("labels=%+v", labels)
}
// label 保存label,供当前处理流程使用
label := labels[0].(map[string]any)
if label["channelCateId"] != "202036301" || label["channelCateName"] != "电子资料" || label["propertyId"] != "-10000" {
t.Fatalf("label=%+v", label)
}
}
// TestRecommendPublishCategoryDataNil 负责TestRecommend发布分类数据Nil相关处理。
func TestRecommendPublishCategoryDataNil(t *testing.T) {
// imgs 保存imgs,供当前处理流程使用
imgs := []uploadedImage{{URL: "u", Width: 1, Height: 1}}
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"]}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// err 保存err,供当前处理流程使用
_, _, err := client.recommendPublishCategory(context.Background(), consignCookies, "T", "D", imgs)
if err == nil || !strings.Contains(err.Error(), "类目推荐响应缺少 data") {
t.Fatalf("err=%v", err)
}
}
// TestRecommendPublishCategoryEmptyCatId 负责TestRecommend发布分类EmptyCat标识相关处理。
func TestRecommendPublishCategoryEmptyCatId(t *testing.T) {
// imgs 保存imgs,供当前处理流程使用
imgs := []uploadedImage{{URL: "u", Width: 1, Height: 1}}
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{}}}`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// err 保存err,供当前处理流程使用
_, _, err := client.recommendPublishCategory(context.Background(), consignCookies, "T", "D", imgs)
if err == nil || !strings.Contains(err.Error(), "未能自动识别商品类目") {
t.Fatalf("err=%v", err)
@@ -617,29 +750,37 @@ func TestRecommendPublishCategoryEmptyCatId(t *testing.T) {
// ---- callMTop / buildMTopQuery ----
// TestCallMTopParseFailure 负责TestCallMTopParseFailure相关处理。
func TestCallMTopParseFailure(t *testing.T) {
// dt 保存dt,供当前处理流程使用
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"some.api": func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `bad{`)
},
}}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
// err 保存err,供当前处理流程使用
_, _, err := client.callMTop(context.Background(), consignCookies, "http://x", "some.api", "1.0", "spm", "spmPre", "log", map[string]any{"k": "v"})
if err == nil || !strings.Contains(err.Error(), "解析 some.api 响应失败") {
t.Fatalf("err=%v", err)
}
}
// TestCallMTopRequestError 负责TestCallMTop请求错误相关处理。
func TestCallMTopRequestError(t *testing.T) {
// 指向不可达地址
client := &ClientImpl{HTTPClient: &http.Client{Transport: &rewriteTransport{base: http.DefaultTransport, target: "http://127.0.0.1:1"}, Timeout: 0}}
// err 保存err,供当前处理流程使用
_, _, err := client.callMTop(context.Background(), consignCookies, "http://127.0.0.1:1", "any.api", "1.0", "s", "p", "l", map[string]any{})
if err == nil || !strings.Contains(err.Error(), "any.api 请求失败") {
t.Fatalf("err=%v", err)
}
}
// TestBuildMTopQuery 负责TestBuildMTop查询相关处理。
func TestBuildMTopQuery(t *testing.T) {
// q 保存q,供当前处理流程使用
q := buildMTopQuery("myapi", "2.0", "T", "SIGN", "spmCnt", "spmPre", "logID")
if !strings.Contains(q, "api=myapi") || !strings.Contains(q, "v=2.0") ||
!strings.Contains(q, "t=T") || !strings.Contains(q, "sign=SIGN") ||
@@ -651,7 +792,9 @@ func TestBuildMTopQuery(t *testing.T) {
// ---- 发布相关纯函数 ----
// TestPublishImagePayload 负责Test发布图片请求载荷相关处理。
func TestPublishImagePayload(t *testing.T) {
// p 保存p,供当前处理流程使用
p := publishImagePayload(uploadedImage{URL: "u", Width: 100, Height: 200}, true)
if p["url"] != "u" || p["widthSize"] != 100 || p["heightSize"] != 200 ||
p["major"] != true || p["type"] != 0 || p["status"] != "done" {
@@ -659,7 +802,9 @@ func TestPublishImagePayload(t *testing.T) {
}
}
// TestPublishLabelsExtractsClicked 负责Test发布LabelsExtractsClicked相关处理。
func TestPublishLabelsExtractsClicked(t *testing.T) {
// category 保存分类,供当前处理流程使用
category := map[string]any{
"cardList": []any{
map[string]any{
@@ -674,10 +819,12 @@ func TestPublishLabelsExtractsClicked(t *testing.T) {
},
},
}
// labels 保存labels,供当前处理流程使用
labels := publishLabels(category)
if len(labels) != 1 {
t.Fatalf("labels=%d want 1", len(labels))
}
// l 保存l,供当前处理流程使用
l := labels[0].(map[string]any)
if l["propertyId"] != "p1" || l["channelCateId"] != "cc" || l["tbCatId"] != "tc" {
t.Fatalf("label=%+v", l)
@@ -687,8 +834,10 @@ func TestPublishLabelsExtractsClicked(t *testing.T) {
}
}
// TestPublishLabelsEmpty 负责Test发布LabelsEmpty相关处理。
func TestPublishLabelsEmpty(t *testing.T) {
if got := publishLabels(map[string]any{}); len(got) != 0 {
if // got 保存got,供当前处理流程使用
got := publishLabels(map[string]any{}); len(got) != 0 {
t.Fatalf("got=%v", got)
}
// cardData 为 nil 的卡片应跳过
@@ -698,49 +847,59 @@ func TestPublishLabelsEmpty(t *testing.T) {
}
}
// TestPublishErrorError 负责Test发布错误错误相关处理。
func TestPublishErrorError(t *testing.T) {
// 有 Ret
e := &PublishError{Ret: []string{"FAIL::a", "FAIL::b"}}
if got := e.Error(); got != "FAIL::a; FAIL::b" {
if // got 保存got,供当前处理流程使用
got := e.Error(); got != "FAIL::a; FAIL::b" {
t.Fatalf("Error()=%q", got)
}
// 无 Ret,有 Body
e = &PublishError{Code: PublishErrorUnknown, Body: "some body"}
if got := e.Error(); got != "some body" {
if // got 保存got,供当前处理流程使用
got := e.Error(); got != "some body" {
t.Fatalf("Error()=%q", got)
}
// 无 Ret 无 Body,回落 Code
e = &PublishError{Code: PublishErrorUnknown}
if got := e.Error(); got != string(PublishErrorUnknown) {
if // got 保存got,供当前处理流程使用
got := e.Error(); got != string(PublishErrorUnknown) {
t.Fatalf("Error()=%q", got)
}
// 长 Body 截断
longBody := strings.Repeat("x", 300)
e = &PublishError{Code: PublishErrorUnknown, Body: longBody}
// got 保存got,供当前处理流程使用
got := e.Error()
if !strings.HasPrefix(got, "xxxxx") || len(got) > 244 {
t.Fatalf("Error() 截断异常 len=%d", len(got))
}
}
// TestClassifyPublishErrorUnknown 负责TestClassify发布错误Unknown相关处理。
func TestClassifyPublishErrorUnknown(t *testing.T) {
// 非已知错误,回落 unknown
err := classifyPublishError([]string{"FAIL_BIZ_RANDOM::随机错误"}, map[string]any{})
// pe 保存pe,供当前处理流程使用
var pe *PublishError
if !errors.As(err, &pe) || pe.Code != PublishErrorUnknown {
t.Fatalf("err=%v want unknown", err)
}
}
// TestClassifyPublishErrorLoginInBody 负责TestClassify发布错误登录In请求体相关处理。
func TestClassifyPublishErrorLoginInBody(t *testing.T) {
// ret 非空,但 body 含 login
err := classifyPublishError([]string{}, map[string]any{"msg": "need login again"})
// pe 保存pe,供当前处理流程使用
var pe *PublishError
if !errors.As(err, &pe) || pe.Code != PublishErrorTokenExpired {
t.Fatalf("err=%v want token expired", err)
}
}
// TestContainsAny 负责TestContainsAny相关处理。
func TestContainsAny(t *testing.T) {
if !containsAny("has stock permission", []string{"stock", "permission"}) {
t.Fatalf("want true")
@@ -753,8 +912,11 @@ func TestContainsAny(t *testing.T) {
}
}
// TestRetFromDecoded 负责TestRetFromDecoded相关处理。
func TestRetFromDecoded(t *testing.T) {
// decoded 保存decoded,供当前处理流程使用
decoded := map[string]any{"ret": []any{"SUCCESS::a", "FAIL::b", 123}}
// got 保存got,供当前处理流程使用
got := retFromDecoded(decoded)
if len(got) != 3 || got[0] != "SUCCESS::a" || got[1] != "FAIL::b" || got[2] != "123" {
t.Fatalf("got=%v", got)
@@ -765,30 +927,38 @@ func TestRetFromDecoded(t *testing.T) {
}
}
// TestMapFromAny 负责TestMapFromAny相关处理。
func TestMapFromAny(t *testing.T) {
if m := mapFromAny(map[string]any{"k": "v"}); m == nil || m["k"] != "v" {
if // m 保存m,供当前处理流程使用
m := mapFromAny(map[string]any{"k": "v"}); m == nil || m["k"] != "v" {
t.Fatalf("m=%v", m)
}
if m := mapFromAny("not-map"); m != nil {
if // m 保存m,供当前处理流程使用
m := mapFromAny("not-map"); m != nil {
t.Fatalf("m=%v want nil", m)
}
if m := mapFromAny(nil); m != nil {
if // m 保存m,供当前处理流程使用
m := mapFromAny(nil); m != nil {
t.Fatalf("m=%v want nil", m)
}
}
// TestFindStringDeepNested 负责TestFindStringDeepNested相关处理。
func TestFindStringDeepNested(t *testing.T) {
// v 保存v,供当前处理流程使用
v := map[string]any{
"a": []any{
map[string]any{"b": map[string]any{"item_id": "deep-id"}},
},
}
if got := findStringDeep(v, "itemId", "item_id", "id"); got != "deep-id" {
if // got 保存got,供当前处理流程使用
got := findStringDeep(v, "itemId", "item_id", "id"); got != "deep-id" {
t.Fatalf("got=%q", got)
}
// 多 key 命中第一个非空
v = map[string]any{"id": "first"}
if got := findStringDeep(v, "itemId", "item_id", "id"); got != "first" {
if // got 保存got,供当前处理流程使用
got := findStringDeep(v, "itemId", "item_id", "id"); got != "first" {
t.Fatalf("got=%q", got)
}
// 找不到
@@ -797,29 +967,38 @@ func TestFindStringDeepNested(t *testing.T) {
}
}
// TestEscapeMultipartFilename 负责TestEscapeMultipartFilename相关处理。
func TestEscapeMultipartFilename(t *testing.T) {
if got := escapeMultipartFilename(`a"b\c`); got != `a\"b\\c` {
if // got 保存got,供当前处理流程使用
got := escapeMultipartFilename(`a"b\c`); got != `a\"b\\c` {
t.Fatalf("got=%q", got)
}
if got := escapeMultipartFilename("normal"); got != "normal" {
if // got 保存got,供当前处理流程使用
got := escapeMultipartFilename("normal"); got != "normal" {
t.Fatalf("got=%q", got)
}
}
// ---- helpers ----
// tinyPNG 负责tinyPNG相关处理。
func tinyPNG(t *testing.T) []byte {
t.Helper()
// img 保存img,供当前处理流程使用
img := image.NewRGBA(image.Rect(0, 0, 1, 1))
img.Set(0, 0, color.RGBA{R: 255, G: 0, B: 0, A: 255})
// buf 保存buf,供当前处理流程使用
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
if // err 保存err,供当前处理流程使用
err := png.Encode(&buf, img); err != nil {
t.Fatalf("png encode: %v", err)
}
return buf.Bytes()
}
// readBody 负责read请求体相关处理。
func readBody(r *http.Request) string {
// buf 保存buf,供当前处理流程使用
buf := make([]byte, r.ContentLength)
r.Body.Read(buf)
return string(buf)
@@ -830,13 +1009,17 @@ func parseDataURL(body string) (map[string]any, bool) {
if !strings.HasPrefix(body, "data=") {
return nil, false
}
// enc 保存enc,供当前处理流程使用
enc := strings.TrimPrefix(body, "data=")
// dec、err 保存dec、err,供当前处理流程使用
dec, err := url.QueryUnescape(enc)
if err != nil {
return nil, false
}
// m 保存m,供当前处理流程使用
var m map[string]any
if err := json.Unmarshal([]byte(dec), &m); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(dec), &m); err != nil {
return nil, false
}
return m, true
+19 -6
View File
@@ -5,39 +5,52 @@ import (
"testing"
)
// TestPublishPayloadBuilders 负责Test发布请求载荷Builders相关处理。
func TestPublishPayloadBuilders(t *testing.T) {
// req 保存req,供当前处理流程使用
req := PublishItemRequest{PriceCents: 1234, OriginalPriceCents: 2000, PostageMode: "fixed", PostageCents: 800}
// price 保存price,供当前处理流程使用
price := publishPriceDTO(req)
if price["priceInCent"] != "1234" || price["origPriceInCent"] != "2000" {
t.Fatalf("publishPriceDTO = %#v", price)
}
// postage 保存postage,供当前处理流程使用
postage := postageDTO(req)
if postage["postPriceInCent"] != "800" || postage["templateId"] != "0" {
t.Fatalf("postageDTO = %#v", postage)
}
if got := postageDTO(PublishItemRequest{PostageMode: "free"}); got["canFreeShipping"] != true {
if // got 保存got,供当前处理流程使用
got := postageDTO(PublishItemRequest{PostageMode: "free"}); got["canFreeShipping"] != true {
t.Fatalf("free postage = %#v", got)
}
if got := postageDTO(PublishItemRequest{PostageMode: "distance"}); got["templateId"] != "-100" {
if // got 保存got,供当前处理流程使用
got := postageDTO(PublishItemRequest{PostageMode: "distance"}); got["templateId"] != "-100" {
t.Fatalf("distance postage = %#v", got)
}
}
// TestPublishParsingAndErrors 负责Test发布ParsingAnd错误列表相关处理。
func TestPublishParsingAndErrors(t *testing.T) {
if w, h := parsePix("800x600"); w != 800 || h != 600 {
if // w、h 保存w、h,供当前处理流程使用
w, h := parsePix("800x600"); w != 800 || h != 600 {
t.Fatalf("parsePix = %d x %d", w, h)
}
if w, h := parsePix("bad"); w != 0 || h != 0 {
if // w、h 保存w、h,供当前处理流程使用
w, h := parsePix("bad"); w != 0 || h != 0 {
t.Fatalf("invalid parsePix = %d x %d", w, h)
}
if got := centsText(1234); got != "12.34" {
if // got 保存got,供当前处理流程使用
got := centsText(1234); got != "12.34" {
t.Fatalf("centsText = %q", got)
}
if got := findStringDeep(map[string]any{"outer": map[string]any{"itemId": "42"}}, "itemId"); got != "42" {
if // got 保存got,供当前处理流程使用
got := findStringDeep(map[string]any{"outer": map[string]any{"itemId": "42"}}, "itemId"); got != "42" {
t.Fatalf("findStringDeep = %q", got)
}
// err 保存err,供当前处理流程使用
err := classifyPublishError([]string{"FAIL_SYS_TOKEN_EXPIRED::令牌过期"}, map[string]any{})
// publishErr 保存发布Err,供当前处理流程使用
var publishErr *PublishError
if !errors.As(err, &publishErr) || publishErr.Code != PublishErrorTokenExpired {
t.Fatalf("token error = %#v", err)
+48 -3
View File
@@ -14,6 +14,7 @@ import (
"xianyu-go/internal/xianyu/protocol"
)
// soldOrdersReferer 保存sold订单列表Referer,供当前处理流程使用
const soldOrdersReferer = "https://seller.goofish.com/?site=COMMONPRO#/seller-trade/order-manage"
// SoldOrderFetcher 是订单同步使用的可选能力,不扩展基础 Client 接口,避免影响其他调用方的 mock。
@@ -48,6 +49,7 @@ var _ SoldOrderFetcher = (*ClientImpl)(nil)
// FetchSoldOrdersPage 获取卖家已售订单。该调用不主动刷新 token;当 ctx
// 携带 CookieSession 时会像浏览器一样吸收响应 Cookie。
// FetchSoldOrdersPage 负责FetchSold订单列表页码相关处理。
func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pageNumber, pageSize int) (*SoldOrdersPage, error) {
if pageNumber < 1 {
pageNumber = 1
@@ -55,15 +57,19 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa
if pageSize < 1 || pageSize > 100 {
pageSize = 30
}
// endpoint 保存endpoint,供当前处理流程使用
endpoint := c.SoldOrdersURL
if endpoint == "" {
endpoint = SoldOrdersAPI
}
// signingCookies、requestCookies 保存signingCookies、requestCookies,供当前处理流程使用
signingCookies, requestCookies := mtopRequestCookies(ctx, cookies, soldOrdersReferer, endpoint)
// token 保存令牌,供当前处理流程使用
token := protocol.SignToken(signingCookies)
if token == "" {
return nil, fmt.Errorf("cookie 缺少 _m_h5_tk,无法获取订单列表")
}
// payload 保存请求载荷,供当前处理流程使用
payload := map[string]any{
"pageNumber": pageNumber,
"rowsPerPage": pageSize,
@@ -71,13 +77,18 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa
"queryCode": "ALL",
"orderSearchParam": "{}",
}
// rawPayload、err 保存原始Payload、err,供当前处理流程使用
rawPayload, err := json.Marshal(payload)
if err != nil {
return nil, err
}
// dataVal 保存数据Val,供当前处理流程使用
dataVal := string(rawPayload)
// timestamp 保存timestamp,供当前处理流程使用
timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
// sign 保存sign,供当前处理流程使用
sign := protocol.GenerateSign(timestamp, token, dataVal)
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildSoldOrdersQuery(timestamp, sign), strings.NewReader("data="+url.QueryEscape(dataVal)))
if err != nil {
return nil, err
@@ -88,24 +99,29 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa
req.Header.Set("Referer", soldOrdersReferer)
req.Header.Set("idle_site_biz_code", "COMMONPRO")
// hc 保存hc,供当前处理流程使用
hc := c.httpClient()
// resp、err 保存resp、err,供当前处理流程使用
resp, err := hc.Do(req)
if err != nil {
return nil, fmt.Errorf("订单列表请求失败: %w", err)
}
defer resp.Body.Close()
absorbMTopResponseCookies(ctx, cookies, resp)
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readMTopBody(resp)
if err != nil {
return nil, err
}
// decoded 保存decoded,供当前处理流程使用
var decoded struct {
Ret []string `json:"ret"`
Data struct {
Module map[string]any `json:"module"`
} `json:"data"`
}
if err := json.Unmarshal(raw, &decoded); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &decoded); err != nil {
return nil, fmt.Errorf("解析订单列表响应失败: %w (body=%s)", err, truncate(string(raw), 300))
}
if isSessionExpiredRet(decoded.Ret) {
@@ -114,10 +130,15 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa
if !hasMTopSuccess(decoded.Ret) {
return nil, fmt.Errorf("订单列表接口返回非成功: ret=%v", decoded.Ret)
}
// module 保存module,供当前处理流程使用
module := decoded.Data.Module
// rawItems 保存原始商品列表,供当前处理流程使用
rawItems, _ := module["items"].([]any)
// items 保存商品列表,供当前处理流程使用
items := make([]SoldOrder, 0, len(rawItems))
// rawItem 表示当前遍历过程中的原始商品
for _, rawItem := range rawItems {
// item、ok 保存item、ok,供当前处理流程使用
item, ok := parseSoldOrder(rawItem)
if ok {
items = append(items, item)
@@ -130,7 +151,9 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa
}, nil
}
// buildSoldOrdersQuery 负责buildSold订单列表查询相关处理。
func buildSoldOrdersQuery(timestamp, sign string) string {
// values 保存values,供当前处理流程使用
values := url.Values{
"jsv": {"2.7.2"},
"appKey": {protocol.SignAppKey},
@@ -149,29 +172,44 @@ func buildSoldOrdersQuery(timestamp, sign string) string {
return values.Encode()
}
// parseSoldOrder 负责parseSold订单相关处理。
func parseSoldOrder(raw any) (SoldOrder, bool) {
// item、ok 保存item、ok,供当前处理流程使用
item, ok := raw.(map[string]any)
if !ok {
return SoldOrder{}, false
}
// common 保存common,供当前处理流程使用
common, _ := item["commonData"].(map[string]any)
// buyer 保存买家,供当前处理流程使用
buyer, _ := item["buyerInfoVO"].(map[string]any)
// price 保存price,供当前处理流程使用
price, _ := item["priceVO"].(map[string]any)
// rights 保存rights,供当前处理流程使用
rights, _ := item["rightVO"].(map[string]any)
// orderID 保存订单ID,供当前处理流程使用
orderID := strings.TrimSpace(mtopString(common["orderId"]))
if orderID == "" {
return SoldOrder{}, false
}
// rawStatus 保存原始状态,供当前处理流程使用
rawStatus := strings.TrimSpace(mtopString(common["orderStatus"]))
// status 保存状态,供当前处理流程使用
status := normalizeSoldOrderStatus(rawStatus, mtopBool(common["inRefund"]))
// amount 保存amount,供当前处理流程使用
amount := firstMTopString(price, "totalPrice", "confirmFee", "auctionPrice")
// quantity 保存quantity,供当前处理流程使用
quantity := firstMTopString(price, "buyNum", "quantity")
if quantity == "" || quantity == "0" {
quantity = "1"
}
// isBargain 保存isBargain,供当前处理流程使用
isBargain := false
// buttons 保存buttons,供当前处理流程使用
buttons, _ := rights["btnList"].([]any)
// rawButton 表示当前遍历过程中的原始Button
for _, rawButton := range buttons {
// button 保存button,供当前处理流程使用
button, _ := rawButton.(map[string]any)
if strings.EqualFold(mtopString(button["tradeAction"]), "SKIP_PIN") {
isBargain = true
@@ -194,6 +232,7 @@ func parseSoldOrder(raw any) (SoldOrder, bool) {
}, true
}
// normalizeSoldOrderStatus 负责normalizeSold订单状态相关处理。
func normalizeSoldOrderStatus(raw string, inRefund bool) string {
if inRefund {
return "refunding"
@@ -216,17 +255,22 @@ func normalizeSoldOrderStatus(raw string, inRefund bool) string {
}
}
// firstMTopString 负责firstMTopString相关处理。
func firstMTopString(values map[string]any, keys ...string) string {
// key 表示当前遍历过程中的key
for _, key := range keys {
if value := strings.TrimSpace(mtopString(values[key])); value != "" {
if // value 保存值,供当前处理流程使用
value := strings.TrimSpace(mtopString(values[key])); value != "" {
return value
}
}
return ""
}
// mtopBool 负责mtopBool相关处理。
func mtopBool(value any) bool {
switch typed := value.(type) {
switch // typed 保存typed,供当前处理流程使用
typed := value.(type) {
case bool:
return typed
case float64:
@@ -234,6 +278,7 @@ func mtopBool(value any) bool {
case int:
return typed != 0
case string:
// normalized 保存normalized,供当前处理流程使用
normalized := strings.ToLower(strings.TrimSpace(typed))
return normalized == "true" || normalized == "1" || normalized == "yes"
default:
+24 -5
View File
@@ -11,7 +11,9 @@ import (
"testing"
)
// TestFetchSoldOrdersPageRequestAndParse 负责TestFetchSold订单列表页码请求AndParse相关处理。
func TestFetchSoldOrdersPageRequestAndParse(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("api") != "mtop.taobao.idle.trade.merchant.sold.get" || r.URL.Query().Get("sign") == "" {
t.Errorf("query=%s", r.URL.RawQuery)
@@ -19,10 +21,14 @@ func TestFetchSoldOrdersPageRequestAndParse(t *testing.T) {
if r.Header.Get("Origin") != "https://seller.goofish.com" || r.Header.Get("idle_site_biz_code") != "COMMONPRO" {
t.Errorf("headers=%v", r.Header)
}
// rawBody 保存原始请求体,供当前处理流程使用
rawBody, _ := io.ReadAll(r.Body)
// form 保存表单,供当前处理流程使用
form, _ := url.ParseQuery(string(rawBody))
// payload 保存请求载荷,供当前处理流程使用
var payload map[string]any
if err := json.Unmarshal([]byte(form.Get("data")), &payload); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(form.Get("data")), &payload); err != nil {
t.Fatal(err)
}
if payload["pageNumber"] != float64(2) || payload["rowsPerPage"] != float64(30) || payload["queryCode"] != "ALL" {
@@ -35,7 +41,9 @@ func TestFetchSoldOrdersPageRequestAndParse(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), SoldOrdersURL: server.URL}
// page、err 保存page、err,供当前处理流程使用
page, err := client.FetchSoldOrdersPage(context.Background(), "unb=1; _m_h5_tk=token_1;", 2, 30)
if err != nil {
t.Fatal(err)
@@ -43,6 +51,7 @@ func TestFetchSoldOrdersPageRequestAndParse(t *testing.T) {
if !page.NextPage || page.TotalCount != 31 || len(page.Items) != 1 {
t.Fatalf("page=%+v", page)
}
// item 保存商品,供当前处理流程使用
item := page.Items[0]
if item.OrderID != "order-1" || item.ItemID != "item-1" || item.OrderStatus != "pending_ship" ||
item.Quantity != "3" || item.Amount != "29.90" || !item.IsBargain || item.ReceiverName != "李四" {
@@ -50,32 +59,42 @@ func TestFetchSoldOrdersPageRequestAndParse(t *testing.T) {
}
}
// TestFetchSoldOrdersPageRejectsMissingTokenAndFailure 负责TestFetchSold订单列表页码RejectsMissing令牌AndFailure相关处理。
func TestFetchSoldOrdersPageRejectsMissingTokenAndFailure(t *testing.T) {
// client 保存client,供当前处理流程使用
client := &ClientImpl{}
if _, err := client.FetchSoldOrdersPage(context.Background(), "unb=1", 1, 30); err == nil || !strings.Contains(err.Error(), "_m_h5_tk") {
if // err 保存err,供当前处理流程使用
_, err := client.FetchSoldOrdersPage(context.Background(), "unb=1", 1, 30); err == nil || !strings.Contains(err.Error(), "_m_h5_tk") {
t.Fatalf("err=%v", err)
}
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = io.WriteString(w, `{"ret":["FAIL_BIZ_ERROR::失败"]}`)
}))
defer server.Close()
client = &ClientImpl{HTTPClient: server.Client(), SoldOrdersURL: server.URL}
if _, err := client.FetchSoldOrdersPage(context.Background(), "_m_h5_tk=token_1", 1, 30); err == nil || !strings.Contains(err.Error(), "非成功") {
if // err 保存err,供当前处理流程使用
_, err := client.FetchSoldOrdersPage(context.Background(), "_m_h5_tk=token_1", 1, 30); err == nil || !strings.Contains(err.Error(), "非成功") {
t.Fatalf("err=%v", err)
}
}
// TestNormalizeSoldOrderStatus 负责TestNormalizeSold订单状态相关处理。
func TestNormalizeSoldOrderStatus(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]string{
"待付款": "processing", "待发货": "pending_ship", "已发货": "shipped",
"交易成功": "completed", "退款成功": "cancelled", "退款中": "refunding",
}
// input、want 表示当前遍历过程中的input、want
for input, want := range cases {
if got := normalizeSoldOrderStatus(input, false); got != want {
if // got 保存got,供当前处理流程使用
got := normalizeSoldOrderStatus(input, false); got != want {
t.Fatalf("input=%s got=%s want=%s", input, got, want)
}
}
if got := normalizeSoldOrderStatus("待发货", true); got != "refunding" {
if // got 保存got,供当前处理流程使用
got := normalizeSoldOrderStatus("待发货", true); got != "refunding" {
t.Fatalf("inRefund got=%s", got)
}
}
+86 -9
View File
@@ -17,11 +17,13 @@ import (
"xianyu-go/internal/xianyu/protocol"
)
// officialMTopMaxAttempts 保存officialMTopMax尝试次数,供当前处理流程使用
const officialMTopMaxAttempts = 5
// RefreshToken 调用 mtop.taobao.idlemessage.pc.login.token 获取 accessToken。
// 遇到 mtop 签名 token 过期时,按官网 lib-mtop 2.7.3 的 H5 流程最多执行
// 5 次请求(含首次),每次先吸收 Go Cookie Jar 再重新签名。
// RefreshToken 刷新令牌。
func (c *ClientImpl) RefreshToken(cookiesStr string) (*RefreshResult, error) {
return c.RefreshTokenContext(context.Background(), cookiesStr)
}
@@ -35,22 +37,31 @@ func (c *ClientImpl) RefreshTokenContext(ctx context.Context, cookiesStr string)
// 闲鱼 IM token 和 WS /reg 的 did 是绑定校验关系:token 请求里的 deviceId
// 必须与 /reg.headers.did 完全一致,否则 /reg 会返回
// "device id or appkey is not equal"。
// RefreshTokenWithDeviceIDContext 刷新令牌WithDeviceID上下文。
func (c *ClientImpl) RefreshTokenWithDeviceIDContext(ctx context.Context, cookiesStr, deviceID string) (*RefreshResult, error) {
return c.RefreshTokenWithCredentialContext(ctx, cookiesStr, deviceID, nil)
}
// RefreshTokenWithCredentialContext 使用完整 Cookie 快照执行纯 Go HTTP 请求,
// 避免把不同 Domain/Path 的同名 Cookie 压成一个值。
// RefreshTokenWithCredentialContext 刷新令牌WithCredential上下文。
func (c *ClientImpl) RefreshTokenWithCredentialContext(ctx context.Context, cookiesStr, deviceID string, cookieSnapshot []cookierefresh.BrowserCookie) (*RefreshResult, error) {
// currentCookies 保存currentCookies,供当前处理流程使用
currentCookies := cookiesStr
// currentSnapshot 保存currentSnapshot,供当前处理流程使用
currentSnapshot := cookierefresh.NormalizeSnapshot(cookieSnapshot)
// currentSnapshotComplete 保存currentSnapshotComplete,供当前处理流程使用
currentSnapshotComplete := cookieSnapshot != nil
// cookieStateChanged 保存登录凭证状态Changed,供当前处理流程使用
cookieStateChanged := false
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
currentCookies, currentSnapshot, cookieStateChanged = session.State()
currentSnapshotComplete = currentSnapshot != nil
}
for attempt := 0; attempt < officialMTopMaxAttempts; attempt++ {
for // attempt 保存尝试次数,供当前处理流程使用
attempt := 0; attempt < officialMTopMaxAttempts; attempt++ {
// accessToken、expireAt、ret、updatedCookies、snapshot、verificationURL、status、snapshotComplete、attemptChanged、err 保存accessToken、expireAt、ret、updatedCookies、snapshot、verificationURL、status、snapshotComplete、attemptChanged、err,供当前处理流程使用
accessToken, expireAt, ret, updatedCookies, snapshot, verificationURL, status, snapshotComplete, attemptChanged, err := c.refreshTokenOnce(ctx, currentCookies, deviceID, currentSnapshot)
if updatedCookies != "" || snapshot != nil || attemptChanged {
currentCookies = updatedCookies
@@ -69,6 +80,7 @@ func (c *ClientImpl) RefreshTokenWithCredentialContext(ctx context.Context, cook
return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), err
}
if accessToken != "" {
// result 保存结果,供当前处理流程使用
result := refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged)
result.AccessToken = accessToken
result.AccessTokenExpireAt = expireAt
@@ -84,14 +96,17 @@ func (c *ClientImpl) RefreshTokenWithCredentialContext(ctx context.Context, cook
return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), fmt.Errorf("token API 返回非成功: ret=%v (status=%d)", ret, status)
}
if attempt == officialMTopMaxAttempts-1 {
// snapshotForClear 保存snapshotForClear,供当前处理流程使用
var snapshotForClear []cookierefresh.BrowserCookie
if currentSnapshotComplete {
snapshotForClear = currentSnapshot
}
// cleanedCookies、cleanedSnapshot 保存cleanedCookies、cleanedSnapshot,供当前处理流程使用
cleanedCookies, cleanedSnapshot := clearOfficialMTopTokenCookies(currentCookies, snapshotForClear)
cookieStateChanged = cookieStateChanged || cleanedCookies != currentCookies || !slices.Equal(cleanedSnapshot, currentSnapshot)
currentCookies, currentSnapshot = cleanedCookies, cleanedSnapshot
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
if currentSnapshot != nil {
session.replace(currentSnapshot)
} else {
@@ -104,6 +119,7 @@ func (c *ClientImpl) RefreshTokenWithCredentialContext(ctx context.Context, cook
return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), fmt.Errorf("token API 登录凭证已失效")
}
// refreshResult 负责refresh结果相关处理。
func refreshResult(updatedCookies string, snapshot []cookierefresh.BrowserCookie, complete, changed bool) *RefreshResult {
if !complete {
snapshot = nil
@@ -116,8 +132,11 @@ func refreshResult(updatedCookies string, snapshot []cookierefresh.BrowserCookie
}
}
// refreshResultFromContext 负责refresh结果From上下文相关处理。
func refreshResultFromContext(ctx context.Context, updatedCookies string, snapshot []cookierefresh.BrowserCookie, complete, changed bool) *RefreshResult {
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
// sessionChanged 保存会话Changed,供当前处理流程使用
var sessionChanged bool
updatedCookies, snapshot, sessionChanged = session.State()
complete = snapshot != nil
@@ -128,13 +147,18 @@ func refreshResultFromContext(ctx context.Context, updatedCookies string, snapsh
// RequestFreshCaptchaURLContext 重新请求 token API,用于浏览器风控验证前获取新鲜验证链接。
// 如果风控已解除并直接返回 accessToken,则 TokenOK=true。
// RequestFreshCaptchaURLContext 负责请求FreshCaptchaURL上下文相关处理。
func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesStr, deviceID string) (*FreshCaptchaResult, error) {
// snapshot 保存snapshot,供当前处理流程使用
var snapshot []cookierefresh.BrowserCookie
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
cookiesStr, snapshot, _ = session.State()
}
// accessToken、expireAt、ret、updatedCookies、verificationURL、err 保存accessToken、expireAt、ret、updatedCookies、verificationURL、err,供当前处理流程使用
accessToken, expireAt, ret, updatedCookies, _, verificationURL, _, _, _, err := c.refreshTokenOnce(ctx, cookiesStr, deviceID, snapshot)
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
updatedCookies, _, _ = session.State()
}
if err != nil {
@@ -156,17 +180,22 @@ func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesS
}, nil
}
// refreshTokenOnce 负责refresh令牌Once相关处理。
func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string, cookieSnapshot []cookierefresh.BrowserCookie) (string, int64, []string, string, []cookierefresh.BrowserCookie, string, int, bool, bool, error) {
// hc 保存hc,供当前处理流程使用
hc := c.httpClientWithTimeout(20 * time.Second)
// tokenURL 保存令牌URL,供当前处理流程使用
tokenURL := c.TokenURL
if tokenURL == "" {
tokenURL = TokenAPI
}
// signingCookies、requestCookies 保存signingCookies、requestCookies,供当前处理流程使用
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, mtopDocumentURL, tokenURL)
if cookieSessionFromContext(ctx) == nil && cookieSnapshot != nil {
signingCookies, requestCookies = snapshotRequestCookies(cookieSnapshot, cookiesStr, tokenURL)
}
// myid 保存myid,供当前处理流程使用
myid := protocol.TransCookies(signingCookies)["unb"]
if myid == "" {
return "", 0, nil, cookiesStr, nil, "", 0, false, false, fmt.Errorf("cookie 缺少 unb 字段,无法生成 deviceId")
@@ -174,29 +203,42 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID
if strings.TrimSpace(deviceID) == "" {
deviceID = protocol.GenerateDeviceID(myid)
}
// token 保存令牌,供当前处理流程使用
token := protocol.SignToken(signingCookies)
// t 保存t,供当前处理流程使用
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
// dataVal 保存数据Val,供当前处理流程使用
dataVal := `{"appKey":"` + RegAppKey + `","deviceId":"` + deviceID + `"}`
// 签名不覆盖 query,因此 query 的编码细节不影响验签。
query := buildTokenQuery(t, protocol.GenerateSign(t, token, dataVal))
// body 保存请求体,供当前处理流程使用
body := "data=" + url.QueryEscape(dataVal)
// requestURL 保存请求URL,供当前处理流程使用
requestURL := tokenURL + "?" + query
// raw 保存原始,供当前处理流程使用
var raw []byte
// status 保存状态,供当前处理流程使用
var status int
// updated 保存updated,供当前处理流程使用
var updated string
// snapshot 保存snapshot,供当前处理流程使用
var snapshot []cookierefresh.BrowserCookie
// snapshotComplete 保存snapshotComplete,供当前处理流程使用
snapshotComplete := false
// stateChanged 保存状态Changed,供当前处理流程使用
stateChanged := false
// req、reqErr 保存req、reqErr,供当前处理流程使用
req, reqErr := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, strings.NewReader(body))
if reqErr != nil {
return "", 0, nil, cookiesStr, nil, "", 0, false, false, reqErr
}
setCommonHeaders(req, requestCookies)
req.Header.Set("Referer", "https://www.goofish.com/im")
// resp、reqErr 保存resp、reqErr,供当前处理流程使用
resp, reqErr := hc.Do(req)
if reqErr != nil {
return "", 0, nil, cookiesStr, nil, "", 0, false, false, fmt.Errorf("token API 请求失败: %w", reqErr)
@@ -204,8 +246,10 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID
defer resp.Body.Close()
// Go CookieSession 在读取响应体前应用 Set-Cookie,避免解析失败时丢掉
// 服务端已经下发的凭证轮换或删除。
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
updated = absorbMTopResponseCookies(ctx, cookiesStr, resp)
// sessionChanged 保存会话Changed,供当前处理流程使用
var sessionChanged bool
_, snapshot, sessionChanged = session.State()
stateChanged = sessionChanged
@@ -225,6 +269,7 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID
}
status = resp.StatusCode
// res 保存响应,供当前处理流程使用
var res struct {
Ret []string `json:"ret"`
Data struct {
@@ -233,11 +278,14 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID
URL string `json:"url"`
} `json:"data"`
}
if err := json.Unmarshal(raw, &res); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &res); err != nil {
return "", 0, nil, updated, snapshot, "", status, snapshotComplete, stateChanged, fmt.Errorf("解析 token 响应失败: %w (body=%s)", err, truncate(string(raw), 300))
}
// ok 保存ok,供当前处理流程使用
ok := false
// r 表示当前遍历过程中的r
for _, r := range res.Ret {
if strings.Contains(r, "SUCCESS") {
ok = true
@@ -253,22 +301,29 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID
return res.Data.AccessToken, parseAccessTokenExpireAt(res.Data.AccessTokenExpiredTime, time.Now()), res.Ret, updated, snapshot, "", status, snapshotComplete, stateChanged, nil
}
// snapshotRequestCookies 负责snapshot请求Cookies相关处理。
func snapshotRequestCookies(snapshot []cookierefresh.BrowserCookie, fallback, requestURL string) (string, string) {
if snapshot == nil {
return fallback, fallback
}
// documentCookies 保存documentCookies,供当前处理流程使用
documentCookies := make([]cookierefresh.BrowserCookie, 0, len(snapshot))
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range snapshot {
if !cookie.HTTPOnly {
documentCookies = append(documentCookies, cookie)
}
}
// signing 保存signing,供当前处理流程使用
signing, _ := cookierefresh.ScopedCookieHeaderForRequest(documentCookies, mtopDocumentURL, goofishTopSite, time.Now())
// requestCookies 保存请求Cookies,供当前处理流程使用
requestCookies, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, goofishTopSite, time.Now())
return signing, requestCookies
}
// isOfficialTokenRetryRet 负责isOfficial令牌重试Ret相关处理。
func isOfficialTokenRetryRet(ret []string) bool {
// value 表示当前遍历过程中的值
for _, value := range ret {
if strings.Contains(value, "TOKEN_EMPTY") || strings.Contains(value, "TOKEN_EXOIRED") {
return true
@@ -277,21 +332,29 @@ func isOfficialTokenRetryRet(ret []string) bool {
return false
}
// clearOfficialMTopTokenCookies 负责clearOfficialMTop令牌Cookies相关处理。
func clearOfficialMTopTokenCookies(cookieStr string, snapshot []cookierefresh.BrowserCookie) (string, []cookierefresh.BrowserCookie) {
// values 保存values,供当前处理流程使用
values := protocol.TransCookies(cookieStr)
// name 表示当前遍历过程中的名称
for _, name := range []string{"_m_h5_c", "_m_h5_tk", "_m_h5_tk_enc"} {
delete(values, name)
}
// cleaned 保存cleaned,供当前处理流程使用
var cleaned []cookierefresh.BrowserCookie
if snapshot != nil {
cleaned = make([]cookierefresh.BrowserCookie, 0, len(snapshot))
}
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range snapshot {
// domain 保存domain,供当前处理流程使用
domain := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(cookie.Domain), "."))
// cookiePath 保存登录凭证路径,供当前处理流程使用
cookiePath := cookie.Path
if cookiePath == "" {
cookiePath = "/"
}
// remove 保存remove,供当前处理流程使用
remove := cookiePath == "/" && domain == "goofish.com" &&
(cookie.Name == "_m_h5_c" || cookie.Name == "_m_h5_tk" || cookie.Name == "_m_h5_tk_enc")
remove = remove || (cookiePath == "/" && domain == "m.goofish.com" &&
@@ -304,33 +367,43 @@ func clearOfficialMTopTokenCookies(cookieStr string, snapshot []cookierefresh.Br
if snapshot != nil {
// 完整 Jar 存在时,扁平兼容值也必须重新按 /im scope 生成;不能用
// name map 把仍有效的 Path=/im 同名凭证一并抹掉。
// canonical 保存canonical,供当前处理流程使用
canonical, _ := cookierefresh.ScopedCookieHeaderForRequest(cleaned, mtopDocumentURL, goofishTopSite, time.Now())
return canonical, cleaned
}
return marshalTokenCookies(values), cleaned
}
// marshalTokenCookies 负责marshal令牌Cookies相关处理。
func marshalTokenCookies(cookies map[string]string) string {
// keys 保存keys,供当前处理流程使用
keys := make([]string, 0, len(cookies))
// key 表示当前遍历过程中的key
for key := range cookies {
keys = append(keys, key)
}
sort.Strings(keys)
// parts 保存parts,供当前处理流程使用
parts := make([]string, 0, len(keys))
// key 表示当前遍历过程中的key
for _, key := range keys {
parts = append(parts, key+"="+cookies[key])
}
return strings.Join(parts, "; ")
}
// parseAccessTokenExpireAt 负责parseAccess令牌ExpireAt相关处理。
func parseAccessTokenExpireAt(raw json.RawMessage, now time.Time) int64 {
// value 保存值,供当前处理流程使用
value := strings.Trim(strings.TrimSpace(string(raw)), `"`)
if value == "" || value == "null" {
return 0
}
if parsed, err := time.Parse(time.RFC3339, value); err == nil {
if // parsed、err 保存parsed、err,供当前处理流程使用
parsed, err := time.Parse(time.RFC3339, value); err == nil {
return parsed.Unix()
}
// n、err 保存n、err,供当前处理流程使用
n, err := strconv.ParseFloat(value, 64)
if err != nil || n <= 0 {
return 0
@@ -349,7 +422,9 @@ func parseAccessTokenExpireAt(raw json.RawMessage, now time.Time) int64 {
// buildTokenQuery 构造 token API 的 query string。
// 值按原样拼接(dangerouslySetWindvaneParams 已是单次编码),不做二次编码。
// buildTokenQuery 负责build令牌查询相关处理。
func buildTokenQuery(t, sign string) string {
// parts 保存parts,供当前处理流程使用
parts := [][2]string{
{"jsv", "2.7.2"},
{"appKey", protocol.SignAppKey},
@@ -371,7 +446,9 @@ func buildTokenQuery(t, sign string) string {
{"spm_pre", ""},
{"log_id", ""},
}
// b 保存b,供当前处理流程使用
var b strings.Builder
// i、p 表示当前遍历过程中的i、p
for i, p := range parts {
if i > 0 {
b.WriteByte('&')
+105 -5
View File
@@ -18,32 +18,44 @@ import (
"xianyu-go/internal/xianyu/protocol"
)
// testCookiesWithUnb 保存testCookiesWithUnb,供当前处理流程使用
const testCookiesWithUnb = "unb=123; _m_h5_tk=oldtoken_1;"
// TestRefreshTokenHTTPUsesCookieSessionScopes 负责TestRefresh令牌HTTPUses登录凭证会话Scopes相关处理。
func TestRefreshTokenHTTPUsesCookieSessionScopes(t *testing.T) {
// initial 保存initial,供当前处理流程使用
initial := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "document-old_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "document_only", Value: "visible", Domain: "www.goofish.com", Path: "/im", Secure: true},
{Name: "api_http_only", Value: "secret", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
}
// ctx、session 保存ctx、session,供当前处理流程使用
ctx, session := WithCookieSnapshot(context.Background(), initial)
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
// cookieHeader 保存登录凭证Header,供当前处理流程使用
cookieHeader := req.Header.Get("Cookie")
// want 表示当前遍历过程中的want
for _, want := range []string{"unb=123", "_m_h5_tk=document-old_1", "api_http_only=secret"} {
if !strings.Contains(cookieHeader, want) {
t.Errorf("request Cookie %q missing %q", cookieHeader, want)
}
}
// unwanted 表示当前遍历过程中的unwanted
for _, unwanted := range []string{"document_only=", "fallback_only="} {
if strings.Contains(cookieHeader, unwanted) {
t.Errorf("request Cookie %q unexpectedly contains %q", cookieHeader, unwanted)
}
}
// timestamp 保存timestamp,供当前处理流程使用
timestamp := req.URL.Query().Get("t")
// dataVal 保存数据Val,供当前处理流程使用
dataVal := `{"appKey":"` + RegAppKey + `","deviceId":"did"}`
// wantSign 保存wantSign,供当前处理流程使用
wantSign := protocol.GenerateSign(timestamp, "document-old", dataVal)
if got := req.URL.Query().Get("sign"); got != wantSign {
if // got 保存got,供当前处理流程使用
got := req.URL.Query().Get("sign"); got != wantSign {
t.Errorf("sign=%q want %q", got, wantSign)
}
return &http.Response{
@@ -55,10 +67,12 @@ func TestRefreshTokenHTTPUsesCookieSessionScopes(t *testing.T) {
Request: req,
}, nil
})}}
// result、err 保存result、err,供当前处理流程使用
result, err := client.RefreshTokenWithDeviceIDContext(ctx, "unb=fallback; _m_h5_tk=fallback_1; fallback_only=leak", "did")
if err != nil || result.AccessToken != "direct-context" {
t.Fatalf("result=%+v err=%v", result, err)
}
// canonical、changed 保存canonical、changed,供当前处理流程使用
canonical, _, changed := session.State()
if !changed || !strings.Contains(canonical, "_m_h5_tk=document-new_9") || !strings.Contains(result.UpdatedCookies, "_m_h5_tk=document-new_9") {
t.Fatalf("canonical=%q result=%+v changed=%v", canonical, result, changed)
@@ -67,8 +81,11 @@ func TestRefreshTokenHTTPUsesCookieSessionScopes(t *testing.T) {
// TestRefreshTokenWithDeviceIDSuccessOnRetry: 首次返回 token 过期 + Set-Cookie,二次成功。
func TestRefreshTokenWithDeviceIDSuccessOnRetry(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// attempt 保存尝试次数,供当前处理流程使用
attempt := requests.Add(1)
if attempt == 1 {
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "newtoken_999", Path: "/"})
@@ -79,9 +96,12 @@ func TestRefreshTokenWithDeviceIDSuccessOnRetry(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// result、err 保存result、err,供当前处理流程使用
result, err := client.RefreshTokenWithDeviceIDContext(ctx, testCookiesWithUnb, "device-xyz")
if err != nil {
t.Fatalf("err=%v", err)
@@ -96,12 +116,15 @@ func TestRefreshTokenWithDeviceIDSuccessOnRetry(t *testing.T) {
// TestRefreshTokenMissingUnbCookie: cookie 缺 unb 报错。
func TestRefreshTokenMissingUnbCookie(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("不应发请求")
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.RefreshTokenContext(context.Background(), "_m_h5_tk=token_1;")
if err == nil || !strings.Contains(err.Error(), "cookie 缺少 unb") {
t.Fatalf("err=%v", err)
@@ -110,14 +133,18 @@ func TestRefreshTokenMissingUnbCookie(t *testing.T) {
// TestRefreshTokenSuccessButAccessTokenEmpty: ret SUCCESS 但 accessToken 为空。
func TestRefreshTokenSuccessButAccessTokenEmpty(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{}}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.RefreshTokenContext(context.Background(), testCookiesWithUnb)
if err == nil || !strings.Contains(err.Error(), "accessToken 为空") {
t.Fatalf("err=%v", err)
@@ -129,14 +156,18 @@ func TestRefreshTokenSuccessButAccessTokenEmpty(t *testing.T) {
// TestRefreshTokenNonSuccessRet: 非 token 过期的失败 ret,不重试直接报错。
func TestRefreshTokenNonSuccessRet(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
fmt.Fprint(w, `{"ret":["FAIL_BIZ_VALIDATE_FAIL::参数错误"]}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.RefreshTokenContext(context.Background(), testCookiesWithUnb)
if err == nil || !strings.Contains(err.Error(), "token API 返回非成功") {
t.Fatalf("err=%v", err)
@@ -148,6 +179,7 @@ func TestRefreshTokenNonSuccessRet(t *testing.T) {
// TestRefreshTokenHTTPError: 5xx 视为请求失败,直接返回 err(不进入 ret 解析路径)。
func TestRefreshTokenHTTPError(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 5xx 但 body 是有效 JSON — refreshTokenOnce 只看业务 ret,不看 HTTP 状态码;
// 由于 ret 解析为非 token 过期失败,应走"返回非成功"分支。
@@ -156,7 +188,9 @@ func TestRefreshTokenHTTPError(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.RefreshTokenContext(context.Background(), testCookiesWithUnb)
if err == nil || !strings.Contains(err.Error(), "token API 返回非成功") {
t.Fatalf("err=%v", err)
@@ -165,12 +199,15 @@ func TestRefreshTokenHTTPError(t *testing.T) {
// TestRefreshTokenParseFailure: 响应非 JSON 解析失败。
func TestRefreshTokenParseFailure(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `not-json{{{`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.RefreshTokenContext(context.Background(), testCookiesWithUnb)
if err == nil || !strings.Contains(err.Error(), "解析 token 响应失败") {
t.Fatalf("err=%v", err)
@@ -179,10 +216,13 @@ func TestRefreshTokenParseFailure(t *testing.T) {
// TestRefreshTokenRequestError: 网络层错误(服务器关闭)。
func TestRefreshTokenRequestError(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
server.Close() // 立即关闭,使请求失败
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.RefreshTokenContext(context.Background(), testCookiesWithUnb)
if err == nil || !strings.Contains(err.Error(), "token API 请求失败") {
t.Fatalf("err=%v", err)
@@ -191,8 +231,11 @@ func TestRefreshTokenRequestError(t *testing.T) {
// TestRefreshTokenExpiredRetNoCookieUsesOfficialAttemptLimit: 官网 lib-mtop 即使
// 响应未下发新 Cookie,也会最多执行五次请求(含首次)。
// TestRefreshTokenExpiredRetNoCookieUsesOfficialAttemptLimit 负责TestRefresh令牌ExpiredRetNo登录凭证UsesOfficial尝试次数上限相关处理。
func TestRefreshTokenExpiredRetNoCookieUsesOfficialAttemptLimit(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
// 不 Set-Cookie,ret 为 token 过期
@@ -200,7 +243,9 @@ func TestRefreshTokenExpiredRetNoCookieUsesOfficialAttemptLimit(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// err 保存err,供当前处理流程使用
_, err := client.RefreshTokenContext(context.Background(), testCookiesWithUnb)
if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
t.Fatalf("err=%v", err)
@@ -210,7 +255,9 @@ func TestRefreshTokenExpiredRetNoCookieUsesOfficialAttemptLimit(t *testing.T) {
}
}
// TestRefreshTokenExhaustionClearsOfficialMTopCookies 负责TestRefresh令牌ExhaustionClearsOfficialMTopCookies相关处理。
func TestRefreshTokenExhaustionClearsOfficialMTopCookies(t *testing.T) {
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/"},
{Name: "keep", Value: "yes", Domain: ".goofish.com", Path: "/"},
@@ -219,13 +266,17 @@ func TestRefreshTokenExhaustionClearsOfficialMTopCookies(t *testing.T) {
{Name: "_m_h5_tk_enc", Value: "enc", Domain: ".m.goofish.com", Path: "/"},
{Name: "_m_h5_tk", Value: "scoped", Domain: ".goofish.com", Path: "/im"},
}
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
requests.Add(1)
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`)
}))
defer server.Close()
// ctx 保存ctx,供当前处理流程使用
ctx, _ := WithCookieSnapshot(context.Background(), snapshot)
// result、err 保存result、err,供当前处理流程使用
result, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenWithCredentialContext(
ctx, testCookiesWithUnb, "did", snapshot,
)
@@ -235,6 +286,7 @@ func TestRefreshTokenExhaustionClearsOfficialMTopCookies(t *testing.T) {
if requests.Load() != officialMTopMaxAttempts {
t.Fatalf("requests=%d want %d", requests.Load(), officialMTopMaxAttempts)
}
// name 表示当前遍历过程中的名称
for _, name := range []string{"_m_h5_c=", "_m_h5_tk_enc="} {
if strings.Contains(result.UpdatedCookies, name) {
t.Fatalf("官网清理后仍包含 %s: %q", name, result.UpdatedCookies)
@@ -246,7 +298,9 @@ func TestRefreshTokenExhaustionClearsOfficialMTopCookies(t *testing.T) {
if !strings.Contains(result.UpdatedCookies, "keep=yes") {
t.Fatalf("无关 Cookie 被误删: %q", result.UpdatedCookies)
}
// keptScoped 保存keptScoped,供当前处理流程使用
var keptScoped bool
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range result.CookieSnapshot {
if cookie.Name == "_m_h5_tk" && cookie.Path == "/im" {
keptScoped = true
@@ -260,17 +314,23 @@ func TestRefreshTokenExhaustionClearsOfficialMTopCookies(t *testing.T) {
}
}
// TestRefreshTokenFlatSessionExhaustionPersistsOfficialCookieClear 负责TestRefresh令牌Flat会话ExhaustionPersistsOfficial登录凭证Clear相关处理。
func TestRefreshTokenFlatSessionExhaustionPersistsOfficialCookieClear(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"],"data":{}}`)
}))
defer server.Close()
// initial 保存initial,供当前处理流程使用
initial := "unb=123; _m_h5_c=c; _m_h5_tk=oldtoken_1; _m_h5_tk_enc=enc; keep=yes"
// ctx、session 保存ctx、session,供当前处理流程使用
ctx, session := WithFlatCookieSession(context.Background(), initial)
// result、err 保存result、err,供当前处理流程使用
result, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenContext(ctx, initial)
if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
t.Fatalf("result=%+v err=%v", result, err)
}
// removed 表示当前遍历过程中的removed
for _, removed := range []string{"_m_h5_c=", "_m_h5_tk=", "_m_h5_tk_enc="} {
if strings.Contains(result.UpdatedCookies, removed) {
t.Fatalf("legacy flat 清理结果仍包含 %s: %q", removed, result.UpdatedCookies)
@@ -279,14 +339,18 @@ func TestRefreshTokenFlatSessionExhaustionPersistsOfficialCookieClear(t *testing
if !strings.Contains(result.UpdatedCookies, "unb=123") || !strings.Contains(result.UpdatedCookies, "keep=yes") || !result.CookieStateChanged {
t.Fatalf("result=%+v", result)
}
// value、snapshot、changed 保存value、snapshot、changed,供当前处理流程使用
value, snapshot, changed := session.State()
if !changed || snapshot != nil || value != result.UpdatedCookies {
t.Fatalf("session value=%q snapshot=%+v changed=%v result=%+v", value, snapshot, changed, result)
}
}
// TestRefreshTokenKeepsAccumulatedSnapshotWhenLaterAttemptFails 负责TestRefresh令牌KeepsAccumulatedSnapshotWhenLater尝试次数Fails相关处理。
func TestRefreshTokenKeepsAccumulatedSnapshotWhenLaterAttemptFails(t *testing.T) {
// calls 保存calls,供当前处理流程使用
var calls atomic.Int32
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
if calls.Add(1) == 1 {
return &http.Response{
@@ -300,10 +364,12 @@ func TestRefreshTokenKeepsAccumulatedSnapshotWhenLaterAttemptFails(t *testing.T)
}
return nil, fmt.Errorf("second attempt network failure")
})}}
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "oldtoken_1", Domain: ".goofish.com", Path: "/", Secure: true},
}
// result、err 保存result、err,供当前处理流程使用
result, err := client.RefreshTokenWithCredentialContext(context.Background(), testCookiesWithUnb, "did", snapshot)
if err == nil || !strings.Contains(err.Error(), "network failure") {
t.Fatalf("result=%+v err=%v", result, err)
@@ -311,7 +377,9 @@ func TestRefreshTokenKeepsAccumulatedSnapshotWhenLaterAttemptFails(t *testing.T)
if !result.CookieSnapshotComplete || !result.CookieStateChanged {
t.Fatalf("累计 Jar 状态丢失: %+v", result)
}
// found 保存found,供当前处理流程使用
var found bool
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range result.CookieSnapshot {
if cookie.Name == "off_im" && cookie.Value == "rotated" && cookie.Path == "/account" {
found = true
@@ -322,13 +390,16 @@ func TestRefreshTokenKeepsAccumulatedSnapshotWhenLaterAttemptFails(t *testing.T)
}
}
// TestRefreshTokenPreservesExplicitFlatDeletionOnParseError 负责TestRefresh令牌PreservesExplicitFlatDeletionOnParse错误相关处理。
func TestRefreshTokenPreservesExplicitFlatDeletionOnParseError(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Add("Set-Cookie", "unb=; Path=/; Max-Age=0")
w.Header().Add("Set-Cookie", "_m_h5_tk=; Path=/; Max-Age=0")
_, _ = w.Write([]byte(`not-json`))
}))
defer server.Close()
// result、err 保存result、err,供当前处理流程使用
result, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenContext(context.Background(), testCookiesWithUnb)
if err == nil || !strings.Contains(err.Error(), "解析 token 响应失败") {
t.Fatalf("result=%+v err=%v", result, err)
@@ -338,20 +409,26 @@ func TestRefreshTokenPreservesExplicitFlatDeletionOnParseError(t *testing.T) {
}
}
// TestRefreshTokenSessionExpiredDoesNotUseTokenRetry 负责TestRefresh令牌会话ExpiredDoesNotUse令牌重试相关处理。
func TestRefreshTokenSessionExpiredDoesNotUseTokenRetry(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
requests.Add(1)
fmt.Fprint(w, `{"ret":["FAIL_SYS_SESSION_EXPIRED::会话过期"]}`)
}))
defer server.Close()
// err 保存err,供当前处理流程使用
_, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenContext(context.Background(), testCookiesWithUnb)
if err == nil || requests.Load() != 1 {
t.Fatalf("err=%v requests=%d want 1", err, requests.Load())
}
}
// TestBuildTokenQueryMatchesCurrentMessagePageContext 负责TestBuild令牌查询MatchesCurrent消息页码上下文相关处理。
func TestBuildTokenQueryMatchesCurrentMessagePageContext(t *testing.T) {
// query、err 保存query、err,供当前处理流程使用
query, err := url.ParseQuery(buildTokenQuery("123", "sig"))
if err != nil {
t.Fatal(err)
@@ -359,16 +436,21 @@ func TestBuildTokenQueryMatchesCurrentMessagePageContext(t *testing.T) {
if query.Get("spm_cnt") != "a21ybx.im.0.0" || query.Get("spm_pre") != "" || query.Get("log_id") != "" {
t.Fatalf("spm query=%v", query)
}
// stale 表示当前遍历过程中的stale
for _, stale := range []string{"smToken", "queryToken", "sm"} {
if _, ok := query[stale]; ok {
if // ok 保存ok,供当前处理流程使用
_, ok := query[stale]; ok {
t.Fatalf("官网当前 token 请求不应包含 %s: %v", stale, query)
}
}
}
// TestRefreshTokenUsesReferenceFingerprint 负责TestRefresh令牌UsesReferenceFingerprint相关处理。
func TestRefreshTokenUsesReferenceFingerprint(t *testing.T) {
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "playwright-native-ua", SecChUA: `"Chromium";v="999"`})
// gotUA、gotSecChUA 保存gotUA、gotSecChUA,供当前处理流程使用
var gotUA, gotSecChUA string
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotUA = r.Header.Get("User-Agent")
gotSecChUA = r.Header.Get("sec-ch-ua")
@@ -376,8 +458,10 @@ func TestRefreshTokenUsesReferenceFingerprint(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
if _, err := client.RefreshTokenWithDeviceIDContext(context.Background(), testCookiesWithUnb, "did"); err != nil {
if // err 保存err,供当前处理流程使用
_, err := client.RefreshTokenWithDeviceIDContext(context.Background(), testCookiesWithUnb, "did"); err != nil {
t.Fatal(err)
}
if gotUA != "playwright-native-ua" || gotSecChUA != `"Chromium";v="999"` {
@@ -387,8 +471,11 @@ func TestRefreshTokenUsesReferenceFingerprint(t *testing.T) {
// TestRefreshTokenContextCanceled: 连续重试期间仍遵守调用方 ctx。
func TestRefreshTokenContextCanceled(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// attempt 保存尝试次数,供当前处理流程使用
attempt := requests.Add(1)
if attempt == 1 {
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "newtoken_999", Path: "/"})
@@ -402,7 +489,9 @@ func TestRefreshTokenContextCanceled(t *testing.T) {
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// 在第二次请求开始后取消,避免依赖固定重试延迟。
go func() {
@@ -411,6 +500,7 @@ func TestRefreshTokenContextCanceled(t *testing.T) {
}
cancel()
}()
// err 保存err,供当前处理流程使用
_, err := client.RefreshTokenContext(ctx, testCookiesWithUnb)
if err == nil {
t.Fatalf("expected ctx cancel error, got nil")
@@ -423,12 +513,15 @@ func TestRefreshTokenContextCanceled(t *testing.T) {
// TestRefreshTokenRefreshWrapper: RefreshToken(无 Context)调用等价于 RefreshTokenContext。
func TestRefreshTokenRefreshWrapper(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"wrapped"}}`)
}))
defer server.Close()
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
// result、err 保存result、err,供当前处理流程使用
result, err := client.RefreshToken(testCookiesWithUnb)
if err != nil {
t.Fatalf("err=%v", err)
@@ -438,8 +531,11 @@ func TestRefreshTokenRefreshWrapper(t *testing.T) {
}
}
// TestParseAccessTokenExpireAtSupportsOfficialTimestampForms 负责TestParseAccess令牌ExpireAtSupportsOfficialTimestampForms相关处理。
func TestParseAccessTokenExpireAtSupportsOfficialTimestampForms(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Unix(1_700_000_000, 0)
// tests 保存tests,供当前处理流程使用
tests := []struct {
name string
raw string
@@ -450,17 +546,21 @@ func TestParseAccessTokenExpireAtSupportsOfficialTimestampForms(t *testing.T) {
{name: "relative seconds", raw: `7200`, want: now.Add(2 * time.Hour).Unix()},
{name: "relative milliseconds", raw: `7200000`, want: now.Add(2 * time.Hour).Unix()},
}
// tt 表示当前遍历过程中的tt
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := parseAccessTokenExpireAt(json.RawMessage(tt.raw), now); got != tt.want {
if // got 保存got,供当前处理流程使用
got := parseAccessTokenExpireAt(json.RawMessage(tt.raw), now); got != tt.want {
t.Fatalf("expireAt=%d want=%d", got, tt.want)
}
})
}
}
// TestParseAccessTokenExpireAtRejectsMissingValue 负责TestParseAccess令牌ExpireAtRejectsMissing值相关处理。
func TestParseAccessTokenExpireAtRejectsMissingValue(t *testing.T) {
if got := parseAccessTokenExpireAt(nil, time.Now()); got != 0 {
if // got 保存got,供当前处理流程使用
got := parseAccessTokenExpireAt(nil, time.Now()); got != 0 {
t.Fatalf("expireAt=%d want=0", got)
}
}
+37 -5
View File
@@ -16,12 +16,17 @@ import (
// FetchUserProfile 获取当前 cookie 对应账号的实时昵称和头像。
func (c *ClientImpl) FetchUserProfile(ctx context.Context, cookiesStr string) (*UserProfileResult, error) {
// currentCookies 保存currentCookies,供当前处理流程使用
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
// lastRet 保存lastRet,供当前处理流程使用
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
for // attempt 保存尝试次数,供当前处理流程使用
attempt := 0; attempt < 4; attempt++ {
// res、ret、updatedCookies、err 保存res、ret、updatedCookies、err,供当前处理流程使用
res, ret, updatedCookies, err := c.fetchUserProfileOnce(ctx, currentCookies)
if err != nil {
return nil, err
@@ -38,14 +43,17 @@ func (c *ClientImpl) FetchUserProfile(ctx context.Context, cookiesStr string) (*
}
if updatedCookies != "" && updatedCookies != currentCookies {
currentCookies = updatedCookies
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
if // err 保存err,供当前处理流程使用
err := sleepCtx(ctx, MTopRetryGap); err != nil {
return nil, err
}
continue
}
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
if // err 保存err,供当前处理流程使用
err := sleepCtx(ctx, MTopRetryGap); err != nil {
return nil, err
}
// refreshed、err 保存refreshed、err,供当前处理流程使用
refreshed, err := c.RefreshTokenContext(ctx, currentCookies)
if err != nil {
return nil, fmt.Errorf("刷新 mtop token 失败: %w", err)
@@ -55,50 +63,67 @@ func (c *ClientImpl) FetchUserProfile(ctx context.Context, cookiesStr string) (*
return nil, fmt.Errorf("账号资料接口 token 重试失败: ret=%v", lastRet)
}
// fetchUserProfileOnce 负责fetch用户ProfileOnce相关处理。
func (c *ClientImpl) fetchUserProfileOnce(ctx context.Context, cookiesStr string) (*UserProfileResult, []string, string, error) {
// hc 保存hc,供当前处理流程使用
hc := c.httpClient()
// dataVal 保存数据Val,供当前处理流程使用
dataVal := "{}"
// signingCookies、requestCookies 保存signingCookies、requestCookies,供当前处理流程使用
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", UserPageNavAPI)
// t 保存t,供当前处理流程使用
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
// sign 保存sign,供当前处理流程使用
sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
// query 保存查询,供当前处理流程使用
query := buildUserPageNavQuery(t, sign)
// body 保存请求体,供当前处理流程使用
body := "data=" + url.QueryEscape(dataVal)
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost, UserPageNavAPI+"?"+query, strings.NewReader(body))
if err != nil {
return nil, nil, cookiesStr, err
}
setCommonHeaders(req, requestCookies)
// resp、err 保存resp、err,供当前处理流程使用
resp, err := hc.Do(req)
if err != nil {
return nil, nil, cookiesStr, fmt.Errorf("账号资料请求失败: %w", err)
}
defer resp.Body.Close()
// updated 保存updated,供当前处理流程使用
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readMTopBody(resp)
if err != nil {
return nil, nil, updated, err
}
// decoded 保存decoded,供当前处理流程使用
var decoded struct {
Ret []string `json:"ret"`
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(raw, &decoded); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(raw, &decoded); err != nil {
return nil, nil, updated, fmt.Errorf("解析账号资料响应失败: %w (body=%s)", err, truncate(string(raw), 300))
}
if !hasMTopSuccess(decoded.Ret) {
return nil, decoded.Ret, updated, nil
}
// profile 保存profile,供当前处理流程使用
profile := parseUserProfile(decoded.Data)
profile.UpdatedCookies = updated
return profile, decoded.Ret, updated, nil
}
// buildUserPageNavQuery 负责build用户页码Nav查询相关处理。
func buildUserPageNavQuery(t, sign string) string {
// parts 保存parts,供当前处理流程使用
parts := [][2]string{
{"jsv", "2.7.2"},
{"appKey", protocol.SignAppKey},
@@ -114,7 +139,9 @@ func buildUserPageNavQuery(t, sign string) string {
{"ecode", "0"},
{"spm_cnt", "a21ybx.home.0.0"},
}
// b 保存b,供当前处理流程使用
var b strings.Builder
// i、p 表示当前遍历过程中的i、p
for i, p := range parts {
if i > 0 {
b.WriteByte('&')
@@ -126,13 +153,18 @@ func buildUserPageNavQuery(t, sign string) string {
return b.String()
}
// parseUserProfile 负责parse用户Profile相关处理。
func parseUserProfile(data map[string]any) *UserProfileResult {
// module 保存module,供当前处理流程使用
module, _ := data["module"].(map[string]any)
// base 保存base,供当前处理流程使用
base, _ := module["base"].(map[string]any)
if base == nil {
return &UserProfileResult{}
}
// nickname 保存nickname,供当前处理流程使用
nickname := strings.TrimSpace(mtopString(base["displayName"]))
// displayNick 保存displayNick,供当前处理流程使用
displayNick := strings.TrimSpace(mtopString(base["displayNick"]))
if nickname == "" {
nickname = displayNick
+50
View File
@@ -21,8 +21,10 @@ type rewriteTransport struct {
target string
}
// RoundTrip 负责RoundTrip相关处理。
func (t *rewriteTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req = req.Clone(req.Context())
// target、err 保存target、err,供当前处理流程使用
target, err := url.Parse(t.target)
if err != nil {
return nil, err
@@ -30,6 +32,7 @@ func (t *rewriteTransport) RoundTrip(req *http.Request) (*http.Response, error)
target.RawQuery = req.URL.RawQuery
req.URL = target
req.Host = target.Host
// rt 保存rt,供当前处理流程使用
rt := t.base
if rt == nil {
rt = http.DefaultTransport
@@ -39,7 +42,9 @@ func (t *rewriteTransport) RoundTrip(req *http.Request) (*http.Response, error)
// TestFetchUserProfileSuccess: 成功解析 module.base。
func TestFetchUserProfileSuccess(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "fresh_8", Path: "/"})
@@ -47,8 +52,11 @@ func TestFetchUserProfileSuccess(t *testing.T) {
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchUserProfile(context.Background(), consignCookies)
if err != nil {
t.Fatalf("err=%v", err)
@@ -66,13 +74,17 @@ func TestFetchUserProfileSuccess(t *testing.T) {
// TestFetchUserProfileNonSuccessRet: 非 token 过期失败 ret 报错。
func TestFetchUserProfileNonSuccessRet(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"ret":["FAIL_BIZ_USER_NOT_FOUND::用户不存在"]}`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// err 保存err,供当前处理流程使用
_, err := client.FetchUserProfile(context.Background(), consignCookies)
if err == nil || !strings.Contains(err.Error(), "账号资料接口返回非成功") {
t.Fatalf("err=%v", err)
@@ -81,13 +93,17 @@ func TestFetchUserProfileNonSuccessRet(t *testing.T) {
// TestFetchUserProfileParseFailure: 响应非 JSON。
func TestFetchUserProfileParseFailure(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `not-json{`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// err 保存err,供当前处理流程使用
_, err := client.FetchUserProfile(context.Background(), consignCookies)
if err == nil || !strings.Contains(err.Error(), "解析账号资料响应失败") {
t.Fatalf("err=%v", err)
@@ -98,7 +114,9 @@ func TestFetchUserProfileParseFailure(t *testing.T) {
func TestFetchUserProfileRequestError(t *testing.T) {
// 指向一个不可达地址
rt := &rewriteTransport{base: http.DefaultTransport, target: "http://127.0.0.1:1"}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 200 * time.Millisecond}}
// err 保存err,供当前处理流程使用
_, err := client.FetchUserProfile(context.Background(), consignCookies)
if err == nil {
t.Fatalf("expected err")
@@ -107,8 +125,11 @@ func TestFetchUserProfileRequestError(t *testing.T) {
// TestFetchUserProfileTokenExpiredRetriesWithSetCookie: token 过期 + Set-Cookie,二次成功。
func TestFetchUserProfileTokenExpiredRetriesWithSetCookie(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// attempt 保存尝试次数,供当前处理流程使用
attempt := requests.Add(1)
if attempt == 1 {
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "newtoken_9", Path: "/"})
@@ -119,10 +140,14 @@ func TestFetchUserProfileTokenExpiredRetriesWithSetCookie(t *testing.T) {
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// res、err 保存res、err,供当前处理流程使用
res, err := client.FetchUserProfile(ctx, consignCookies)
if err != nil {
t.Fatalf("err=%v", err)
@@ -139,14 +164,18 @@ func TestFetchUserProfileTokenExpiredRetriesWithSetCookie(t *testing.T) {
// TestFetchUserProfileRefreshTokenFailure: token 过期无 Set-Cookie,RefreshToken 失败时报错。
func TestFetchUserProfileRefreshTokenFailure(t *testing.T) {
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// profile 持续返回 token 过期且不 Set-Cookie;token API 也返回失败
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`)
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}}
// err 保存err,供当前处理流程使用
_, err := client.FetchUserProfile(context.Background(), consignCookies)
if err == nil || !strings.Contains(err.Error(), "刷新 mtop token 失败") {
t.Fatalf("err=%v", err)
@@ -155,9 +184,13 @@ func TestFetchUserProfileRefreshTokenFailure(t *testing.T) {
// TestFetchUserProfileRetryExhausted: token 过期但每次都通过新 Set-Cookie 重试,4 次后耗尽。
// 关键:每次下发的 Cookie 值都不同,使 updatedCookies != currentCookies,跳过 RefreshToken 走 continue。
// TestFetchUserProfileRetryExhausted 负责TestFetch用户Profile重试Exhausted相关处理。
func TestFetchUserProfileRetryExhausted(t *testing.T) {
// requests 保存请求列表,供当前处理流程使用
var requests atomic.Int32
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// n 保存n,供当前处理流程使用
n := requests.Add(1)
// 每次下发不同的 _m_h5_tk 值,确保 updatedCookies != currentCookies
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: fmt.Sprintf("tok_%d", n), Path: "/"})
@@ -165,10 +198,14 @@ func TestFetchUserProfileRetryExhausted(t *testing.T) {
}))
defer server.Close()
// rt 保存rt,供当前处理流程使用
rt := &rewriteTransport{base: server.Client().Transport, target: server.URL}
// client 保存client,供当前处理流程使用
client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 15 * time.Second}}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// err 保存err,供当前处理流程使用
_, err := client.FetchUserProfile(ctx, consignCookies)
if err == nil || !strings.Contains(err.Error(), "账号资料接口 token 重试失败") {
t.Fatalf("err=%v", err)
@@ -177,7 +214,10 @@ func TestFetchUserProfileRetryExhausted(t *testing.T) {
t.Fatalf("requests=%d want 4(重试上限)", requests.Load())
}
}
// TestParseUserProfileFull 负责TestParse用户ProfileFull相关处理。
func TestParseUserProfileFull(t *testing.T) {
// data 保存数据,供当前处理流程使用
data := map[string]any{
"module": map[string]any{
"base": map[string]any{
@@ -187,6 +227,7 @@ func TestParseUserProfileFull(t *testing.T) {
},
},
}
// p 保存p,供当前处理流程使用
p := parseUserProfile(data)
if p.Nickname != "小明" || p.DisplayNick != "小明昵称" || p.AvatarURL != "https://cdn/avatar.jpg" {
t.Fatalf("p=%+v", p)
@@ -195,6 +236,7 @@ func TestParseUserProfileFull(t *testing.T) {
// TestParseUserProfileNicknameFallsBackToDisplayNick: displayName 为空时用 displayNick。
func TestParseUserProfileNicknameFallsBackToDisplayNick(t *testing.T) {
// data 保存数据,供当前处理流程使用
data := map[string]any{
"module": map[string]any{
"base": map[string]any{
@@ -202,6 +244,7 @@ func TestParseUserProfileNicknameFallsBackToDisplayNick(t *testing.T) {
},
},
}
// p 保存p,供当前处理流程使用
p := parseUserProfile(data)
if p.Nickname != "fallbackNick" || p.DisplayNick != "fallbackNick" {
t.Fatalf("p=%+v", p)
@@ -210,6 +253,7 @@ func TestParseUserProfileNicknameFallsBackToDisplayNick(t *testing.T) {
// TestParseUserProfileEmptyBase: base 为 nil 时返回空结构。
func TestParseUserProfileEmptyBase(t *testing.T) {
// p 保存p,供当前处理流程使用
p := parseUserProfile(map[string]any{"module": map[string]any{}})
if p == nil || p.Nickname != "" || p.AvatarURL != "" {
t.Fatalf("p=%+v want empty", p)
@@ -218,6 +262,7 @@ func TestParseUserProfileEmptyBase(t *testing.T) {
// TestParseUserProfileNoModule: module 缺失也返回空结构。
func TestParseUserProfileNoModule(t *testing.T) {
// p 保存p,供当前处理流程使用
p := parseUserProfile(map[string]any{})
if p == nil || p.Nickname != "" {
t.Fatalf("p=%+v want empty", p)
@@ -226,6 +271,7 @@ func TestParseUserProfileNoModule(t *testing.T) {
// TestParseUserProfileTrimsWhitespace: 字段带空白被 TrimSpace。
func TestParseUserProfileTrimsWhitespace(t *testing.T) {
// data 保存数据,供当前处理流程使用
data := map[string]any{
"module": map[string]any{
"base": map[string]any{
@@ -234,6 +280,7 @@ func TestParseUserProfileTrimsWhitespace(t *testing.T) {
},
},
}
// p 保存p,供当前处理流程使用
p := parseUserProfile(data)
if p.Nickname != "小明" || p.AvatarURL != "https://cdn/a.jpg" {
t.Fatalf("p=%+v", p)
@@ -242,6 +289,7 @@ func TestParseUserProfileTrimsWhitespace(t *testing.T) {
// TestParseUserProfileNumericAvatar: 非字符串字段经 mtopString 转换。
func TestParseUserProfileNumericAvatar(t *testing.T) {
// data 保存数据,供当前处理流程使用
data := map[string]any{
"module": map[string]any{
"base": map[string]any{
@@ -249,6 +297,7 @@ func TestParseUserProfileNumericAvatar(t *testing.T) {
},
},
}
// p 保存p,供当前处理流程使用
p := parseUserProfile(data)
if p.Nickname != "12345" {
t.Fatalf("Nickname=%q want 12345", p.Nickname)
@@ -257,6 +306,7 @@ func TestParseUserProfileNumericAvatar(t *testing.T) {
// TestBuildUserPageNavQuery: 验证 query 拼接与编码。
func TestBuildUserPageNavQuery(t *testing.T) {
// q 保存q,供当前处理流程使用
q := buildUserPageNavQuery("1000", "SIGN")
if !strings.Contains(q, "t=1000") || !strings.Contains(q, "sign=SIGN") ||
!strings.Contains(q, "api=mtop.idle.web.user.page.nav") ||
+9 -1
View File
@@ -5,12 +5,15 @@ import "strings"
// TransCookies 将 "k1=v1; k2=v2" 形式的 cookie 字符串解析为 map。
func TransCookies(cookiesStr string) map[string]string {
// cookies 保存cookies,供当前处理流程使用
cookies := make(map[string]string)
if cookiesStr == "" {
return cookies
}
// part 表示当前遍历过程中的part
for _, part := range strings.Split(cookiesStr, ";") {
part = strings.TrimSpace(part)
// key、value、ok 保存key、value、ok,供当前处理流程使用
key, value, ok := strings.Cut(part, "=")
key = strings.TrimSpace(key)
if !ok || key == "" {
@@ -23,12 +26,16 @@ func TransCookies(cookiesStr string) map[string]string {
// SignToken 从 cookie 字符串中提取 _m_h5_tk 的前半段,作为 mtop API 签名用的 token。
// _m_h5_tk 形如 "<token>_<timestamp>",取 "_" 前的部分。
// SignToken 负责Sign令牌相关处理。
func SignToken(cookiesStr string) string {
// 浏览器 Cookie header / document.cookie 会把更长 Path 的同名 Cookie
// 排在前面,官网 cookie getter 读取首个匹配项。不能先压成 map 再取值,
// 否则同名 token 会被最后一个(通常是更宽作用域)错误覆盖。
// v 保存v,供当前处理流程使用
v := ""
// part 表示当前遍历过程中的part
for _, part := range strings.Split(cookiesStr, ";") {
// key、value、ok 保存key、value、ok,供当前处理流程使用
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
if ok && strings.TrimSpace(key) == "_m_h5_tk" {
v = strings.TrimSpace(value)
@@ -38,7 +45,8 @@ func SignToken(cookiesStr string) string {
if v == "" {
return ""
}
if i := strings.Index(v, "_"); i >= 0 {
if // i 保存i,供当前处理流程使用
i := strings.Index(v, "_"); i >= 0 {
return v[:i]
}
return v
+13 -1
View File
@@ -8,6 +8,7 @@ import (
// TestTransCookies_Table 表驱动覆盖 cookie 解析的边界。
func TestTransCookies_Table(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
in string
@@ -27,12 +28,15 @@ func TestTransCookies_Table(t *testing.T) {
{"single fragment no space separator", "a=1;b=2", map[string]string{"a": "1", "b": "2"}},
{"trailing separator", "a=1; b=2;", map[string]string{"a": "1", "b": "2"}},
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// got 保存got,供当前处理流程使用
got := TransCookies(tc.in)
if len(got) != len(tc.want) {
t.Fatalf("TransCookies(%q) = %v (len %d), want %v (len %d)", tc.in, got, len(got), tc.want, len(tc.want))
}
// k、v 表示当前遍历过程中的k、v
for k, v := range tc.want {
if got[k] != v {
t.Fatalf("TransCookies(%q)[%q] = %q, want %q", tc.in, k, got[k], v)
@@ -44,6 +48,7 @@ func TestTransCookies_Table(t *testing.T) {
// TestSignToken 表驱动覆盖从 cookie 串提取 _m_h5_tk token 的边界。
func TestSignToken(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
in string
@@ -59,8 +64,10 @@ func TestSignToken(t *testing.T) {
{"token with multiple underscores takes first", "_m_h5_tk=a_b_c", "a"},
{"token among other cookies", "a=1; _m_h5_tk=tken_123; b=2", "tken"},
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// got 保存got,供当前处理流程使用
got := SignToken(tc.in)
if got != tc.want {
t.Fatalf("SignToken(%q) = %q, want %q", tc.in, got, tc.want)
@@ -69,7 +76,9 @@ func TestSignToken(t *testing.T) {
}
}
// TestSignTokenUsesFirstScopedDuplicate 负责TestSign令牌UsesFirstScopedDuplicate相关处理。
func TestSignTokenUsesFirstScopedDuplicate(t *testing.T) {
// got 保存got,供当前处理流程使用
got := SignToken("_m_h5_tk=narrow_1; other=x; _m_h5_tk=wide_2")
if got != "narrow" {
t.Fatalf("SignToken duplicate=%q want narrow", got)
@@ -78,9 +87,12 @@ func TestSignTokenUsesFirstScopedDuplicate(t *testing.T) {
// TestSignToken_ConsistentWithTransCookies SignToken 必须基于 TransCookies 的解析结果。
func TestSignToken_ConsistentWithTransCookies(t *testing.T) {
// cookies 保存cookies,供当前处理流程使用
cookies := "x=1; _m_h5_tk=mytoken_999; y=2"
// want 保存want,供当前处理流程使用
want := strings.SplitN(TransCookies(cookies)["_m_h5_tk"], "_", 2)[0]
if got := SignToken(cookies); got != want {
if // got 保存got,供当前处理流程使用
got := SignToken(cookies); got != want {
t.Fatalf("SignToken = %q, want %q derived from TransCookies", got, want)
}
}
+18 -3
View File
@@ -12,6 +12,8 @@ import (
// - map 的键统一转为字符串(整数键 → 数字字符串)
// - []byte(msgpack bin)→ UTF-8 字符串(忽略无效字节)
// - 其余类型原样保留
//
// Decrypt 负责Decrypt相关处理。
func Decrypt(data string) (string, error) {
// 清理非 ASCII。
data = stripNonASCII(data)
@@ -19,7 +21,8 @@ func Decrypt(data string) (string, error) {
// base64 解码,必要时补 padding。
decoded, err := base64.StdEncoding.DecodeString(data)
if err != nil {
if pad := len(data) % 4; pad != 0 {
if // pad 保存pad,供当前处理流程使用
pad := len(data) % 4; pad != 0 {
decoded, err = base64.StdEncoding.DecodeString(data + strings.Repeat("=", 4-pad))
}
if err != nil {
@@ -27,13 +30,17 @@ func Decrypt(data string) (string, error) {
}
}
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: decoded}
// val、err 保存val、err,供当前处理流程使用
val, err := d.decodeValue()
if err != nil {
return "", fmt.Errorf("解密失败: %w", err)
}
// normalized 保存normalized,供当前处理流程使用
normalized := normalizeForJSON(val)
// b、err 保存b、err,供当前处理流程使用
b, err := json.Marshal(normalized)
if err != nil {
return "", fmt.Errorf("解密失败: JSON 序列化: %w", err)
@@ -43,8 +50,10 @@ func Decrypt(data string) (string, error) {
// stripNonASCII 删除非 ASCII 字符。
func stripNonASCII(s string) string {
// b 保存b,供当前处理流程使用
var b strings.Builder
b.Grow(len(s))
// r 表示当前遍历过程中的r
for _, r := range s {
if r < 0x80 {
b.WriteRune(r)
@@ -55,15 +64,20 @@ func stripNonASCII(s string) string {
// normalizeForJSON 把 msgpack 解码出的任意结构转为 json.Marshal 友好的结构。
func normalizeForJSON(v any) any {
switch x := v.(type) {
switch // x 保存x,供当前处理流程使用
x := v.(type) {
case map[any]any:
// m 保存m,供当前处理流程使用
m := make(map[string]any, len(x))
// k、val 表示当前遍历过程中的k、val
for k, val := range x {
m[keyToString(k)] = normalizeForJSON(val)
}
return m
case []any:
// out 保存out,供当前处理流程使用
out := make([]any, len(x))
// i、e 表示当前遍历过程中的i、e
for i, e := range x {
out[i] = normalizeForJSON(e)
}
@@ -78,7 +92,8 @@ func normalizeForJSON(v any) any {
// keyToString 将非字符串 map 键转换为 JSON 对象键。
func keyToString(k any) string {
switch x := k.(type) {
switch // x 保存x,供当前处理流程使用
x := k.(type) {
case string:
return x
case int64:
+90 -7
View File
@@ -18,6 +18,7 @@ func mp(b ...byte) string { return b64(b) }
// TestMessagePack_DecodePrimitives 覆盖 msgpack 各原生类型的解码。
func TestMessagePack_DecodePrimitives(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
raw []byte
@@ -56,9 +57,12 @@ func TestMessagePack_DecodePrimitives(t *testing.T) {
{"bin16", append([]byte{0xc5, 0x00, 0x03}, []byte("xyz")...), []byte("xyz")},
{"bin32", append([]byte{0xc6, 0x00, 0x00, 0x00, 0x03}, []byte("xyz")...), []byte("xyz")},
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: tc.raw}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("decodeValue() err: %v", err)
@@ -73,11 +77,14 @@ func TestMessagePack_DecodePrimitives(t *testing.T) {
// TestMessagePack_DecodeArrays 覆盖 fixarray / array16 / array32 与嵌套数组。
func TestMessagePack_DecodeArrays(t *testing.T) {
t.Run("fixarray empty", func(t *testing.T) {
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: []byte{0x90}}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := []any{}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v, want %#v", got, want)
@@ -85,11 +92,14 @@ func TestMessagePack_DecodeArrays(t *testing.T) {
})
t.Run("fixarray mixed types", func(t *testing.T) {
// [1, "a", true, nil]
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: []byte{0x94, 0x01, 0xa1, 'a', 0xc3, 0xc0}}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := []any{int64(1), "a", true, nil}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v, want %#v", got, want)
@@ -97,11 +107,14 @@ func TestMessagePack_DecodeArrays(t *testing.T) {
})
t.Run("array16", func(t *testing.T) {
// array16 with 2 elements: [1, 2]
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: []byte{0xdc, 0x00, 0x02, 0x01, 0x02}}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := []any{int64(1), int64(2)}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v, want %#v", got, want)
@@ -109,11 +122,14 @@ func TestMessagePack_DecodeArrays(t *testing.T) {
})
t.Run("array32", func(t *testing.T) {
// array32 with 2 elements: [1, 2]
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: []byte{0xdd, 0x00, 0x00, 0x00, 0x02, 0x01, 0x02}}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := []any{int64(1), int64(2)}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v, want %#v", got, want)
@@ -121,11 +137,14 @@ func TestMessagePack_DecodeArrays(t *testing.T) {
})
t.Run("nested arrays", func(t *testing.T) {
// [[1, 2], [3, 4]]
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: []byte{0x92, 0x92, 0x01, 0x02, 0x92, 0x03, 0x04}}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := []any{[]any{int64(1), int64(2)}, []any{int64(3), int64(4)}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v, want %#v", got, want)
@@ -136,11 +155,14 @@ func TestMessagePack_DecodeArrays(t *testing.T) {
// TestMessagePack_DecodeMaps 覆盖 fixmap / map16 / map32 及嵌套 map。
func TestMessagePack_DecodeMaps(t *testing.T) {
t.Run("fixmap empty", func(t *testing.T) {
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: []byte{0x80}}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := map[any]any{}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v, want %#v", got, want)
@@ -148,11 +170,14 @@ func TestMessagePack_DecodeMaps(t *testing.T) {
})
t.Run("fixmap string keys", func(t *testing.T) {
// {"a": 1, "b": 2}
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: []byte{0x82, 0xa1, 'a', 0x01, 0xa1, 'b', 0x02}}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := map[any]any{"a": int64(1), "b": int64(2)}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v, want %#v", got, want)
@@ -160,11 +185,14 @@ func TestMessagePack_DecodeMaps(t *testing.T) {
})
t.Run("fixmap integer keys", func(t *testing.T) {
// {1: "a", 2: "b"}
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: []byte{0x82, 0x01, 0xa1, 'a', 0x02, 0xa1, 'b'}}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := map[any]any{int64(1): "a", int64(2): "b"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v, want %#v", got, want)
@@ -172,11 +200,14 @@ func TestMessagePack_DecodeMaps(t *testing.T) {
})
t.Run("map16", func(t *testing.T) {
// map16 with 1 pair: {"k": 1}
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: []byte{0xde, 0x00, 0x01, 0xa1, 'k', 0x01}}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := map[any]any{"k": int64(1)}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v, want %#v", got, want)
@@ -184,11 +215,14 @@ func TestMessagePack_DecodeMaps(t *testing.T) {
})
t.Run("map32", func(t *testing.T) {
// map32 with 1 pair: {"k": 1}
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: []byte{0xdf, 0x00, 0x00, 0x00, 0x01, 0xa1, 'k', 0x01}}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := map[any]any{"k": int64(1)}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %#v, want %#v", got, want)
@@ -196,16 +230,20 @@ func TestMessagePack_DecodeMaps(t *testing.T) {
})
t.Run("nested map and array", func(t *testing.T) {
// {"arr": [1, 2], "obj": {"k": "v"}}
// raw 保存原始,供当前处理流程使用
raw := []byte{
0x82,
0xa3, 'a', 'r', 'r', 0x92, 0x01, 0x02,
0xa3, 'o', 'b', 'j', 0x81, 0xa1, 'k', 0xa1, 'v',
}
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: raw}
// got、err 保存got、err,供当前处理流程使用
got, err := d.decodeValue()
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := map[any]any{
"arr": []any{int64(1), int64(2)},
"obj": map[any]any{"k": "v"},
@@ -218,6 +256,7 @@ func TestMessagePack_DecodeMaps(t *testing.T) {
// TestMessagePack_Errors 覆盖解码错误路径:截断、未知格式字节。
func TestMessagePack_Errors(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
raw []byte
@@ -253,9 +292,12 @@ func TestMessagePack_Errors(t *testing.T) {
{"truncated map value", []byte{0x81, 0xa1, 'k'}},
{"truncated map key", []byte{0x81}},
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// d 保存d,供当前处理流程使用
d := &msgpackDecoder{data: tc.raw}
// err 保存err,供当前处理流程使用
_, err := d.decodeValue()
if err == nil {
t.Fatal("expected error")
@@ -267,6 +309,7 @@ func TestMessagePack_Errors(t *testing.T) {
// TestDecrypt_Types 端到端覆盖 Decrypt 对各 msgpack 类型的 JSON 归一化输出。
func TestDecrypt_Types(t *testing.T) {
t.Run("nil", func(t *testing.T) {
// got、err 保存got、err,供当前处理流程使用
got, err := Decrypt(mp(0xc0))
if err != nil {
t.Fatalf("err: %v", err)
@@ -276,6 +319,7 @@ func TestDecrypt_Types(t *testing.T) {
}
})
t.Run("bool true", func(t *testing.T) {
// got、err 保存got、err,供当前处理流程使用
got, err := Decrypt(mp(0xc3))
if err != nil {
t.Fatalf("err: %v", err)
@@ -286,10 +330,12 @@ func TestDecrypt_Types(t *testing.T) {
})
t.Run("integer key map", func(t *testing.T) {
// {1: "a"} → {"1":"a"}
// got、err 保存got、err,供当前处理流程使用
got, err := Decrypt(mp(0x81, 0x01, 0xa1, 'a'))
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := `{"1":"a"}`
if got != want {
t.Fatalf("got %q, want %q", got, want)
@@ -297,21 +343,25 @@ func TestDecrypt_Types(t *testing.T) {
})
t.Run("nested map array", func(t *testing.T) {
// {"arr":[1,2],"obj":{"k":"v"}}
// raw 保存原始,供当前处理流程使用
raw := []byte{
0x82,
0xa3, 'a', 'r', 'r', 0x92, 0x01, 0x02,
0xa3, 'o', 'b', 'j', 0x81, 0xa1, 'k', 0xa1, 'v',
}
// got、err 保存got、err,供当前处理流程使用
got, err := Decrypt(mp(raw...))
if err != nil {
t.Fatalf("err: %v", err)
}
// JSON 结构比对(顺序无关)。
var gv, wv any
if err := json.Unmarshal([]byte(got), &gv); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(got), &gv); err != nil {
t.Fatalf("unmarshal got: %v", err)
}
if err := json.Unmarshal([]byte(`{"arr":[1,2],"obj":{"k":"v"}}`), &wv); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(`{"arr":[1,2],"obj":{"k":"v"}}`), &wv); err != nil {
t.Fatalf("unmarshal want: %v", err)
}
if !reflect.DeepEqual(gv, wv) {
@@ -320,10 +370,12 @@ func TestDecrypt_Types(t *testing.T) {
})
t.Run("bin to utf8 string", func(t *testing.T) {
// bin8 of "hello"
// got、err 保存got、err,供当前处理流程使用
got, err := Decrypt(mp(append([]byte{0xc4, 0x05}, []byte("hello")...)...))
if err != nil {
t.Fatalf("err: %v", err)
}
// want 保存want,供当前处理流程使用
want := `"hello"`
if got != want {
t.Fatalf("got %q, want %q", got, want)
@@ -331,6 +383,7 @@ func TestDecrypt_Types(t *testing.T) {
})
t.Run("bin with invalid utf8 dropped", func(t *testing.T) {
// bin8 with 0xff (invalid utf8 lead byte) → ToValidUTF8 drops it.
// got、err 保存got、err,供当前处理流程使用
got, err := Decrypt(mp(0xc4, 0x02, 0xff, 0x41))
if err != nil {
t.Fatalf("err: %v", err)
@@ -341,16 +394,21 @@ func TestDecrypt_Types(t *testing.T) {
}
})
t.Run("float64", func(t *testing.T) {
// bits 保存bits,供当前处理流程使用
bits := math.Float64bits(3.14)
// buf 保存buf,供当前处理流程使用
buf := make([]byte, 9)
buf[0] = 0xcb
binary.BigEndian.PutUint64(buf[1:], bits)
// got、err 保存got、err,供当前处理流程使用
got, err := Decrypt(mp(buf...))
if err != nil {
t.Fatalf("err: %v", err)
}
// g 保存g,供当前处理流程使用
var g float64
if err := json.Unmarshal([]byte(got), &g); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(got), &g); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if g != 3.14 {
@@ -363,7 +421,9 @@ func TestDecrypt_Types(t *testing.T) {
func TestDecrypt_Base64Padding(t *testing.T) {
// msgpack fixstr "hij" → 字节 0xa3 'h' 'i' 'j',再 base64 编码。
// 4 字节输入 → base64 输出 8 字符(含 1 个 '=' padding)。
// full 保存full,供当前处理流程使用
full := b64([]byte{0xa3, 'h', 'i', 'j'})
// trimmed 保存trimmed,供当前处理流程使用
trimmed := strings.TrimRight(full, "=")
// 去掉 padding 后长度模 4 ≠ 0,应触发补齐逻辑并解码成功。
got, err := Decrypt(trimmed)
@@ -423,6 +483,7 @@ func TestDecrypt_Errors(t *testing.T) {
// TestNormalizeForJSON 覆盖 normalizeForJSON 的各分支。
func TestNormalizeForJSON(t *testing.T) {
t.Run("map[any]any with mixed keys", func(t *testing.T) {
// in 保存in,供当前处理流程使用
in := map[any]any{
"str": "v",
int64(2): int64(3),
@@ -431,7 +492,9 @@ func TestNormalizeForJSON(t *testing.T) {
nil: "n",
float64(1.5): "f",
}
// out 保存out,供当前处理流程使用
out := normalizeForJSON(in)
// m、ok 保存m、ok,供当前处理流程使用
m, ok := out.(map[string]any)
if !ok {
t.Fatalf("expected map[string]any, got %T", out)
@@ -444,8 +507,11 @@ func TestNormalizeForJSON(t *testing.T) {
}
})
t.Run("nested []any", func(t *testing.T) {
// in 保存in,供当前处理流程使用
in := []any{int64(1), []any{int64(2), "x"}}
// out 保存out,供当前处理流程使用
out := normalizeForJSON(in)
// arr、ok 保存arr、ok,供当前处理流程使用
arr, ok := out.([]any)
if !ok {
t.Fatalf("expected []any, got %T", out)
@@ -453,28 +519,37 @@ func TestNormalizeForJSON(t *testing.T) {
if arr[0] != int64(1) {
t.Fatalf("arr[0] = %#v", arr[0])
}
if inner, ok := arr[1].([]any); !ok || inner[0] != int64(2) || inner[1] != "x" {
if // inner、ok 保存inner、ok,供当前处理流程使用
inner, ok := arr[1].([]any); !ok || inner[0] != int64(2) || inner[1] != "x" {
t.Fatalf("arr[1] = %#v", arr[1])
}
})
t.Run("[]byte normalized to valid utf8", func(t *testing.T) {
// in 保存in,供当前处理流程使用
in := []byte{0x41, 0xff, 0x42} // 'A', invalid, 'B'
// out 保存out,供当前处理流程使用
out := normalizeForJSON(in)
if out != "AB" {
t.Fatalf("got %q, want %q", out, "AB")
}
})
t.Run("scalar passthrough", func(t *testing.T) {
// in 表示当前遍历过程中的in
for _, in := range []any{int64(1), uint64(2), float64(3.5), "s", true, nil} {
if out := normalizeForJSON(in); out != in {
if // out 保存out,供当前处理流程使用
out := normalizeForJSON(in); out != in {
t.Fatalf("normalizeForJSON(%#v) = %#v, want passthrough", in, out)
}
}
})
t.Run("map[any]any with unknown key type falls to default", func(t *testing.T) {
// custom 保存custom,供当前处理流程使用
type custom struct{ X int }
// in 保存in,供当前处理流程使用
in := map[any]any{custom{1}: "v"}
// out 保存out,供当前处理流程使用
out := normalizeForJSON(in)
// m、ok 保存m、ok,供当前处理流程使用
m, ok := out.(map[string]any)
if !ok {
t.Fatalf("expected map[string]any, got %T", out)
@@ -487,6 +562,7 @@ func TestNormalizeForJSON(t *testing.T) {
// TestKeyToString 覆盖 keyToString 的各类型分支。
func TestKeyToString(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
in any
@@ -502,15 +578,19 @@ func TestKeyToString(t *testing.T) {
{"bytes valid utf8", []byte("hello"), "hello"},
{"bytes invalid utf8", []byte{0xff, 0x41}, "A"},
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := keyToString(tc.in); got != tc.want {
if // got 保存got,供当前处理流程使用
got := keyToString(tc.in); got != tc.want {
t.Fatalf("keyToString(%#v) = %q, want %q", tc.in, got, tc.want)
}
})
}
t.Run("default fallback", func(t *testing.T) {
// custom 保存custom,供当前处理流程使用
type custom struct{ X int }
// got 保存got,供当前处理流程使用
got := keyToString(custom{X: 7})
if got == "" {
t.Fatal("expected non-empty default fallback")
@@ -524,6 +604,7 @@ func TestKeyToString(t *testing.T) {
// TestStripNonASCII 覆盖 stripNonASCII 行为。
func TestStripNonASCII(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
in string
@@ -537,9 +618,11 @@ func TestStripNonASCII(t *testing.T) {
{"del 0x7f kept", "a\x7fb", "a\x7fb"},
{"0x80 stripped", "a\x80b", "ab"},
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := stripNonASCII(tc.in); got != tc.want {
if // got 保存got,供当前处理流程使用
got := stripNonASCII(tc.in); got != tc.want {
t.Fatalf("stripNonASCII(%q) = %q, want %q", tc.in, got, tc.want)
}
})
+31 -4
View File
@@ -8,15 +8,21 @@ import (
"testing"
)
// sampleB64 保存sampleB64,供当前处理流程使用
//
//go:embed testdata/sample.b64
var sampleB64 string
// expectedDecrypt 保存expectedDecrypt,供当前处理流程使用
//
//go:embed testdata/expected_decrypt.json
var expectedDecrypt string
// TestGenerateSign_Golden 锁定签名结果。
func TestGenerateSign_Golden(t *testing.T) {
// got 保存got,供当前处理流程使用
got := GenerateSign("1700000000000", "abc_token", `{"appKey":"x"}`)
// want 保存want,供当前处理流程使用
want := "497ff18ef9c6d4792ba5aeef0e99929a"
if got != want {
t.Fatalf("sign mismatch:\n got %s\nwant %s", got, want)
@@ -25,21 +31,29 @@ func TestGenerateSign_Golden(t *testing.T) {
// TestDecrypt_Golden 用真实抓包样本锁定解密输出。
// 比较方式:两侧都按 JSON 解析(UseNumber 保留整数精度),reflect.DeepEqual 结构相等。
// TestDecrypt_Golden 负责TestDecryptGolden相关处理。
func TestDecrypt_Golden(t *testing.T) {
// got、err 保存got、err,供当前处理流程使用
got, err := Decrypt(strings.TrimSpace(sampleB64))
if err != nil {
t.Fatalf("Decrypt failed: %v", err)
}
// gotV 保存gotV,供当前处理流程使用
gotV := mustParseJSONUseNumber(t, got)
// wantV 保存wantV,供当前处理流程使用
wantV := mustParseJSONUseNumber(t, strings.TrimSpace(expectedDecrypt))
if !reflect.DeepEqual(gotV, wantV) {
// gj 保存gj,供当前处理流程使用
gj, _ := json.MarshalIndent(gotV, "", " ")
// wj 保存wj,供当前处理流程使用
wj, _ := json.MarshalIndent(wantV, "", " ")
t.Fatalf("decrypt mismatch:\n--- got ---\n%s\n--- want ---\n%s", gj, wj)
}
}
// TestMessagePackSignedIntegers 负责Test消息PackSignedIntegers相关处理。
func TestMessagePackSignedIntegers(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
raw []byte
@@ -51,9 +65,12 @@ func TestMessagePackSignedIntegers(t *testing.T) {
{"int32", []byte{0xd2, 0xff, 0xff, 0xff, 0xfd}, -3},
{"int64", []byte{0xd3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc}, -4},
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// decoder 保存decoder,供当前处理流程使用
decoder := &msgpackDecoder{data: tc.raw}
// got、err 保存got、err,供当前处理流程使用
got, err := decoder.decodeValue()
if err != nil || got != tc.want {
t.Fatalf("decodeValue() = %#v, %v; want %d", got, err, tc.want)
@@ -62,25 +79,33 @@ func TestMessagePackSignedIntegers(t *testing.T) {
}
}
// TestGeneratedIdentifiers 负责TestGeneratedIdentifiers相关处理。
func TestGeneratedIdentifiers(t *testing.T) {
if mid := GenerateMid(); !strings.HasSuffix(mid, " 0") {
if // mid 保存mid,供当前处理流程使用
mid := GenerateMid(); !strings.HasSuffix(mid, " 0") {
t.Fatalf("invalid mid: %q", mid)
}
if uuid := GenerateUUID(); !strings.HasPrefix(uuid, "-") || !strings.HasSuffix(uuid, "1") {
if // uuid 保存uuid,供当前处理流程使用
uuid := GenerateUUID(); !strings.HasPrefix(uuid, "-") || !strings.HasSuffix(uuid, "1") {
t.Fatalf("invalid uuid: %q", uuid)
}
// deviceID 保存deviceID,供当前处理流程使用
deviceID := GenerateDeviceID("123")
if len(deviceID) != 40 || !strings.HasSuffix(deviceID, "-123") || deviceID[14] != '4' {
t.Fatalf("invalid device ID: %q", deviceID)
}
}
// mustParseJSONUseNumber 负责mustParseJSONUseNumber相关处理。
func mustParseJSONUseNumber(t *testing.T, s string) any {
t.Helper()
// dec 保存dec,供当前处理流程使用
dec := json.NewDecoder(strings.NewReader(s))
dec.UseNumber()
// v 保存v,供当前处理流程使用
var v any
if err := dec.Decode(&v); err != nil {
if // err 保存err,供当前处理流程使用
err := dec.Decode(&v); err != nil {
t.Fatalf("parse json: %v", err)
}
return v
@@ -88,11 +113,13 @@ func mustParseJSONUseNumber(t *testing.T, s string) any {
// TestTransCookies 基本解析。
func TestTransCookies(t *testing.T) {
// c 保存c,供当前处理流程使用
c := TransCookies("a=1; b=2; _m_h5_tk=tokenpart_123")
if c["a"] != "1" || c["b"] != "2" {
t.Fatalf("unexpected: %v", c)
}
if got := SignToken("a=1; _m_h5_tk=tokenpart_123"); got != "tokenpart" {
if // got 保存got,供当前处理流程使用
got := SignToken("a=1; _m_h5_tk=tokenpart_123"); got != "tokenpart" {
t.Fatalf("SignToken = %q, want tokenpart", got)
}
}
+41 -2
View File
@@ -9,30 +9,37 @@ import (
// msgpackDecoder 解析闲鱼消息使用的 MessagePack 数据。
// 解码结果类型:int64/uint64/float64/string/bool/nil/[]byte/[]any/map[any]any。
// bin 解码为 []byte,map 键保留原类型(整数键为 int64)。
// msgpackDecoder 保存msgpackDecoder,供当前处理流程使用
type msgpackDecoder struct {
data []byte
pos int
}
// readByte 负责readByte相关处理。
func (d *msgpackDecoder) readByte() (byte, error) {
if d.pos >= len(d.data) {
return 0, fmt.Errorf("msgpack: unexpected end of data")
}
// b 保存b,供当前处理流程使用
b := d.data[d.pos]
d.pos++
return b, nil
}
// readBytes 负责readBytes相关处理。
func (d *msgpackDecoder) readBytes(n int) ([]byte, error) {
if d.pos+n > len(d.data) {
return nil, fmt.Errorf("msgpack: unexpected end of data")
}
// r 保存r,供当前处理流程使用
r := d.data[d.pos : d.pos+n]
d.pos += n
return r, nil
}
// decodeValue 负责decode值相关处理。
func (d *msgpackDecoder) decodeValue() (any, error) {
// fb、err 保存fb、err,供当前处理流程使用
fb, err := d.readByte()
if err != nil {
return nil, err
@@ -59,116 +66,137 @@ func (d *msgpackDecoder) decodeValue() (any, error) {
case 0xc3:
return true, nil
case 0xc4: // bin 8
// n、err 保存n、err,供当前处理流程使用
n, err := d.readByte()
if err != nil {
return nil, err
}
return d.readBytes(int(n))
case 0xc5: // bin 16
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(2)
if err != nil {
return nil, err
}
return d.readBytes(int(binary.BigEndian.Uint16(b)))
case 0xc6: // bin 32
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(4)
if err != nil {
return nil, err
}
return d.readBytes(int(binary.BigEndian.Uint32(b)))
case 0xca: // float 32
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(4)
if err != nil {
return nil, err
}
// bits 保存bits,供当前处理流程使用
bits := binary.BigEndian.Uint32(b)
return float64(math.Float32frombits(bits)), nil
case 0xcb: // float 64
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(8)
if err != nil {
return nil, err
}
return math.Float64frombits(binary.BigEndian.Uint64(b)), nil
case 0xcc: // uint 8
// n、err 保存n、err,供当前处理流程使用
n, err := d.readByte()
return uint64(n), err
case 0xcd: // uint 16
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(2)
if err != nil {
return nil, err
}
return uint64(binary.BigEndian.Uint16(b)), nil
case 0xce: // uint 32
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(4)
if err != nil {
return nil, err
}
return uint64(binary.BigEndian.Uint32(b)), nil
case 0xcf: // uint 64
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(8)
if err != nil {
return nil, err
}
return binary.BigEndian.Uint64(b), nil
case 0xd0: // int 8
// n、err 保存n、err,供当前处理流程使用
n, err := d.readByte()
// #nosec G115 -- MessagePack 有符号整数使用二进制补码编码,此转换用于符号扩展。
return int64(int8(n)), err
case 0xd1: // int 16
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(2)
if err != nil {
return nil, err
}
return int64(int16(binary.BigEndian.Uint16(b))), nil // #nosec G115 -- 协议要求的符号扩展
case 0xd2: // int 32
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(4)
if err != nil {
return nil, err
}
return int64(int32(binary.BigEndian.Uint32(b))), nil // #nosec G115 -- 协议要求的符号扩展
case 0xd3: // int 64
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(8)
if err != nil {
return nil, err
}
return int64(binary.BigEndian.Uint64(b)), nil // #nosec G115 -- 协议要求的符号扩展
case 0xd9: // str 8
// n、err 保存n、err,供当前处理流程使用
n, err := d.readByte()
if err != nil {
return nil, err
}
return d.readString(int(n))
case 0xda: // str 16
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(2)
if err != nil {
return nil, err
}
return d.readString(int(binary.BigEndian.Uint16(b)))
case 0xdb: // str 32
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(4)
if err != nil {
return nil, err
}
return d.readString(int(binary.BigEndian.Uint32(b)))
case 0xdc: // array 16
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(2)
if err != nil {
return nil, err
}
return d.decodeArray(int(binary.BigEndian.Uint16(b)))
case 0xdd: // array 32
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(4)
if err != nil {
return nil, err
}
return d.decodeArray(int(binary.BigEndian.Uint32(b)))
case 0xde: // map 16
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(2)
if err != nil {
return nil, err
}
return d.decodeMap(int(binary.BigEndian.Uint16(b)))
case 0xdf: // map 32
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(4)
if err != nil {
return nil, err
@@ -183,7 +211,9 @@ func (d *msgpackDecoder) decodeValue() (any, error) {
return nil, fmt.Errorf("msgpack: unknown format byte 0x%02x", fb)
}
// readString 负责readString相关处理。
func (d *msgpackDecoder) readString(n int) (string, error) {
// b、err 保存b、err,供当前处理流程使用
b, err := d.readBytes(n)
if err != nil {
return "", err
@@ -191,9 +221,13 @@ func (d *msgpackDecoder) readString(n int) (string, error) {
return string(b), nil // UTF-8
}
// decodeArray 负责decodeArray相关处理。
func (d *msgpackDecoder) decodeArray(n int) (any, error) {
// arr 保存arr,供当前处理流程使用
arr := make([]any, n)
for i := 0; i < n; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < n; i++ {
// v、err 保存v、err,供当前处理流程使用
v, err := d.decodeValue()
if err != nil {
return nil, err
@@ -203,13 +237,18 @@ func (d *msgpackDecoder) decodeArray(n int) (any, error) {
return arr, nil
}
// decodeMap 负责decodeMap相关处理。
func (d *msgpackDecoder) decodeMap(n int) (any, error) {
// m 保存m,供当前处理流程使用
m := make(map[any]any, n)
for i := 0; i < n; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < n; i++ {
// k、err 保存k、err,供当前处理流程使用
k, err := d.decodeValue()
if err != nil {
return nil, err
}
// v、err 保存v、err,供当前处理流程使用
v, err := d.decodeValue()
if err != nil {
return nil, err
+10 -1
View File
@@ -15,6 +15,7 @@ const SignAppKey = "34839810"
// GenerateSign 生成 mtop API 签名:MD5(token + "&" + t + "&" + appKey + "&" + data)。
func GenerateSign(t, token, data string) string {
// msg 保存msg,供当前处理流程使用
msg := token + "&" + t + "&" + SignAppKey + "&" + data
// #nosec G401 -- MTOP 协议明确要求 MD5,不能替换为其他摘要算法。
sum := md5.Sum([]byte(msg))
@@ -23,7 +24,9 @@ func GenerateSign(t, token, data string) string {
// GenerateMid 生成非密码学用途的消息 ID,形如 "<0-999随机><毫秒时间戳> 0"。
func GenerateMid() string {
// randomPart 保存randomPart,供当前处理流程使用
randomPart := randomInt(1000)
// ts 保存ts,供当前处理流程使用
ts := time.Now().UnixMilli()
return fmt.Sprintf("%d%d 0", randomPart, ts)
}
@@ -33,13 +36,17 @@ func GenerateUUID() string {
return fmt.Sprintf("-%d1", time.Now().UnixMilli())
}
// deviceIDChars 保存deviceIDChars,供当前处理流程使用
const deviceIDChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// GenerateDeviceID 生成设备 ID:36 位 UUID 格式(位置 8/13/18/23 为 "-",14 为 "4",
// 19 取 (rand&0x3)|0x8),末尾追加 "-<userID>"。
// GenerateDeviceID 负责GenerateDeviceID相关处理。
func GenerateDeviceID(userID string) string {
// result 保存结果,供当前处理流程使用
result := make([]byte, 36)
for i := 0; i < 36; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < 36; i++ {
switch i {
case 8, 13, 18, 23:
result[i] = '-'
@@ -54,6 +61,7 @@ func GenerateDeviceID(userID string) string {
return string(result) + "-" + userID
}
// randomFallback 保存randomFallback,供当前处理流程使用
var randomFallback atomic.Uint64
// randomInt 返回 [0,max) 的密码学随机数;系统熵源异常时使用进程内单调计数兜底。
@@ -61,6 +69,7 @@ func randomInt(max int) int {
if max <= 1 {
return 0
}
// n、err 保存n、err,供当前处理流程使用
n, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
if err == nil {
return int(n.Int64())
+32 -4
View File
@@ -9,7 +9,9 @@ import (
// TestGenerateSign 表驱动覆盖 GenerateSign 的边界输入。
// GenerateSign 是纯函数(MD5(token+"&"+t+"&"+SignAppKey+"&"+data)),结果应稳定可复现。
// TestGenerateSign 负责TestGenerateSign相关处理。
func TestGenerateSign(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
name string
t string
@@ -23,15 +25,19 @@ func TestGenerateSign(t *testing.T) {
{"unicode", "1700000000000", "中文token", `{"msg":"你好世界"}`},
{"long string", "1700000000000", strings.Repeat("a", 10_000), strings.Repeat("x", 10_000)},
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// got 保存got,供当前处理流程使用
got := GenerateSign(tc.t, tc.token, tc.data)
if len(got) != 32 {
t.Fatalf("GenerateSign length = %d, want 32 (md5 hex)", len(got))
}
// 与独立计算的期望值比对,锁定拼接顺序与算法。
msg := tc.token + "&" + tc.t + "&" + SignAppKey + "&" + tc.data
// sum 保存sum,供当前处理流程使用
sum := md5.Sum([]byte(msg))
// want 保存want,供当前处理流程使用
want := hex.EncodeToString(sum[:])
if got != want {
t.Fatalf("GenerateSign = %q, want %q", got, want)
@@ -48,7 +54,9 @@ func TestGenerateSign(t *testing.T) {
// TestGenerateSign_Deterministic 相同输入两次调用结果一致。
func TestGenerateSign_Deterministic(t *testing.T) {
// a 保存a,供当前处理流程使用
a := GenerateSign("1", "2", "3")
// b 保存b,供当前处理流程使用
b := GenerateSign("1", "2", "3")
if a != b {
t.Fatalf("GenerateSign not deterministic: %s != %s", a, b)
@@ -57,10 +65,12 @@ func TestGenerateSign_Deterministic(t *testing.T) {
// TestGenerateMid_Format 校验 Mid 的格式与字符集。
func TestGenerateMid_Format(t *testing.T) {
// mid 保存mid,供当前处理流程使用
mid := GenerateMid()
if !strings.HasSuffix(mid, " 0") {
t.Fatalf("mid should end with \" 0\", got %q", mid)
}
// body 保存请求体,供当前处理流程使用
body := strings.TrimSuffix(mid, " 0")
// body = "<0-999 随机数><毫秒时间戳>",全部应为十进制数字。
for _, r := range body {
@@ -76,8 +86,10 @@ func TestGenerateMid_Format(t *testing.T) {
// TestGenerateMid_Uniqueness 多次调用应产生不同输出(时间戳/随机量不同)。
func TestGenerateMid_Uniqueness(t *testing.T) {
// seen 保存seen,供当前处理流程使用
seen := make(map[string]struct{}, 100)
for i := 0; i < 100; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < 100; i++ {
seen[GenerateMid()] = struct{}{}
}
// 至少应有 2 个不同值(极端情况下时间戳/随机数都碰撞的概率可忽略)。
@@ -88,11 +100,14 @@ func TestGenerateMid_Uniqueness(t *testing.T) {
// TestGenerateUUID_Format 校验 UUID 形如 "-<毫秒>1"。
func TestGenerateUUID_Format(t *testing.T) {
// u 保存u,供当前处理流程使用
u := GenerateUUID()
if !strings.HasPrefix(u, "-") || !strings.HasSuffix(u, "1") {
t.Fatalf("invalid uuid: %q", u)
}
// body 保存请求体,供当前处理流程使用
body := strings.TrimSuffix(strings.TrimPrefix(u, "-"), "1")
// r 表示当前遍历过程中的r
for _, r := range body {
if r < '0' || r > '9' {
t.Fatalf("uuid body should be all digits, got %q in %q", r, u)
@@ -102,9 +117,12 @@ func TestGenerateUUID_Format(t *testing.T) {
// TestGenerateDeviceID_Format 校验设备 ID 的固定位置约束。
func TestGenerateDeviceID_Format(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []string{"123", "", "user-with-dash", "中文用户", strings.Repeat("u", 100)}
// userID 表示当前遍历过程中的用户ID
for _, userID := range cases {
t.Run(userID, func(t *testing.T) {
// id 保存标识,供当前处理流程使用
id := GenerateDeviceID(userID)
// 36 字符 UUID + "-" + userID。
wantLen := 36 + 1 + len(userID)
@@ -114,6 +132,7 @@ func TestGenerateDeviceID_Format(t *testing.T) {
if !strings.HasSuffix(id, "-"+userID) {
t.Fatalf("device ID should end with -userID, got %q", id)
}
// uuid 保存uuid,供当前处理流程使用
uuid := id[:36]
// 固定分隔符位置。
for _, pos := range []int{8, 13, 18, 23} {
@@ -133,6 +152,7 @@ func TestGenerateDeviceID_Format(t *testing.T) {
}
// 其余字符取自 deviceIDChars 字符集。
const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"
// i、r 表示当前遍历过程中的i、r
for i, r := range uuid {
if !strings.ContainsRune(chars, r) {
t.Fatalf("device ID pos %d = %q not in allowed charset (id=%q)", i, r, id)
@@ -144,8 +164,10 @@ func TestGenerateDeviceID_Format(t *testing.T) {
// TestGenerateDeviceID_Uniqueness 不同调用产生不同设备 ID(随机位差异)。
func TestGenerateDeviceID_Uniqueness(t *testing.T) {
// seen 保存seen,供当前处理流程使用
seen := make(map[string]struct{}, 50)
for i := 0; i < 50; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < 50; i++ {
seen[GenerateDeviceID("u")] = struct{}{}
}
if len(seen) < 2 {
@@ -155,7 +177,9 @@ func TestGenerateDeviceID_Uniqueness(t *testing.T) {
// TestGenerateDeviceID_DifferentUsers 不同 userID 产生不同后缀。
func TestGenerateDeviceID_DifferentUsers(t *testing.T) {
// a 保存a,供当前处理流程使用
a := GenerateDeviceID("alice")
// b 保存b,供当前处理流程使用
b := GenerateDeviceID("bob")
if strings.HasSuffix(a, "-bob") || strings.HasSuffix(b, "-alice") {
t.Fatalf("device ID suffix mismatched: a=%q b=%q", a, b)
@@ -164,12 +188,16 @@ func TestGenerateDeviceID_DifferentUsers(t *testing.T) {
// TestRandomInt_Bounds 覆盖 randomInt 的边界:max<=1 恒返回 0;正常区间值合法。
func TestRandomInt_Bounds(t *testing.T) {
// max 表示当前遍历过程中的max
for _, max := range []int{0, 1, -5} {
if got := randomInt(max); got != 0 {
if // got 保存got,供当前处理流程使用
got := randomInt(max); got != 0 {
t.Fatalf("randomInt(%d) = %d, want 0", max, got)
}
}
for i := 0; i < 1000; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < 1000; i++ {
// got 保存got,供当前处理流程使用
got := randomInt(16)
if got < 0 || got >= 16 {
t.Fatalf("randomInt(16) = %d, out of [0,16)", got)
+159 -20
View File
@@ -28,6 +28,7 @@ import (
xrenew "xianyu-go/internal/xianyu/renew"
)
// maxQRResponseBytes 保存maxQR响应Bytes,供当前处理流程使用
const (
maxQRResponseBytes = 2 << 20
qrPollInterval = 2 * time.Second
@@ -35,6 +36,7 @@ const (
qrTopSite = "https://goofish.com"
)
// host 保存host,供当前处理流程使用
const (
host = "https://passport.goofish.com"
apiMiniLogin = host + "/mini_login.htm"
@@ -45,8 +47,10 @@ const (
appKey = "34839810"
)
// qrVerifyTargetURL 保存qrVerifyTargetURL,供当前处理流程使用
var qrVerifyTargetURL = "https://www.goofish.com/im"
// qrHeaders 保存qrHeaders,供当前处理流程使用
var qrHeaders = map[string]string{
"Accept": "application/json, text/plain, */*",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
@@ -77,12 +81,14 @@ type Session struct {
faceQRContent string // 人脸验证二维码原始内容,便于排查协议变化
}
// isExpired 负责isExpired相关处理。
func (s *Session) isExpired() bool {
s.mu.RLock()
defer s.mu.RUnlock()
return time.Since(s.createdTime) > s.expireTime
}
// sessionSnapshot 保存会话Snapshot,供当前处理流程使用
type sessionSnapshot struct {
status string
cookies map[string]string
@@ -96,6 +102,7 @@ type sessionSnapshot struct {
createdTime time.Time
}
// snapshot 负责snapshot相关处理。
func (s *Session) snapshot() sessionSnapshot {
s.mu.RLock()
defer s.mu.RUnlock()
@@ -134,6 +141,7 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
if err != nil {
return "", "", fmt.Errorf("生成扫码会话 ID: %w", err)
}
// sess 保存sess,供当前处理流程使用
sess := &Session{
SessionID: sessionID,
Status: "waiting",
@@ -157,27 +165,33 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
// 3. 生成二维码。
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, apiGenerateQR, nil)
// q 保存q,供当前处理流程使用
q := req.URL.Query()
// k、v 表示当前遍历过程中的k、v
for k, v := range loginParams {
q.Set(k, v)
}
req.URL.RawQuery = q.Encode()
m.setHeaders(req)
if cookieStr := sessionCookieHeader(sess, req.URL.String()); cookieStr != "" {
if // cookieStr 保存登录凭证Str,供当前处理流程使用
cookieStr := sessionCookieHeader(sess, req.URL.String()); cookieStr != "" {
req.Header.Set("Cookie", cookieStr)
}
// resp、err 保存resp、err,供当前处理流程使用
resp, err := m.httpc.Do(req)
if err != nil {
return "", "", fmt.Errorf("请求二维码接口失败: %w", err)
}
defer resp.Body.Close()
absorbSessionResponse(sess, apiGenerateQR, resp)
// body、err 保存body、err,供当前处理流程使用
body, err := readQRBody(resp.Body)
if err != nil {
return "", "", err
}
// result 保存结果,供当前处理流程使用
var result struct {
Content struct {
Success bool `json:"success"`
@@ -188,7 +202,8 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
} `json:"data"`
} `json:"content"`
}
if err := json.Unmarshal(body, &result); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(body, &result); err != nil {
return "", "", fmt.Errorf("解析二维码响应失败: %w (body=%s)", err, truncate(string(body), 300))
}
if !result.Content.Success {
@@ -197,7 +212,8 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
// t 是毫秒时间戳数字,必须转成纯数字字符串(不能用科学计数法)。
var tStr string
switch tv := result.Content.Data.T.(type) {
switch // tv 保存tv,供当前处理流程使用
tv := result.Content.Data.T.(type) {
case float64:
tStr = strconv.FormatInt(int64(tv), 10)
case string:
@@ -215,7 +231,9 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
return "", "", fmt.Errorf("生成二维码失败: %w", err)
}
png.DisableBorder = false
// pngBytes 保存pngBytes,供当前处理流程使用
pngBytes, _ := png.PNG(256)
// pngBytes64 保存pngBytes64,供当前处理流程使用
pngBytes64 := base64.StdEncoding.EncodeToString(pngBytes)
qrCodeURL = "data:image/png;base64," + pngBytes64
@@ -228,6 +246,7 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
// 5. 扫码会话独立于生成二维码的 HTTP 请求,但受会话有效期约束。
// #nosec G118 -- 后台任务必须跨越原请求,且由超时上下文保证退出。
go func() {
// monitorCtx、cancel 保存monitorCtx、cancel,供当前处理流程使用
monitorCtx, cancel := context.WithTimeout(context.Background(), sess.snapshot().expireTime)
defer cancel()
m.monitorQRStatus(monitorCtx, sessionID)
@@ -240,6 +259,7 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
// GetSessionStatus 查询扫码状态。
func (m *Manager) GetSessionStatus(sessionID string) map[string]any {
m.mu.Lock()
// sess、ok 保存sess、ok,供当前处理流程使用
sess, ok := m.sessions[sessionID]
m.mu.Unlock()
if !ok {
@@ -249,6 +269,7 @@ func (m *Manager) GetSessionStatus(sessionID string) map[string]any {
if time.Since(sess.createdTime) > sess.expireTime && sess.Status != "success" {
sess.Status = "expired"
}
// snapshot 保存snapshot,供当前处理流程使用
snapshot := sessionSnapshot{
status: sess.Status, cookies: cloneCookieMap(sess.cookies), unb: sess.unb,
cookieSnapshot: cloneCookieSnapshot(sess.cookieSnapshot),
@@ -256,6 +277,7 @@ func (m *Manager) GetSessionStatus(sessionID string) map[string]any {
faceQRURL: sess.faceQRURL,
}
sess.mu.Unlock()
// result 保存结果,供当前处理流程使用
result := map[string]any{
"status": snapshot.status,
"session_id": sessionID,
@@ -294,14 +316,18 @@ func (m *Manager) DeleteSession(sessionID string) {
// monitorQRStatus 后台轮询扫码状态。
func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
m.mu.Lock()
// sess 保存sess,供当前处理流程使用
sess := m.sessions[sessionID]
m.mu.Unlock()
if sess == nil {
return
}
// maxWait 保存maxWait,供当前处理流程使用
maxWait := 5 * time.Minute
// start 保存开始,供当前处理流程使用
start := time.Now()
// serverErrors 保存server错误列表,供当前处理流程使用
serverErrors := 0
for time.Since(start) < maxWait {
@@ -312,12 +338,14 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
}
m.mu.Lock()
if _, ok := m.sessions[sessionID]; !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := m.sessions[sessionID]; !ok {
m.mu.Unlock()
return
}
m.mu.Unlock()
// resp、err 保存resp、err,供当前处理流程使用
resp, err := m.pollQRCodeStatus(ctx, sess)
if err != nil {
m.logger.Error("轮询扫码状态异常", "err", err)
@@ -327,7 +355,9 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
continue
}
absorbSessionResponse(sess, apiScanStatus, resp)
// body、readErr 保存body、readErr,供当前处理流程使用
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
// closeErr 保存closeErr,供当前处理流程使用
closeErr := resp.Body.Close()
if readErr != nil || closeErr != nil {
m.logger.Warn("读取扫码状态响应失败", "read_err", readErr, "close_err", closeErr)
@@ -337,6 +367,7 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
continue
}
// qrResult 保存qr结果,供当前处理流程使用
var qrResult struct {
HasError bool `json:"hasError"`
Content struct {
@@ -347,7 +378,8 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
} `json:"data"`
} `json:"content"`
}
if err := json.Unmarshal(body, &qrResult); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(body, &qrResult); err != nil {
m.logger.Warn("解析扫码状态响应失败", "err", err)
if !waitQRRetry(ctx, qrPollInterval) {
return
@@ -368,6 +400,7 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
}
serverErrors = 0
// status 保存状态,供当前处理流程使用
status := qrResult.Content.Data.QRCodeStatus
switch status {
case "CONFIRMED":
@@ -388,13 +421,17 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
// 扫码 5 分钟窗口在用户扫人脸二维码时把会话误标为 expired。
sess.createdTime = time.Now()
sess.expireTime = 5 * time.Minute
// verURL 保存verURL,供当前处理流程使用
verURL := sess.verificationURL
// expireTime 保存expire时间,供当前处理流程使用
expireTime := sess.expireTime
// cookieCount 保存登录凭证数量,供当前处理流程使用
cookieCount := len(sess.cookies)
sess.mu.Unlock()
m.logger.Warn("扫码登录需要风控验证,使用 Go HTTP 保持原登录会话", "session_id", sessionID, "verification_url", logsafe.URL(verURL), "tmp_cookie_count", cookieCount)
// #nosec G118 -- 验证必须跨越轮询请求,且由独立五分钟上下文保证退出。
go func() {
// verifyCtx、cancel 保存verifyCtx、cancel,供当前处理流程使用
verifyCtx, cancel := context.WithTimeout(context.Background(), expireTime)
defer cancel()
m.runGoVerification(verifyCtx, sessionID, verURL)
@@ -407,19 +444,26 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
// 二维码组件确认成功后,真实网页还会进入 /im 并跟随登录
// 重定向。部分账号的长登录 Cookie 只在这一步下发,不能只
// 保存 query.do 的响应头。
if err := m.completeConfirmedLogin(ctx, sess); err != nil {
if // err 保存err,供当前处理流程使用
err := m.completeConfirmedLogin(ctx, sess); err != nil {
m.logger.Warn("扫码确认后的官网登录跳转未完成,保留当前登录凭证", "session_id", sessionID, "err", err)
}
if err := m.enableConfirmedLongLogin(ctx, sess); err != nil {
if // err 保存err,供当前处理流程使用
err := m.enableConfirmedLongLogin(ctx, sess); err != nil {
m.logger.Warn("扫码登录已成功,但官网保持登录开启失败", "session_id", sessionID, "err", err)
}
sess.mu.Lock()
sess.Status = "success"
finalizeSessionCredentialsLocked(sess)
// unb 保存unb,供当前处理流程使用
unb := sess.unb
// cookieCount 保存登录凭证数量,供当前处理流程使用
cookieCount := len(sess.cookies)
// hasHavanaLongLogin 保存hasHavanaLong登录,供当前处理流程使用
hasHavanaLongLogin := sess.cookies["havana_lgc_exp"] != ""
// hasCookie3Backup 保存hasCookie3Backup,供当前处理流程使用
hasCookie3Backup := sess.cookies["cookie3_bak_exp"] != ""
// snapshotComplete 保存snapshotComplete,供当前处理流程使用
snapshotComplete := sess.cookieSnapshot != nil
sess.mu.Unlock()
m.logger.Info("扫码登录成功", "session_id", sessionID, "account_hash", logsafe.ID(unb),
@@ -472,37 +516,46 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
// completeConfirmedLogin 对齐二维码组件确认后的顶层页面跳转。专用 Cookie
// Jar 会捕获自动重定向链上的全部 Set-Cookie,并保留 Domain/Path/HttpOnly。
// completeConfirmedLogin 负责completeConfirmed登录相关处理。
func (m *Manager) completeConfirmedLogin(ctx context.Context, sess *Session) error {
if sess == nil {
return errors.New("扫码会话为空")
}
// state 保存状态,供当前处理流程使用
state := sess.snapshot()
// client、jar、err 保存client、jar、err,供当前处理流程使用
client, jar, err := m.faceHTTPClient(state.cookies, state.cookieSnapshot, apiScanStatus, qrVerifyTargetURL)
if err != nil {
return fmt.Errorf("创建扫码完成 Cookie Jar: %w", err)
}
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodGet, qrVerifyTargetURL, nil)
if err != nil {
return fmt.Errorf("创建扫码完成请求: %w", err)
}
m.setDocumentHeaders(req)
// resp、err 保存resp、err,供当前处理流程使用
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("访问闲鱼消息页完成登录: %w", err)
}
defer resp.Body.Close()
if _, err := io.Copy(io.Discard, io.LimitReader(resp.Body, 2<<20)); err != nil {
if // err 保存err,供当前处理流程使用
_, err := io.Copy(io.Discard, io.LimitReader(resp.Body, 2<<20)); err != nil {
return fmt.Errorf("读取扫码完成响应: %w", err)
}
// urls 保存urls,供当前处理流程使用
urls := []*url.URL{mustParseURL(qrVerifyTargetURL)}
if resp.Request != nil && resp.Request.URL != nil {
urls = append(urls, resp.Request.URL)
}
// finalCookies 保存finalCookies,供当前处理流程使用
finalCookies := collectJarCookies(jar, urls...)
if finalCookies["unb"] == "" {
return errors.New("扫码完成跳转未保留账号标识")
}
// finalSnapshot、snapshotComplete 保存finalSnapshot、snapshotComplete,供当前处理流程使用
finalSnapshot, snapshotComplete := jar.Snapshot()
sess.mu.Lock()
sess.cookies = finalCookies
@@ -518,13 +571,18 @@ func (m *Manager) completeConfirmedLogin(ctx context.Context, sess *Session) err
// enableConfirmedLongLogin 对齐官网账号安全页的“保持登录”开关:先提交
// status=0,再查询 hasLongTokenLogin,并保存两次响应更新后的完整 Cookie Jar。
// enableConfirmedLongLogin 负责enableConfirmedLong登录相关处理。
func (m *Manager) enableConfirmedLongLogin(ctx context.Context, sess *Session) error {
if sess == nil {
return errors.New("扫码会话为空")
}
// state 保存状态,供当前处理流程使用
state := sess.snapshot()
// service 保存service,供当前处理流程使用
service := xrenew.Service{HTTPClient: m.httpc, DocumentReferer: qrVerifyTargetURL}
// settings 保存设置,供当前处理流程使用
var settings *xrenew.LongLoginSettings
// err 保存err,供当前处理流程使用
var err error
if state.cookieSnapshot != nil {
settings, err = service.SetLongLoginSettings(ctx, cookieMarshal(state.cookies), true, state.cookieSnapshot)
@@ -541,7 +599,8 @@ func (m *Manager) enableConfirmedLongLogin(ctx context.Context, sess *Session) e
finalizeSessionCredentialsLocked(sess)
} else if strings.TrimSpace(settings.NewCookies) != "" {
sess.cookies = parseCookieStr(settings.NewCookies)
if unb := sess.cookies["unb"]; unb != "" {
if // unb 保存unb,供当前处理流程使用
unb := sess.cookies["unb"]; unb != "" {
sess.unb = unb
}
}
@@ -556,17 +615,21 @@ func (m *Manager) enableConfirmedLongLogin(ctx context.Context, sess *Session) e
return nil
}
// runGoVerification 负责运行GoVerification相关处理。
func (m *Manager) runGoVerification(ctx context.Context, sessionID, verificationURL string) {
if !strings.Contains(verificationURL, "/iv/") && !strings.Contains(verificationURL, "identity_verify") {
m.logger.Warn("扫码验证地址不属于已支持的人脸流程,保持人工验证状态", "session_id", sessionID, "verification_url", logsafe.URL(verificationURL))
return
}
if err := m.runFaceVerification(ctx, sessionID, verificationURL); err != nil {
if // err 保存err,供当前处理流程使用
err := m.runFaceVerification(ctx, sessionID, verificationURL); err != nil {
m.logger.Warn("扫码人脸验证 Go HTTP 流程未完成,保持人工验证状态", "session_id", sessionID, "err", err)
}
}
// waitQRRetry 负责waitQR重试相关处理。
func waitQRRetry(ctx context.Context, delay time.Duration) bool {
// timer 保存定时器,供当前处理流程使用
timer := time.NewTimer(delay)
defer timer.Stop()
select {
@@ -579,13 +642,16 @@ func waitQRRetry(ctx context.Context, delay time.Duration) bool {
// CompleteVerification 用户完成风控验证后调用。整个凭证换取过程只使用
// Go Cookie Jar;不得导航浏览器页面或通过 DOM 判断登录状态。
// CompleteVerification 负责CompleteVerification相关处理。
func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error) {
m.mu.Lock()
// sess、ok 保存sess、ok,供当前处理流程使用
sess, ok := m.sessions[sessionID]
m.mu.Unlock()
if !ok {
return "", "", fmt.Errorf("会话不存在")
}
// state 保存状态,供当前处理流程使用
state := sess.snapshot()
if len(state.cookies) == 0 {
return "", "", fmt.Errorf("无扫码临时 cookie")
@@ -595,45 +661,56 @@ func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (c
}
m.logger.Info("开始用临时 cookie 换取真实 cookie", "session_id", sessionID, "tmp_cookie_count", len(state.cookies))
// targetURL 保存targetURL,供当前处理流程使用
targetURL := qrVerifyTargetURL
// seedURL 保存seedURL,供当前处理流程使用
seedURL := state.verificationURL
if strings.TrimSpace(seedURL) == "" {
seedURL = targetURL
}
// jarClient、jar、err 保存jarClient、jar、err,供当前处理流程使用
jarClient, jar, err := m.faceHTTPClient(state.cookies, state.cookieSnapshot, seedURL, targetURL)
if err != nil {
return "", "", fmt.Errorf("创建登录 Cookie Jar: %w", err)
}
jarClient.Timeout = 30 * time.Second
// target、err 保存target、err,供当前处理流程使用
target, err := url.Parse(targetURL)
if err != nil {
return "", "", fmt.Errorf("解析登录凭证换取地址: %w", err)
}
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
if err != nil {
return "", "", err
}
m.setDocumentHeaders(req)
// resp、err 保存resp、err,供当前处理流程使用
resp, err := jarClient.Do(req)
if err != nil {
return "", "", fmt.Errorf("访问 goofish.com/im 换取登录凭证失败: %w", err)
}
defer resp.Body.Close()
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
if // err 保存err,供当前处理流程使用
_, err := io.Copy(io.Discard, resp.Body); err != nil {
return "", "", fmt.Errorf("读取登录凭证换取响应失败: %w", err)
}
// responseURL 保存响应URL,供当前处理流程使用
var responseURL *url.URL
if resp.Request != nil {
responseURL = resp.Request.URL
}
// finalCookies 保存finalCookies,供当前处理流程使用
finalCookies := collectJarCookies(jar, target, responseURL)
// finalUNB 保存finalUNB,供当前处理流程使用
finalUNB := finalCookies["unb"]
if finalUNB == "" {
return "", "", fmt.Errorf("纯 Go 登录凭证换取未获取到 unb,验证可能尚未完成或临时 Cookie 已失效")
}
sess.mu.Lock()
sess.cookies = finalCookies
if finalSnapshot, complete := jar.Snapshot(); complete {
if // finalSnapshot、complete 保存finalSnapshot、complete,供当前处理流程使用
finalSnapshot, complete := jar.Snapshot(); complete {
sess.cookieSnapshot = finalSnapshot
} else {
sess.cookieSnapshot = nil
@@ -648,9 +725,12 @@ func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (c
// parseCookieStr 把 "k=v; k2=v2" 解析回 map。
func parseCookieStr(s string) map[string]string {
// m 保存m,供当前处理流程使用
m := make(map[string]string)
// part 表示当前遍历过程中的part
for _, part := range strings.Split(s, "; ") {
if eq := strings.Index(part, "="); eq >= 0 {
if // eq 保存eq,供当前处理流程使用
eq := strings.Index(part, "="); eq >= 0 {
m[part[:eq]] = part[eq+1:]
}
}
@@ -659,29 +739,40 @@ func parseCookieStr(s string) map[string]string {
// getMH5TK 获取 m_h5_tk。
func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
// req 保存req,供当前处理流程使用
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, apiH5TK, nil)
m.setHeaders(req)
// resp、err 保存resp、err,供当前处理流程使用
resp, err := m.httpc.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
absorbSessionResponse(sess, apiH5TK, resp)
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
if // err 保存err,供当前处理流程使用
_, err := io.Copy(io.Discard, resp.Body); err != nil {
return err
}
// mH5TK 保存mH5TK,供当前处理流程使用
mH5TK := protocolCookieValue(sessionCookieHeader(sess, apiH5TK), "_m_h5_tk")
// token 保存令牌,供当前处理流程使用
token := ""
if parts := strings.SplitN(mH5TK, "_", 2); len(parts) > 0 {
if // parts 保存parts,供当前处理流程使用
parts := strings.SplitN(mH5TK, "_", 2); len(parts) > 0 {
token = parts[0]
}
// t 保存t,供当前处理流程使用
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
// dataStr 保存数据Str,供当前处理流程使用
dataStr := `{"bizScene":"home"}`
// signInput 保存signInput,供当前处理流程使用
signInput := token + "&" + t + "&" + appKey + "&" + dataStr
// sign 保存sign,供当前处理流程使用
sign := md5hex(signInput)
// params 保存params,供当前处理流程使用
params := url.Values{}
params.Set("jsv", "2.7.2")
params.Set("appKey", appKey)
@@ -694,21 +785,25 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
params.Set("api", "mtop.gaia.nodejs.gaia.idle.data.gw.v2.index.get")
params.Set("data", dataStr)
// req2 保存req2,供当前处理流程使用
req2, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiH5TK+"?"+params.Encode(), nil)
m.setHeaders(req2)
req2.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// cookieStr 保存登录凭证Str,供当前处理流程使用
cookieStr := sessionCookieHeader(sess, req2.URL.String())
if cookieStr != "" {
req2.Header.Set("Cookie", cookieStr)
}
// resp2、err 保存resp2、err,供当前处理流程使用
resp2, err := m.httpc.Do(req2)
if err != nil {
return err
}
defer resp2.Body.Close()
absorbSessionResponse(sess, req2.URL.String(), resp2)
if _, err := io.Copy(io.Discard, resp2.Body); err != nil {
if // err 保存err,供当前处理流程使用
_, err := io.Copy(io.Discard, resp2.Body); err != nil {
return err
}
@@ -717,6 +812,7 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
// getLoginParams 获取登录表单参数。
func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string]string, error) {
// params 保存params,供当前处理流程使用
params := url.Values{}
params.Set("lang", "zh_cn")
params.Set("appName", "xianyu")
@@ -730,6 +826,7 @@ func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string
params.Set("stie", "77")
params.Set("rnd", strconv.FormatFloat(randFloat(), 'f', -1, 64))
// req 保存req,供当前处理流程使用
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, apiMiniLogin+"?"+params.Encode(), nil)
m.setHeaders(req)
@@ -739,12 +836,14 @@ func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string
req.Header.Set("Cookie", cookieStr)
}
// resp、err 保存resp、err,供当前处理流程使用
resp, err := m.httpc.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
absorbSessionResponse(sess, req.URL.String(), resp)
// body、err 保存body、err,供当前处理流程使用
body, err := readQRBody(resp.Body)
if err != nil {
return nil, err
@@ -754,15 +853,18 @@ func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string
// 从 HTML 里提取 window.viewData = {...};
re := regexp.MustCompile(`window\.viewData\s*=\s*(\{.*?\});`)
// match 保存match,供当前处理流程使用
match := re.FindSubmatch(body)
if match == nil {
return nil, fmt.Errorf("获取登录参数失败:未找到 viewData")
}
// viewData 保存view数据,供当前处理流程使用
var viewData struct {
LoginFormData map[string]any `json:"loginFormData"`
}
if err := json.Unmarshal(match[1], &viewData); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(match[1], &viewData); err != nil {
return nil, fmt.Errorf("解析 viewData 失败: %w", err)
}
if viewData.LoginFormData == nil {
@@ -770,6 +872,7 @@ func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string
}
// 把所有值转为字符串(有些是 bool/number)。
strParams := make(map[string]string, len(viewData.LoginFormData))
// k、v 表示当前遍历过程中的k、v
for k, v := range viewData.LoginFormData {
strParams[k] = fmt.Sprintf("%v", v)
}
@@ -782,11 +885,15 @@ func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string
// pollQRCodeStatus 轮询二维码状态。
func (m *Manager) pollQRCodeStatus(ctx context.Context, sess *Session) (*http.Response, error) {
// form 保存表单,供当前处理流程使用
form := url.Values{}
// state 保存状态,供当前处理流程使用
state := sess.snapshot()
// k、v 表示当前遍历过程中的k、v
for k, v := range state.params {
form.Set(k, v)
}
// fingerprint 保存fingerprint,供当前处理流程使用
fingerprint := xianyu.CurrentBrowserFingerprint()
// 对齐 havana-nlogin 二维码组件 query.do 的浏览器环境字段。
// ua 是 AWSC/UAB 的可选结果;纯 Go 客户端在该值尚未生成时与官网
@@ -799,9 +906,11 @@ func (m *Manager) pollQRCodeStatus(ctx context.Context, sess *Session) (*http.Re
form.Set("documentReferer", qrVerifyTargetURL)
form.Set("defaultView", "qrcode")
// req 保存req,供当前处理流程使用
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiScanStatus, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
m.setHeaders(req)
// cookieStr 保存登录凭证Str,供当前处理流程使用
cookieStr := sessionCookieHeader(sess, req.URL.String())
if cookieStr != "" {
req.Header.Set("Cookie", cookieStr)
@@ -810,6 +919,7 @@ func (m *Manager) pollQRCodeStatus(ctx context.Context, sess *Session) (*http.Re
return m.httpc.Do(req)
}
// navigatorPlatform 负责navigatorPlatform相关处理。
func navigatorPlatform(secCHPlatform string) string {
switch strings.ToLower(strings.TrimSpace(secCHPlatform)) {
case "windows":
@@ -827,8 +937,10 @@ func navigatorPlatform(secCHPlatform string) string {
}
}
// setHeaders 负责setHeaders相关处理。
func (m *Manager) setHeaders(req *http.Request) {
xianyu.ApplyBrowserFingerprint(req.Header)
// k、v 表示当前遍历过程中的k、v
for k, v := range qrHeaders {
req.Header.Set(k, v)
}
@@ -836,6 +948,7 @@ func (m *Manager) setHeaders(req *http.Request) {
// setDocumentHeaders 复刻浏览器从闲鱼首页进入 /im 的文档请求头。这里只
// 发送 HTTP 请求并接收 Set-Cookie,不加载或校验任何页面 DOM。
// setDocumentHeaders 负责setDocumentHeaders相关处理。
func (m *Manager) setDocumentHeaders(req *http.Request) {
xianyu.ApplyBrowserFingerprint(req.Header)
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
@@ -847,6 +960,7 @@ func (m *Manager) setDocumentHeaders(req *http.Request) {
req.Header.Set("Upgrade-Insecure-Requests", "1")
}
// sessionCookieHeader 负责会话登录凭证Header相关处理。
func sessionCookieHeader(sess *Session, requestURL string) string {
if sess == nil {
return ""
@@ -854,9 +968,11 @@ func sessionCookieHeader(sess *Session, requestURL string) string {
return snapshotCookieHeader(sess.snapshot(), requestURL)
}
// snapshotCookieHeader 负责snapshot登录凭证Header相关处理。
func snapshotCookieHeader(state sessionSnapshot, requestURL string) string {
if state.cookieSnapshot != nil {
if value, authoritative := cookierefresh.ScopedCookieHeaderForRequest(
if // value、authoritative 保存value、authoritative,供当前处理流程使用
value, authoritative := cookierefresh.ScopedCookieHeaderForRequest(
state.cookieSnapshot, requestURL, qrTopSite, time.Now(),
); authoritative {
return value
@@ -865,6 +981,7 @@ func snapshotCookieHeader(state sessionSnapshot, requestURL string) string {
return cookieMarshal(state.cookies)
}
// absorbSessionResponse 负责absorb会话响应相关处理。
func absorbSessionResponse(sess *Session, requestURL string, resp *http.Response) {
if sess == nil || resp == nil {
return
@@ -879,6 +996,7 @@ func absorbSessionResponse(sess *Session, requestURL string, resp *http.Response
sess.cookieSnapshot = []cookierefresh.BrowserCookie{}
}
}
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range resp.Cookies() {
if cookie == nil || cookie.Name == "" {
continue
@@ -897,25 +1015,30 @@ func absorbSessionResponse(sess *Session, requestURL string, resp *http.Response
}
}
// finalizeSessionCredentialsLocked 负责finalize会话CredentialsLocked相关处理。
func finalizeSessionCredentialsLocked(sess *Session) {
if sess == nil {
return
}
if sess.cookieSnapshot != nil {
// value 保存值,供当前处理流程使用
value, _ := cookierefresh.ScopedCookieHeaderForRequest(
sess.cookieSnapshot, qrVerifyTargetURL, qrTopSite, time.Now(),
)
sess.cookies = parseCookieStr(value)
}
if unb := sess.cookies["unb"]; unb != "" {
if // unb 保存unb,供当前处理流程使用
unb := sess.cookies["unb"]; unb != "" {
sess.unb = unb
}
}
// cloneCookieSnapshot 负责clone登录凭证Snapshot相关处理。
func cloneCookieSnapshot(in []cookierefresh.BrowserCookie) []cookierefresh.BrowserCookie {
if in == nil {
return nil
}
// out 保存out,供当前处理流程使用
out := cookierefresh.NormalizeSnapshot(in)
if out == nil {
return []cookierefresh.BrowserCookie{}
@@ -923,8 +1046,11 @@ func cloneCookieSnapshot(in []cookierefresh.BrowserCookie) []cookierefresh.Brows
return out
}
// protocolCookieValue 负责protocol登录凭证值相关处理。
func protocolCookieValue(cookieHeader, name string) string {
// part 表示当前遍历过程中的part
for _, part := range strings.Split(cookieHeader, ";") {
// key、value、ok 保存key、value、ok,供当前处理流程使用
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
if ok && key == name {
return value
@@ -935,23 +1061,30 @@ func protocolCookieValue(cookieHeader, name string) string {
// ---- 工具函数 ----
// md5hex 负责md5hex相关处理。
func md5hex(s string) string {
// #nosec G401 -- 闲鱼登录协议明确要求 MD5,不能替换为其他摘要算法。
h := md5.Sum([]byte(s))
return hex.EncodeToString(h[:])
}
// cookieMarshal 负责登录凭证Marshal相关处理。
func cookieMarshal(cookies map[string]string) string {
// parts 保存parts,供当前处理流程使用
parts := make([]string, 0, len(cookies))
// k、v 表示当前遍历过程中的k、v
for k, v := range cookies {
parts = append(parts, k+"="+v)
}
return strings.Join(parts, "; ")
}
// randomUUID 负责randomUUID相关处理。
func randomUUID() (string, error) {
// b 保存b,供当前处理流程使用
b := make([]byte, 16)
if _, err := io.ReadFull(randReader, b); err != nil {
if // err 保存err,供当前处理流程使用
_, err := io.ReadFull(randReader, b); err != nil {
return "", err
}
b[6] = (b[6] & 0x0f) | 0x40
@@ -960,10 +1093,15 @@ func randomUUID() (string, error) {
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
}
// randReader 保存randReader,供当前处理流程使用
var randReader io.Reader = rand.Reader
// randFloat 保存randFloat,供当前处理流程使用
var randFloat = func() float64 { return float64(time.Now().UnixNano()%1e9) / 1e9 }
// readQRBody 负责readQR请求体相关处理。
func readQRBody(r io.Reader) ([]byte, error) {
// body、err 保存body、err,供当前处理流程使用
body, err := io.ReadAll(io.LimitReader(r, maxQRResponseBytes+1))
if err != nil {
return nil, err
@@ -974,6 +1112,7 @@ func readQRBody(r io.Reader) ([]byte, error) {
return body, nil
}
// truncate 负责truncate相关处理。
func truncate(s string, n int) string {
if len(s) <= n {
return s
+56 -4
View File
@@ -17,26 +17,36 @@ import (
"xianyu-go/internal/xianyu/cookierefresh"
)
// failingReader 保存failingReader,供当前处理流程使用
type failingReader struct{}
// Read 读取当前值。
func (failingReader) Read([]byte) (int, error) { return 0, errors.New("entropy unavailable") }
// TestReadQRBodyRejectsOversizedResponse 负责TestReadQR请求体RejectsOversized响应相关处理。
func TestReadQRBodyRejectsOversizedResponse(t *testing.T) {
if _, err := readQRBody(strings.NewReader(strings.Repeat("x", maxQRResponseBytes+1))); err == nil {
if // err 保存err,供当前处理流程使用
_, err := readQRBody(strings.NewReader(strings.Repeat("x", maxQRResponseBytes+1))); err == nil {
t.Fatal("oversized QR response should fail")
}
}
// TestSessionStatusConcurrentSnapshot 负责Test会话状态ConcurrentSnapshot相关处理。
func TestSessionStatusConcurrentSnapshot(t *testing.T) {
// m 保存m,供当前处理流程使用
m := NewManager(nil)
// sess 保存sess,供当前处理流程使用
sess := testVerificationSession()
m.sessions["s1"] = sess
// wg 保存wg,供当前处理流程使用
var wg sync.WaitGroup
for worker := 0; worker < 8; worker++ {
for // worker 保存工作器,供当前处理流程使用
worker := 0; worker < 8; worker++ {
wg.Add(1)
go func(worker int) {
defer wg.Done()
for i := 0; i < 500; i++ {
for // i 保存i,供当前处理流程使用
i := 0; i < 500; i++ {
if worker%2 == 0 {
sess.mu.Lock()
sess.verificationScreenshot = fmt.Sprintf("shot-%d-%d", worker, i)
@@ -44,6 +54,7 @@ func TestSessionStatusConcurrentSnapshot(t *testing.T) {
sess.Status = "verification_required"
sess.mu.Unlock()
} else {
// status 保存状态,供当前处理流程使用
status := m.GetSessionStatus("s1")
if status["status"] == "not_found" {
t.Error("existing session reported not_found")
@@ -56,61 +67,80 @@ func TestSessionStatusConcurrentSnapshot(t *testing.T) {
wg.Wait()
}
// TestCompleteVerificationRequiresPureGoCredentialResult 负责TestCompleteVerificationRequiresPureGoCredential结果相关处理。
func TestCompleteVerificationRequiresPureGoCredentialResult(t *testing.T) {
// m 保存m,供当前处理流程使用
m := NewManager(nil)
m.sessions["s1"] = testVerificationSession()
// oldTarget 保存oldTarget,供当前处理流程使用
oldTarget := qrVerifyTargetURL
qrVerifyTargetURL = newEmptyCookieServer(t)
defer func() { qrVerifyTargetURL = oldTarget }()
// err 保存err,供当前处理流程使用
_, _, err := m.CompleteVerification(context.Background(), "s1")
if err == nil || !strings.Contains(err.Error(), "纯 Go 登录凭证换取未获取到 unb") {
t.Fatalf("错误异常: %v", err)
}
}
// TestCompleteVerificationReturnsCompletedSessionWithoutAnotherRequest 负责TestCompleteVerificationReturnsCompleted会话WithoutAnother请求相关处理。
func TestCompleteVerificationReturnsCompletedSessionWithoutAnotherRequest(t *testing.T) {
// m 保存m,供当前处理流程使用
m := NewManager(nil)
// sess 保存sess,供当前处理流程使用
sess := testVerificationSession()
sess.Status = "success"
sess.unb = "completed-account"
sess.cookies["unb"] = sess.unb
m.sessions["s1"] = sess
// cookies、unb、err 保存cookies、unb、err,供当前处理流程使用
cookies, unb, err := m.CompleteVerification(context.Background(), "s1")
if err != nil || unb != "completed-account" || !strings.Contains(cookies, "unb=completed-account") {
t.Fatalf("completed session: cookies=%q unb=%q err=%v", cookies, unb, err)
}
}
// TestCompleteVerificationMissingSession 负责TestCompleteVerificationMissing会话相关处理。
func TestCompleteVerificationMissingSession(t *testing.T) {
// m 保存m,供当前处理流程使用
m := NewManager(nil)
// err 保存err,供当前处理流程使用
_, _, err := m.CompleteVerification(context.Background(), "missing")
if err == nil || !strings.Contains(err.Error(), "会话不存在") {
t.Fatalf("错误异常: %v", err)
}
}
// TestRandomUUIDRequiresEntropy 负责TestRandomUUIDRequiresEntropy相关处理。
func TestRandomUUIDRequiresEntropy(t *testing.T) {
// original 保存original,供当前处理流程使用
original := randReader
t.Cleanup(func() { randReader = original })
randReader = failingReader{}
if _, err := randomUUID(); err == nil {
if // err 保存err,供当前处理流程使用
_, err := randomUUID(); err == nil {
t.Fatal("randomUUID should fail when entropy source fails")
}
randReader = io.LimitReader(strings.NewReader("0123456789abcdef"), 16)
// id、err 保存id、err,供当前处理流程使用
id, err := randomUUID()
if err != nil || len(id) != 36 || id[14] != '4' {
t.Fatalf("randomUUID() = %q, %v", id, err)
}
}
// TestFaceVerificationExtractors 负责TestFaceVerificationExtractors相关处理。
func TestFaceVerificationExtractors(t *testing.T) {
// normal 保存normal,供当前处理流程使用
normal := `<script>window.location.href = "https://passport.goofish.com/iv/mini/verify_modes.htm?htoken=abc-123&_umidfg=";</script>`
// htoken、err 保存htoken、err,供当前处理流程使用
htoken, err := extractFaceHToken(`https://passport.goofish.com/iv/mini/normal_validate.htm?htoken=abc-123`)
if err != nil || htoken != "abc-123" {
t.Fatalf("extractFaceHToken=%q err=%v", htoken, err)
}
// verifyURL、err 保存verifyURL、err,供当前处理流程使用
verifyURL, err := extractVerifyModesURL(normal)
if err != nil {
t.Fatalf("extractVerifyModesURL: %v", err)
@@ -118,6 +148,7 @@ func TestFaceVerificationExtractors(t *testing.T) {
if !strings.HasSuffix(verifyURL, "_umidfg=1") {
t.Fatalf("verifyURL 未补齐 _umidfg: %q", verifyURL)
}
// qrContent、err 保存qrContent、err,供当前处理流程使用
qrContent, err := extractFaceQRCodeContent(`<script>new Qrcode({ text: "https:\/\/passport.goofish.com\/face?x=1&amp;y=2" });</script>`)
if err != nil {
t.Fatalf("extractFaceQRCodeContent: %v", err)
@@ -127,7 +158,9 @@ func TestFaceVerificationExtractors(t *testing.T) {
}
}
// TestCheckFaceVerificationDone 负责TestCheckFaceVerificationDone相关处理。
func TestCheckFaceVerificationDone(t *testing.T) {
// hc 保存hc,供当前处理流程使用
hc := &handlerChain{}
hc.handle("/iv/photoVerify/check.do", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("htoken") != "face-token" {
@@ -135,51 +168,68 @@ func TestCheckFaceVerificationDone(t *testing.T) {
}
_, _ = w.Write([]byte(`{"content":{"code":3,"url":"https://passport.goofish.com/ivCheckLogin.htm?ok=1"}}`))
}))
// m 保存m,供当前处理流程使用
m, _, _ := newStubbedManager(t, hc)
// jar、err 保存jar、err,供当前处理流程使用
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatal(err)
}
// client 保存client,供当前处理流程使用
client := *m.httpc
client.Jar = jar
// gotURL、done、err 保存gotURL、done、err,供当前处理流程使用
gotURL, done, err := m.checkFaceVerification(context.Background(), &client, "face-token")
if err != nil || !done || !strings.Contains(gotURL, "ivCheckLogin") {
t.Fatalf("checkFaceVerification url=%q done=%v err=%v", gotURL, done, err)
}
}
// TestCollectJarCookies 负责TestCollectJarCookies相关处理。
func TestCollectJarCookies(t *testing.T) {
// jar、err 保存jar、err,供当前处理流程使用
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatal(err)
}
// u 保存u,供当前处理流程使用
u, _ := url.Parse("https://passport.goofish.com/")
jar.SetCookies(u, []*http.Cookie{{Name: "unb", Value: "123"}, {Name: "cookie2", Value: "abc"}})
// got 保存got,供当前处理流程使用
got := collectJarCookies(jar, u)
if got["unb"] != "123" || got["cookie2"] != "abc" {
t.Fatalf("collectJarCookies=%v", got)
}
}
// TestFaceCookieJarExportsCrossDomainAttributes 负责TestFace登录凭证JarExportsCrossDomainAttributes相关处理。
func TestFaceCookieJarExportsCrossDomainAttributes(t *testing.T) {
// jar 保存jar,供当前处理流程使用
jar := newFaceCookieJar(map[string]string{"tmp": "1"}, []cookierefresh.BrowserCookie{})
// passport 保存passport,供当前处理流程使用
passport, _ := url.Parse("https://passport.goofish.com/ivCheckLogin.htm")
// input 保存input,供当前处理流程使用
input := &http.Cookie{
Name: "unb", Value: "777", Domain: ".goofish.com", Path: "/", Secure: true, HttpOnly: true,
}
jar.SetCookies(passport, []*http.Cookie{input})
// www 保存www,供当前处理流程使用
www, _ := url.Parse("https://www.goofish.com/im")
// got 保存got,供当前处理流程使用
got := collectJarCookies(jar, www)
if got["unb"] != "777" {
// snapshot 保存snapshot,供当前处理流程使用
snapshot, _ := jar.Snapshot()
t.Fatalf("跨域 Cookie 未进入 /im: cookies=%v snapshot=%+v raw=%q", got, snapshot, input.String())
}
// snapshot、complete 保存snapshot、complete,供当前处理流程使用
snapshot, complete := jar.Snapshot()
if !complete || len(snapshot) != 1 || snapshot[0].Domain != ".goofish.com" || !snapshot[0].HTTPOnly || !snapshot[0].Secure {
t.Fatalf("完整 Cookie 属性未保留: complete=%v snapshot=%+v", complete, snapshot)
}
}
// testVerificationSession 负责testVerification会话相关处理。
func testVerificationSession() *Session {
return &Session{
SessionID: "s1",
@@ -190,8 +240,10 @@ func testVerificationSession() *Session {
}
}
// newEmptyCookieServer 负责newEmpty登录凭证Server相关处理。
func newEmptyCookieServer(t *testing.T) string {
t.Helper()
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
File diff suppressed because it is too large. Load diff
+82 -3
View File
@@ -25,52 +25,64 @@ import (
// 关键点:必须用同一个 Cookie Jar 贯穿 normal_validate -> verify_modes ->
// identity_verify -> check.do -> ivCheckLogin。服务端会在跳转链路中写入身份
// 锚点 Cookie;如果拆成多个无状态请求,最终通常拿不到 unb。
// runFaceVerification 负责运行FaceVerification相关处理。
func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL string) error {
m.mu.Lock()
// sess 保存sess,供当前处理流程使用
sess := m.sessions[sessionID]
if sess == nil {
m.mu.Unlock()
return fmt.Errorf("会话不存在")
}
m.mu.Unlock()
// state 保存状态,供当前处理流程使用
state := sess.snapshot()
// initialCookies 保存initialCookies,供当前处理流程使用
initialCookies := state.cookies
if len(initialCookies) == 0 {
return fmt.Errorf("无扫码临时 cookie")
}
// client、jar、err 保存client、jar、err,供当前处理流程使用
client, jar, err := m.faceHTTPClient(initialCookies, state.cookieSnapshot, iframeURL)
if err != nil {
return err
}
// normalHTML、err 保存normalHTML、err,供当前处理流程使用
normalHTML, err := m.faceGetHTML(ctx, client, iframeURL, "")
if err != nil {
return fmt.Errorf("请求 normal_validate: %w", err)
}
// htoken、err 保存htoken、err,供当前处理流程使用
htoken, err := extractFaceHToken(normalHTML)
if err != nil {
return err
}
// verifyModesURL、err 保存verifyModesURL、err,供当前处理流程使用
verifyModesURL, err := extractVerifyModesURL(normalHTML)
if err != nil {
return err
}
// identityHTML、err 保存identityHTML、err,供当前处理流程使用
identityHTML, err := m.faceGetHTML(ctx, client, verifyModesURL, "")
if err != nil {
return fmt.Errorf("请求 verify_modes: %w", err)
}
// faceContent、err 保存faceContent、err,供当前处理流程使用
faceContent, err := extractFaceQRCodeContent(identityHTML)
if err != nil {
return err
}
// faceQRURL、err 保存faceQRURL、err,供当前处理流程使用
faceQRURL, err := renderQRDataURL(faceContent)
if err != nil {
return fmt.Errorf("渲染人脸二维码: %w", err)
}
m.mu.Lock()
// s 保存s,供当前处理流程使用
s := m.sessions[sessionID]
m.mu.Unlock()
if s != nil {
@@ -82,18 +94,22 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
}
m.logger.Info("人脸验证二维码已生成,等待用户手机扫码", "session_id", sessionID)
// ivCheckURL、err 保存ivCheckURL、err,供当前处理流程使用
ivCheckURL, err := m.waitFaceVerification(ctx, client, sessionID, htoken)
if err != nil {
return err
}
if _, err := m.faceGetHTML(ctx, client, ivCheckURL, faceIdentityReferer(htoken)); err != nil {
if // err 保存err,供当前处理流程使用
_, err := m.faceGetHTML(ctx, client, ivCheckURL, faceIdentityReferer(htoken)); err != nil {
return fmt.Errorf("请求 ivCheckLogin: %w", err)
}
// finalCookies 保存finalCookies,供当前处理流程使用
finalCookies := collectJarCookies(jar, mustParseURL(qrVerifyTargetURL))
if finalCookies["unb"] == "" {
return fmt.Errorf("人脸验证完成但未获取到 unb")
}
// finalSnapshot、snapshotComplete 保存finalSnapshot、snapshotComplete,供当前处理流程使用
finalSnapshot, snapshotComplete := jar.Snapshot()
m.mu.Lock()
@@ -115,16 +131,21 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
return nil
}
// faceHTTPClient 负责faceHTTPClient相关处理。
func (m *Manager) faceHTTPClient(cookies map[string]string, snapshot []cookierefresh.BrowserCookie, seedURLs ...string) (*http.Client, *faceCookieJar, error) {
// jar 保存jar,供当前处理流程使用
jar := newFaceCookieJar(cookies, snapshot)
if snapshot == nil {
setJarCookies(jar, mustParseURL(host), cookies)
// rawURL 表示当前遍历过程中的原始URL
for _, rawURL := range seedURLs {
if u, err := url.Parse(rawURL); err == nil {
if // u、err 保存u、err,供当前处理流程使用
u, err := url.Parse(rawURL); err == nil {
setJarCookies(jar, u, cookies)
}
}
}
// hc 保存hc,供当前处理流程使用
hc := *m.httpc
hc.Jar = jar
return &hc, jar, nil
@@ -134,13 +155,16 @@ func (m *Manager) faceHTTPClient(cookies map[string]string, snapshot []cookieref
// cookiejar 能正确发送 Cookie,但没有导出完整 Jar 的接口;这个实现直接以
// BrowserCookie 为权威状态,使自动重定向中的每个 Set-Cookie 都能原样进入
// 最终持久化快照。
// faceCookieJar 保存face登录凭证Jar,供当前处理流程使用
type faceCookieJar struct {
mu sync.Mutex
snapshot []cookierefresh.BrowserCookie
authoritative bool
}
// newFaceCookieJar 负责newFace登录凭证Jar相关处理。
func newFaceCookieJar(cookies map[string]string, snapshot []cookierefresh.BrowserCookie) *faceCookieJar {
// jar 保存jar,供当前处理流程使用
jar := &faceCookieJar{authoritative: snapshot != nil}
if snapshot != nil {
jar.snapshot = cookierefresh.NormalizeSnapshot(snapshot)
@@ -155,19 +179,25 @@ func newFaceCookieJar(cookies map[string]string, snapshot []cookierefresh.Browse
return jar
}
// Cookies 负责Cookies相关处理。
func (j *faceCookieJar) Cookies(u *url.URL) []*http.Cookie {
if j == nil || u == nil {
return nil
}
j.mu.Lock()
// header 保存header,供当前处理流程使用
header, _ := cookierefresh.ScopedCookieHeaderForRequest(j.snapshot, u.String(), qrTopSite, time.Now())
j.mu.Unlock()
if header == "" {
return nil
}
// parts 保存parts,供当前处理流程使用
parts := strings.Split(header, ";")
// out 保存out,供当前处理流程使用
out := make([]*http.Cookie, 0, len(parts))
// part 表示当前遍历过程中的part
for _, part := range parts {
// name、value、ok 保存name、value、ok,供当前处理流程使用
name, value, ok := strings.Cut(strings.TrimSpace(part), "=")
if !ok || name == "" {
continue
@@ -177,15 +207,19 @@ func (j *faceCookieJar) Cookies(u *url.URL) []*http.Cookie {
return out
}
// SetCookies 设置Cookies。
func (j *faceCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
if j == nil || u == nil || len(cookies) == 0 {
return
}
// raw 保存原始,供当前处理流程使用
raw := make([]string, 0, len(cookies))
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range cookies {
if cookie == nil || strings.TrimSpace(cookie.Name) == "" {
continue
}
// line 保存line,供当前处理流程使用
line := strings.TrimSpace(cookie.Raw)
if line == "" {
line = cookie.String()
@@ -205,6 +239,7 @@ func (j *faceCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
j.mu.Unlock()
}
// Snapshot 负责Snapshot相关处理。
func (j *faceCookieJar) Snapshot() ([]cookierefresh.BrowserCookie, bool) {
if j == nil {
return nil, false
@@ -214,6 +249,7 @@ func (j *faceCookieJar) Snapshot() ([]cookierefresh.BrowserCookie, bool) {
if !j.authoritative {
return nil, false
}
// out 保存out,供当前处理流程使用
out := cookierefresh.NormalizeSnapshot(j.snapshot)
if out == nil {
out = []cookierefresh.BrowserCookie{}
@@ -221,7 +257,9 @@ func (j *faceCookieJar) Snapshot() ([]cookierefresh.BrowserCookie, bool) {
return out, true
}
// faceGetHTML 负责faceGetHTML相关处理。
func (m *Manager) faceGetHTML(ctx context.Context, client *http.Client, targetURL, referer string) (string, error) {
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
if err != nil {
return "", err
@@ -230,11 +268,13 @@ func (m *Manager) faceGetHTML(ctx context.Context, client *http.Client, targetUR
if referer != "" {
req.Header.Set("Referer", referer)
}
// resp、err 保存resp、err,供当前处理流程使用
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// body、err 保存body、err,供当前处理流程使用
body, err := readQRBody(resp.Body)
if err != nil {
return "", err
@@ -242,17 +282,22 @@ func (m *Manager) faceGetHTML(ctx context.Context, client *http.Client, targetUR
return string(body), nil
}
// waitFaceVerification 负责waitFaceVerification相关处理。
func (m *Manager) waitFaceVerification(ctx context.Context, client *http.Client, sessionID, htoken string) (string, error) {
// ticker 保存ticker,供当前处理流程使用
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
m.mu.Lock()
// sess 保存sess,供当前处理流程使用
sess := m.sessions[sessionID]
m.mu.Unlock()
// expired 保存expired,供当前处理流程使用
expired := sess == nil || sess.isExpired()
if expired {
return "", fmt.Errorf("人脸验证超时或会话已过期")
}
// ivCheckURL、done、err 保存ivCheckURL、done、err,供当前处理流程使用
ivCheckURL, done, err := m.checkFaceVerification(ctx, client, htoken)
if err != nil {
m.logger.Warn("人脸验证轮询异常", "session_id", sessionID, "err", err)
@@ -267,11 +312,14 @@ func (m *Manager) waitFaceVerification(ctx context.Context, client *http.Client,
}
}
// checkFaceVerification 负责checkFaceVerification相关处理。
func (m *Manager) checkFaceVerification(ctx context.Context, client *http.Client, htoken string) (ivCheckURL string, done bool, err error) {
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiFaceCheck, nil)
if err != nil {
return "", false, err
}
// q 保存q,供当前处理流程使用
q := req.URL.Query()
q.Set("htoken", htoken)
req.URL.RawQuery = q.Encode()
@@ -279,22 +327,26 @@ func (m *Manager) checkFaceVerification(ctx context.Context, client *http.Client
req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
req.Header.Set("X-Requested-With", "XMLHttpRequest")
req.Header.Set("Referer", faceIdentityReferer(htoken))
// resp、err 保存resp、err,供当前处理流程使用
resp, err := client.Do(req)
if err != nil {
return "", false, err
}
defer resp.Body.Close()
// body、err 保存body、err,供当前处理流程使用
body, err := readQRBody(resp.Body)
if err != nil {
return "", false, err
}
// result 保存结果,供当前处理流程使用
var result struct {
Content struct {
Code any `json:"code"`
URL string `json:"url"`
} `json:"content"`
}
if err := json.Unmarshal(body, &result); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(body, &result); err != nil {
return "", false, fmt.Errorf("解析人脸验证状态失败: %w", err)
}
if fmt.Sprint(result.Content.Code) == "3" {
@@ -303,38 +355,49 @@ func (m *Manager) checkFaceVerification(ctx context.Context, client *http.Client
return "", false, nil
}
// faceIdentityReferer 负责faceIdentityReferer相关处理。
func faceIdentityReferer(htoken string) string {
return host + "/iv/mini/identity_verify.htm?htoken=" + url.QueryEscape(htoken)
}
// cloneCookieMap 负责clone登录凭证Map相关处理。
func cloneCookieMap(in map[string]string) map[string]string {
// out 保存out,供当前处理流程使用
out := make(map[string]string, len(in))
// k、v 表示当前遍历过程中的k、v
for k, v := range in {
out[k] = v
}
return out
}
// setJarCookies 负责setJarCookies相关处理。
func setJarCookies(jar http.CookieJar, u *url.URL, cookies map[string]string) {
if jar == nil || u == nil {
return
}
// cs 保存cs,供当前处理流程使用
cs := make([]*http.Cookie, 0, len(cookies))
// k、v 表示当前遍历过程中的k、v
for k, v := range cookies {
cs = append(cs, &http.Cookie{Name: k, Value: v, Path: "/"})
}
jar.SetCookies(u, cs)
}
// collectJarCookies 负责collectJarCookies相关处理。
func collectJarCookies(jar http.CookieJar, urls ...*url.URL) map[string]string {
// out 保存out,供当前处理流程使用
out := make(map[string]string)
if jar == nil {
return out
}
// u 表示当前遍历过程中的u
for _, u := range urls {
if u == nil {
continue
}
// c 表示当前遍历过程中的c
for _, c := range jar.Cookies(u) {
out[c.Name] = c.Value
}
@@ -342,7 +405,9 @@ func collectJarCookies(jar http.CookieJar, urls ...*url.URL) map[string]string {
return out
}
// mustParseURL 负责mustParseURL相关处理。
func mustParseURL(raw string) *url.URL {
// u、err 保存u、err,供当前处理流程使用
u, err := url.Parse(raw)
if err != nil {
return nil
@@ -350,12 +415,15 @@ func mustParseURL(raw string) *url.URL {
return u
}
// renderQRDataURL 负责renderQR数据URL相关处理。
func renderQRDataURL(content string) (string, error) {
// png、err 保存png、err,供当前处理流程使用
png, err := qrcode.New(content, qrcode.Low)
if err != nil {
return "", err
}
png.DisableBorder = false
// pngBytes、err 保存pngBytes、err,供当前处理流程使用
pngBytes, err := png.PNG(256)
if err != nil {
return "", err
@@ -363,8 +431,11 @@ func renderQRDataURL(content string) (string, error) {
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(pngBytes), nil
}
// extractFaceHToken 负责extractFaceH令牌相关处理。
func extractFaceHToken(pageHTML string) (string, error) {
// re 保存re,供当前处理流程使用
re := regexp.MustCompile(`htoken=([A-Za-z0-9_\-]+)`)
// match 保存match,供当前处理流程使用
match := re.FindStringSubmatch(pageHTML)
if match == nil {
return "", fmt.Errorf("人脸验证:未能提取 htoken")
@@ -372,12 +443,16 @@ func extractFaceHToken(pageHTML string) (string, error) {
return match[1], nil
}
// extractVerifyModesURL 负责extractVerifyModesURL相关处理。
func extractVerifyModesURL(pageHTML string) (string, error) {
// re 保存re,供当前处理流程使用
re := regexp.MustCompile(`window\.location\.href\s*=\s*"((?:https?:)?//[^"]*?/iv/mini/verify_modes\.htm\?[^"]*)"`)
// match 保存match,供当前处理流程使用
match := re.FindStringSubmatch(pageHTML)
if match == nil {
return "", fmt.Errorf("人脸验证:未能提取 verify_modes 链接")
}
// raw 保存原始,供当前处理流程使用
raw := html.UnescapeString(match[1])
raw = strings.ReplaceAll(raw, `\/`, `/`)
if strings.HasPrefix(raw, "//") {
@@ -389,12 +464,16 @@ func extractVerifyModesURL(pageHTML string) (string, error) {
return raw, nil
}
// extractFaceQRCodeContent 负责extractFaceQRCode内容相关处理。
func extractFaceQRCodeContent(pageHTML string) (string, error) {
// re 保存re,供当前处理流程使用
re := regexp.MustCompile(`new\s+Qrcode\(\{\s*text:\s*"((?:\\.|[^"\\])*)"`)
// match 保存match,供当前处理流程使用
match := re.FindStringSubmatch(pageHTML)
if match == nil {
return "", fmt.Errorf("人脸验证:未能提取人脸验证二维码 URL")
}
// content、err 保存content、err,供当前处理流程使用
content, err := strconv.Unquote(`"` + match[1] + `"`)
if err != nil {
content = match[1]
+164 -17
View File
@@ -20,6 +20,7 @@ import (
"xianyu-go/internal/xianyu/protocol"
)
// HasLoginURL 保存Has登录URL,供当前处理流程使用
const (
HasLoginURL = "https://passport.goofish.com/newlogin/hasLogin.do"
SilentHasLoginURL = "https://passport.goofish.com/newlogin/silentHasLogin.do"
@@ -47,6 +48,7 @@ type Service struct {
PromiseTimeout time.Duration
}
// LongLoginSettings 保存Long登录设置,供当前处理流程使用
type LongLoginSettings struct {
CanOpenLongLogin bool `json:"can_open_long_login"`
Enabled bool `json:"enabled"`
@@ -56,13 +58,16 @@ type LongLoginSettings struct {
CookieSnapshotComplete bool `json:"-"`
}
// longLoginCookieState 保存long登录登录凭证状态,供当前处理流程使用
type longLoginCookieState struct {
flat string
snapshot []cookierefresh.BrowserCookie
authoritative bool
}
// newLongLoginCookieState 负责newLong登录登录凭证状态相关处理。
func newLongLoginCookieState(cookiesStr string, snapshots [][]cookierefresh.BrowserCookie) *longLoginCookieState {
// state 保存状态,供当前处理流程使用
state := &longLoginCookieState{flat: cookiesStr, authoritative: len(snapshots) > 0}
if state.authoritative {
state.snapshot = cookierefresh.NormalizeSnapshot(snapshots[0])
@@ -74,6 +79,7 @@ func newLongLoginCookieState(cookiesStr string, snapshots [][]cookierefresh.Brow
return state
}
// requestCookies 负责请求Cookies相关处理。
func (state *longLoginCookieState) requestCookies(requestURL string) string {
if state == nil || !state.authoritative {
if state == nil {
@@ -81,10 +87,12 @@ func (state *longLoginCookieState) requestCookies(requestURL string) string {
}
return state.flat
}
// value 保存值,供当前处理流程使用
value, _ := cookierefresh.ScopedCookieHeaderForRequest(state.snapshot, requestURL, goofishTopSite, time.Now())
return value
}
// apply 负责apply相关处理。
func (state *longLoginCookieState) apply(requestURL string, setCookies []string) {
if state == nil {
return
@@ -100,10 +108,12 @@ func (state *longLoginCookieState) apply(requestURL string, setCookies []string)
state.flat = MergeSetCookies(state.flat, setCookies)
}
// refreshCanonical 负责refreshCanonical相关处理。
func (state *longLoginCookieState) refreshCanonical() {
state.flat, _ = cookierefresh.ScopedCookieHeaderForRequest(state.snapshot, goofishIMDocumentURL, goofishTopSite, time.Now())
}
// populate 负责populate相关处理。
func (state *longLoginCookieState) populate(result *LongLoginSettings) {
if state == nil || result == nil {
return
@@ -125,17 +135,21 @@ func (s Service) QueryLongLoginSettings(ctx context.Context, cookiesStr string,
// SetLongLoginSettings 中 status=0 表示开启,status=1 表示关闭。
func (s Service) SetLongLoginSettings(ctx context.Context, cookiesStr string, enabled bool, snapshots ...[]cookierefresh.BrowserCookie) (*LongLoginSettings, error) {
// status 保存状态,供当前处理流程使用
status := "1"
if enabled {
status = "0"
}
// state 保存状态,供当前处理流程使用
state := newLongLoginCookieState(cookiesStr, snapshots)
// setResult、err 保存setResult、err,供当前处理流程使用
setResult, err := s.longLoginRequest(ctx, state, &status)
if err != nil {
return setResult, err
}
// 官网 SET 成功后触发 LONG_LOGIN_SWITCH,再通过 QUERY 获取最终状态;SET
// 本身只要求 data.success,不要求携带 returnValue。
// queried、err 保存queried、err,供当前处理流程使用
queried, err := s.longLoginRequest(ctx, state, nil)
if queried == nil {
queried = &LongLoginSettings{
@@ -153,20 +167,26 @@ func (s Service) SetLongLoginSettings(ctx context.Context, cookiesStr string, en
return queried, nil
}
// longLoginRequest 负责long登录请求相关处理。
func (s Service) longLoginRequest(ctx context.Context, cookieState *longLoginCookieState, status *string) (*LongLoginSettings, error) {
// partial 保存partial,供当前处理流程使用
partial := &LongLoginSettings{}
cookieState.populate(partial)
if status != nil {
partial.Enabled = *status == "0"
}
// cookieURL 保存登录凭证URL,供当前处理流程使用
cookieURL := QueryLoginSettingsURL
// target 保存target,供当前处理流程使用
target := s.urlOrDefault(s.QueryLoginSettingsURL, QueryLoginSettingsURL)
// body 保存请求体,供当前处理流程使用
var body io.Reader
if status != nil {
cookieURL = SetLoginSettingsURL
target = s.urlOrDefault(s.SetLoginSettingsURL, SetLoginSettingsURL)
body = strings.NewReader("status=" + url.QueryEscape(*status))
}
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost, target, body)
if err != nil {
return partial, err
@@ -176,12 +196,15 @@ func (s Service) longLoginRequest(ctx context.Context, cookieState *longLoginCoo
if status != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
// hc 保存hc,供当前处理流程使用
hc := s.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: longLoginRequestTimout}
}
// requestCtx、cancel 保存请求Ctx、cancel,供当前处理流程使用
requestCtx, cancel := context.WithTimeout(req.Context(), longLoginRequestTimout)
defer cancel()
// resp、err 保存resp、err,供当前处理流程使用
resp, err := hc.Do(req.Clone(requestCtx))
if err != nil {
return partial, fmt.Errorf("保存登录信息请求失败: %w", err)
@@ -192,6 +215,7 @@ func (s Service) longLoginRequest(ctx context.Context, cookieState *longLoginCoo
partial.SetCookies = filterValidSetCookies(resp.Header.Values("Set-Cookie"))
cookieState.apply(cookieURL, partial.SetCookies)
cookieState.populate(partial)
// raw、err 保存raw、err,供当前处理流程使用
raw, err := readRenewBody(resp.Body)
if err != nil {
return partial, fmt.Errorf("保存登录信息响应读取失败: %w", err)
@@ -205,6 +229,7 @@ func (s Service) longLoginRequest(ctx context.Context, cookieState *longLoginCoo
}
return partial, nil
}
// value、ok 保存value、ok,供当前处理流程使用
value, ok := findReturnValue(raw)
if !ok {
return partial, fmt.Errorf("保存登录信息响应缺少 returnValue")
@@ -214,22 +239,29 @@ func (s Service) longLoginRequest(ctx context.Context, cookieState *longLoginCoo
return partial, nil
}
// longLoginSetBusinessOK 负责long登录SetBusinessOK相关处理。
func longLoginSetBusinessOK(raw []byte) bool {
// payload 保存请求载荷,供当前处理流程使用
var payload map[string]any
if json.Unmarshal(raw, &payload) != nil {
return false
}
if success, _ := payload["success"].(bool); success {
if // success 保存success,供当前处理流程使用
success, _ := payload["success"].(bool); success {
return true
}
if data, _ := payload["data"].(map[string]any); data != nil {
if // data 保存数据,供当前处理流程使用
data, _ := payload["data"].(map[string]any); data != nil {
// success 保存success,供当前处理流程使用
success, _ := data["success"].(bool)
return success
}
return false
}
// findReturnValue 负责findReturn值相关处理。
func findReturnValue(raw []byte) (map[string]any, bool) {
// payload 保存请求载荷,供当前处理流程使用
var payload map[string]any
if json.Unmarshal(raw, &payload) != nil {
return nil, false
@@ -237,16 +269,21 @@ func findReturnValue(raw []byte) (map[string]any, bool) {
return findMapChild(payload, "returnValue", 0)
}
// findMapChild 负责findMapChild相关处理。
func findMapChild(parent map[string]any, key string, depth int) (map[string]any, bool) {
if parent == nil || depth > 6 {
return nil, false
}
if value, ok := parent[key].(map[string]any); ok {
if // value、ok 保存value、ok,供当前处理流程使用
value, ok := parent[key].(map[string]any); ok {
return value, true
}
// child 表示当前遍历过程中的child
for _, child := range parent {
if nested, ok := child.(map[string]any); ok {
if value, found := findMapChild(nested, key, depth+1); found {
if // nested、ok 保存nested、ok,供当前处理流程使用
nested, ok := child.(map[string]any); ok {
if // value、found 保存value、found,供当前处理流程使用
value, found := findMapChild(nested, key, depth+1); found {
return value, true
}
}
@@ -274,6 +311,7 @@ type Result struct {
responseCookieURL string
}
// pendingRenewResult 保存pendingRenew结果,供当前处理流程使用
type pendingRenewResult struct {
result *Result
err error
@@ -290,7 +328,8 @@ func (r *Result) AwaitPending(ctx context.Context) (*Result, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case outcome, ok := <-r.pending:
case // outcome、ok 保存outcome、ok,供当前处理流程使用
outcome, ok := <-r.pending:
if !ok {
return nil, nil
}
@@ -301,24 +340,32 @@ func (r *Result) AwaitPending(ctx context.Context) (*Result, error) {
// RebaseResponseCookies 把续期响应的 Set-Cookie 应用到“当前最新”凭证状态。
// 后台 fetch 可能晚于其他 MTOP 请求返回,必须重放响应头而不是覆盖成请求发起
// 时计算出的旧快照。
// RebaseResponseCookies 负责Rebase响应Cookies相关处理。
func RebaseResponseCookies(currentCookies, currentMetadata string, result *Result) (string, string, bool) {
if result == nil || len(result.SetCookies) == 0 {
return currentCookies, currentMetadata, false
}
// requestURL 保存请求URL,供当前处理流程使用
requestURL := strings.TrimSpace(result.responseCookieURL)
if requestURL == "" {
requestURL = SilentHasLoginURL
}
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(currentMetadata); complete {
if // snapshot、complete 保存snapshot、complete,供当前处理流程使用
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(currentMetadata); complete {
// updated 保存updated,供当前处理流程使用
updated := cookierefresh.ApplySetCookies(snapshot, requestURL, result.SetCookies, time.Now(), goofishTopSite)
if updated == nil {
updated = []cookierefresh.BrowserCookie{}
}
// value 保存值,供当前处理流程使用
value, _ := cookierefresh.ScopedCookieHeaderForRequest(updated, goofishIMDocumentURL, goofishTopSite, time.Now())
// metadata 保存metadata,供当前处理流程使用
metadata := cookierefresh.MetadataWithSnapshot(currentMetadata, updated)
return value, metadata, value != currentCookies || metadata != currentMetadata
}
// value 保存值,供当前处理流程使用
value := MergeSetCookies(currentCookies, result.SetCookies)
// metadata 保存metadata,供当前处理流程使用
metadata := cookierefresh.MetadataWithoutSnapshot(currentMetadata)
return value, metadata, value != currentCookies || metadata != currentMetadata
}
@@ -332,6 +379,7 @@ type StepResult struct {
Message string
}
// autoLoginModeHavana 保存auto登录模式Havana,供当前处理流程使用
const (
autoLoginModeHavana = "havana"
autoLoginModeCookie3 = "cookie3"
@@ -342,6 +390,7 @@ const (
// branch, waits briefly, and sends exactly one silentHasLogin request.
// It never chains hasLogin/setLoginSettings or escalates to an interactive
// login from this proactive renewal path.
// RenewAPIFirst 负责RenewAPIFirst相关处理。
func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*Result, error) {
return s.renewAPIFirst(ctx, false, cookiesStr, snapshots...)
}
@@ -349,35 +398,49 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots
// RenewAfterSessionExpired 用于服务端已经明确返回 SESSION_EXPIRED 的恢复路径。
// sdkSilent 只用于限制健康账号的主动静默续期;它不能阻止一次已经被业务接口
// 证实为失效的凭证恢复。长登录凭证本身过期时仍拒绝请求并要求重新扫码。
// RenewAfterSessionExpired 负责RenewAfter会话Expired相关处理。
func (s Service) RenewAfterSessionExpired(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*Result, error) {
return s.renewAPIFirst(ctx, true, cookiesStr, snapshots...)
}
// renewAPIFirst 负责renewAPIFirst相关处理。
func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*Result, error) {
cookiesStr = strings.TrimSpace(cookiesStr)
// authoritativeSnapshot 保存authoritativeSnapshot,供当前处理流程使用
authoritativeSnapshot := len(snapshots) > 0 && snapshots[0] != nil
// documentURL 保存documentURL,供当前处理流程使用
documentURL := s.documentReferer()
// requestURL 保存请求URL,供当前处理流程使用
requestURL := s.urlOrDefault(s.SilentHasLoginURL, SilentHasLoginURL)
// now 保存now,供当前处理流程使用
now := time.Now()
// decisionCookies 保存decisionCookies,供当前处理流程使用
decisionCookies := cookiesStr
// requestCookies 保存请求Cookies,供当前处理流程使用
requestCookies := cookiesStr
// newCookies 保存newCookies,供当前处理流程使用
newCookies := cookiesStr
// snapshot 保存snapshot,供当前处理流程使用
var snapshot []cookierefresh.BrowserCookie
if authoritativeSnapshot {
snapshot = cookierefresh.NormalizeSnapshot(snapshots[0])
// havana_lgc_exp 由官网以 HttpOnly Cookie 下发。续期服务保存的是
// 浏览器完整 Cookie Jar,不能按 document.cookie 过滤,否则刚登录的
// 有效长登录凭证会被误判为不存在。
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, documentURL, goofishTopSite, now); authoritative {
if // scoped、authoritative 保存scoped、authoritative,供当前处理流程使用
scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, documentURL, goofishTopSite, now); authoritative {
decisionCookies = scoped
}
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, goofishTopSite, now); authoritative {
if // scoped、authoritative 保存scoped、authoritative,供当前处理流程使用
scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, goofishTopSite, now); authoritative {
requestCookies = scoped
}
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, goofishIMDocumentURL, goofishTopSite, now); authoritative {
if // scoped、authoritative 保存scoped、authoritative,供当前处理流程使用
scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, goofishIMDocumentURL, goofishTopSite, now); authoritative {
newCookies = scoped
}
}
// result 保存结果,供当前处理流程使用
result := &Result{
RenewMethod: "auto_login_plugin",
NewCookies: newCookies,
@@ -394,6 +457,7 @@ func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookies
result.NeedPasswordLogin = true
return result, nil
}
// mode、skipReason 保存mode、skip原因,供当前处理流程使用
mode, skipReason := autoLoginMode(firstCookieValues(decisionCookies), now)
if sessionExpired && skipReason == "fatigue" {
// 业务接口已明确证明 Session 失效,忽略主动续期疲劳标记,但仍只调用
@@ -406,6 +470,7 @@ func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookies
result.Message = autoLoginSkipMessage(skipReason)
return result, nil
}
// delay 保存延迟,供当前处理流程使用
delay := 2 * time.Second
if s.RetryDelay < 0 {
delay = 0
@@ -413,6 +478,7 @@ func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookies
delay = s.RetryDelay
}
if delay > 0 {
// timer 保存定时器,供当前处理流程使用
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
@@ -423,7 +489,9 @@ func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookies
case <-timer.C:
}
}
// call、err 保存call、err,供当前处理流程使用
call, err := s.callAutoLogin(ctx, requestCookies, mode)
// populate 保存populate,供当前处理流程使用
populate := func(target *Result, finished callResult, callErr error, promiseTimedOut bool) (*Result, error) {
target.RequestCount = 1
target.SetCookies = append([]string(nil), finished.SetCookies...)
@@ -432,10 +500,12 @@ func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookies
target.StepDetails = []StepResult{finished.Step}
}
if authoritativeSnapshot {
// updatedSnapshot 保存updatedSnapshot,供当前处理流程使用
updatedSnapshot := cookierefresh.ApplySetCookies(snapshot, requestURL, finished.SetCookies, time.Now(), goofishTopSite)
target.CookieSnapshot = updatedSnapshot
target.CookieSnapshotComplete = true
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(updatedSnapshot, goofishIMDocumentURL, goofishTopSite, time.Now()); authoritative {
if // scoped、authoritative 保存scoped、authoritative,供当前处理流程使用
scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(updatedSnapshot, goofishIMDocumentURL, goofishTopSite, time.Now()); authoritative {
target.NewCookies = scoped
}
target.UpdatedCookieNames = cookierefresh.ChangedSnapshotLabels(snapshot, updatedSnapshot)
@@ -457,6 +527,7 @@ func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookies
target.NeedPasswordLogin = true
return target, callErr
}
// message 保存消息,供当前处理流程使用
message := "静默续期成功"
if !finished.Step.BusinessOK {
message = firstNonEmpty(finished.Step.Message, "静默续期未通过")
@@ -471,14 +542,17 @@ func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookies
result.StepDetails = []StepResult{call.Step}
result.Message = call.Step.Message
result.NeedPasswordLogin = false
// pending 保存pending,供当前处理流程使用
pending := make(chan pendingRenewResult, 1)
result.pending = pending
go func() {
// outcome、ok 保存outcome、ok,供当前处理流程使用
outcome, ok := <-call.pending
if !ok {
close(pending)
return
}
// late 保存late,供当前处理流程使用
late := &Result{
RenewMethod: "auto_login_plugin",
NewCookies: newCookies,
@@ -490,6 +564,7 @@ func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookies
}
// Promise 超时只描述前端等待窗口;底层响应到达后必须按真实
// HTTP/业务结果生成终态,不能永久标记为失败。
// late、lateErr 保存late、lateErr,供当前处理流程使用
late, lateErr := populate(late, outcome.call, outcome.err, false)
pending <- pendingRenewResult{result: late, err: lateErr}
close(pending)
@@ -499,6 +574,7 @@ func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookies
return populate(result, call, err, false)
}
// autoLoginModeWithoutFatigue 负责auto登录模式WithoutFatigue相关处理。
func autoLoginModeWithoutFatigue(cookies map[string]string, now time.Time) (mode, skipReason string) {
if cookieTimeAfter(cookies["havana_lgc_exp"], now) {
return autoLoginModeHavana, ""
@@ -509,6 +585,7 @@ func autoLoginModeWithoutFatigue(cookies map[string]string, now time.Time) (mode
return "", "long_login_expired"
}
// autoLoginMode 负责auto登录模式相关处理。
func autoLoginMode(cookies map[string]string, now time.Time) (mode, skipReason string) {
if strictCookieTimeAfter(cookies["sdkSilent"], now) {
return "", "fatigue"
@@ -524,15 +601,20 @@ func autoLoginMode(cookies map[string]string, now time.Time) (mode, skipReason s
// firstCookieValues 对齐浏览器 document.cookie getter:同名 Cookie 按浏览器
// header 顺序读取首个值。ScopedCookieHeaderForRequest 已把更长 Path 排在前面。
// firstCookieValues 负责first登录凭证Values相关处理。
func firstCookieValues(cookieHeader string) map[string]string {
// values 保存values,供当前处理流程使用
values := make(map[string]string)
// part 表示当前遍历过程中的part
for _, part := range strings.Split(cookieHeader, ";") {
// name、value、ok 保存name、value、ok,供当前处理流程使用
name, value, ok := strings.Cut(strings.TrimSpace(part), "=")
name = strings.TrimSpace(name)
if !ok || name == "" {
continue
}
if _, exists := values[name]; exists {
if // exists 保存exists,供当前处理流程使用
_, exists := values[name]; exists {
continue
}
values[name] = strings.TrimSpace(value)
@@ -540,20 +622,24 @@ func firstCookieValues(cookieHeader string) map[string]string {
return values
}
// strictCookieTimeAfter 负责strict登录凭证时间After相关处理。
func strictCookieTimeAfter(raw string, now time.Time) bool {
raw = strings.TrimSpace(raw)
if raw == "" {
return false
}
// millis、err 保存millis、err,供当前处理流程使用
millis, err := strconv.ParseInt(raw, 10, 64)
return err == nil && millis > now.UnixMilli()
}
// cookieTimeAfter 负责登录凭证时间After相关处理。
func cookieTimeAfter(raw string, now time.Time) bool {
raw = strings.TrimSpace(raw)
if raw == "" {
return false
}
// millis、err 保存millis、err,供当前处理流程使用
millis, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
// plugin.js 使用 Invalid Date <= now;结果为 false,因此非空异常值
@@ -563,6 +649,7 @@ func cookieTimeAfter(raw string, now time.Time) bool {
return millis > now.UnixMilli()
}
// autoLoginSkipMessage 负责auto登录Skip消息相关处理。
func autoLoginSkipMessage(reason string) string {
switch reason {
case "fatigue":
@@ -574,6 +661,7 @@ func autoLoginSkipMessage(reason string) string {
}
}
// callResult 保存call结果,供当前处理流程使用
type callResult struct {
Step StepResult
SetCookies []string
@@ -581,17 +669,22 @@ type callResult struct {
pending <-chan callOutcome
}
// callOutcome 保存callOutcome,供当前处理流程使用
type callOutcome struct {
call callResult
err error
}
// callAutoLogin 负责callAuto登录相关处理。
func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (callResult, error) {
// partial 保存partial,供当前处理流程使用
partial := callResult{Step: StepResult{Name: "silentHasLogin"}}
// req、err 保存req、err,供当前处理流程使用
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.SilentHasLoginURL, SilentHasLoginURL), nil)
if err != nil {
return partial, err
}
// query 保存查询,供当前处理流程使用
query := [][2]string{
{"documentReferer", s.documentReferer()},
{"appName", "xianyu"},
@@ -611,29 +704,38 @@ func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (ca
return s.doRenewRequest(req, "silentHasLogin")
}
// doRenewRequest 负责doRenew请求相关处理。
func (s Service) doRenewRequest(req *http.Request, name string) (callResult, error) {
// hc 保存hc,供当前处理流程使用
hc := s.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: backgroundFetchTimeout}
}
// Promise.race 的计时器不能取消底层 fetch。使用 WithoutCancel 让 2 秒
// 窗口结束后请求继续,但仍以 30 秒硬上限防止后台泄漏。
// requestCtx、cancel 保存请求Ctx、cancel,供当前处理流程使用
requestCtx, cancel := context.WithTimeout(context.WithoutCancel(req.Context()), backgroundFetchTimeout)
// backgroundReq 保存backgroundReq,供当前处理流程使用
backgroundReq := req.Clone(requestCtx)
// done 保存done,供当前处理流程使用
done := make(chan callOutcome, 1)
go func() {
defer cancel()
// call、err 保存call、err,供当前处理流程使用
call, err := executeRenewRequest(hc, backgroundReq, name)
done <- callOutcome{call: call, err: err}
}()
// timer 保存定时器,供当前处理流程使用
timer := time.NewTimer(s.promiseTimeout())
defer timer.Stop()
select {
case <-req.Context().Done():
cancel()
// result 保存结果,供当前处理流程使用
result := callResult{Step: StepResult{Name: name, Message: req.Context().Err().Error()}}
return result, req.Context().Err()
case outcome := <-done:
case // outcome 保存outcome,供当前处理流程使用
outcome := <-done:
return outcome.call, outcome.err
case <-timer.C:
return callResult{
@@ -643,6 +745,7 @@ func (s Service) doRenewRequest(req *http.Request, name string) (callResult, err
}
}
// promiseTimeout 负责promiseTimeout相关处理。
func (s Service) promiseTimeout() time.Duration {
if s.PromiseTimeout > 0 {
return s.PromiseTimeout
@@ -650,8 +753,11 @@ func (s Service) promiseTimeout() time.Duration {
return defaultRequestTimout
}
// executeRenewRequest 负责executeRenew请求相关处理。
func executeRenewRequest(hc *http.Client, req *http.Request, name string) (callResult, error) {
// result 保存结果,供当前处理流程使用
result := callResult{Step: StepResult{Name: name}}
// resp、err 保存resp、err,供当前处理流程使用
resp, err := hc.Do(req)
if err != nil {
result.Step.Message = fmt.Sprintf("请求失败: %v", err)
@@ -663,6 +769,7 @@ func executeRenewRequest(hc *http.Client, req *http.Request, name string) (callR
result.SetCookies = filterValidSetCookies(resp.Header.Values("Set-Cookie"))
result.Step.HTTPStatus = resp.StatusCode
result.Step.SetCookieCount = len(result.SetCookies)
// body、err 保存body、err,供当前处理流程使用
body, err := readRenewBody(resp.Body)
if err != nil {
result.Step.Message = fmt.Sprintf("响应读取失败: %v", err)
@@ -682,25 +789,33 @@ func executeRenewRequest(hc *http.Client, req *http.Request, name string) (callR
return result, nil
}
// renewBusinessOK 负责renewBusinessOK相关处理。
func renewBusinessOK(body []byte) bool {
if len(body) == 0 {
return false
}
// payload 保存请求载荷,供当前处理流程使用
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(body, &payload); err != nil {
return false
}
// content 保存内容,供当前处理流程使用
content, _ := payload["content"].(map[string]any)
if data, _ := payload["data"].(map[string]any); data != nil {
if nested, _ := data["content"].(map[string]any); nested != nil {
if // data 保存数据,供当前处理流程使用
data, _ := payload["data"].(map[string]any); data != nil {
if // nested 保存nested,供当前处理流程使用
nested, _ := data["content"].(map[string]any); nested != nil {
content = nested
}
}
if content == nil {
return false
}
// data 保存数据,供当前处理流程使用
data, _ := content["data"].(map[string]any)
if data != nil {
// finished 保存finished,供当前处理流程使用
finished, _ := data["processFinished"].(bool)
if finished && numericResultCode(data["resultCode"]) == 100 {
return true
@@ -709,11 +824,14 @@ func renewBusinessOK(body []byte) bool {
return false
}
// numericResultCode 负责numeric结果Code相关处理。
func numericResultCode(v any) int {
switch value := v.(type) {
switch // value 保存值,供当前处理流程使用
value := v.(type) {
case float64:
return int(value)
case json.Number:
// n 保存n,供当前处理流程使用
n, _ := strconv.Atoi(value.String())
return n
case int:
@@ -723,6 +841,7 @@ func numericResultCode(v any) int {
}
}
// setSilentHasLoginHeaders 负责setSilentHas登录Headers相关处理。
func setSilentHasLoginHeaders(req *http.Request, cookiesStr, documentReferer string) {
xianyu.ApplyBrowserFingerprint(req.Header)
req.Header.Set("Accept", "*/*")
@@ -735,17 +854,21 @@ func setSilentHasLoginHeaders(req *http.Request, cookiesStr, documentReferer str
req.Header.Set("Cookie", strings.ReplaceAll(strings.ReplaceAll(cookiesStr, "\n", ""), "\r", ""))
}
// appendOrderedQuery 负责appendOrdered查询相关处理。
func appendOrderedQuery(target *url.URL, values [][2]string) {
// parts 保存parts,供当前处理流程使用
parts := make([]string, 0, len(values)+1)
if strings.TrimSpace(target.RawQuery) != "" {
parts = append(parts, target.RawQuery)
}
// item 表示当前遍历过程中的商品
for _, item := range values {
parts = append(parts, url.QueryEscape(item[0])+"="+url.QueryEscape(item[1]))
}
target.RawQuery = strings.Join(parts, "&")
}
// urlOrDefault 负责地址OrDefault相关处理。
func (s Service) urlOrDefault(v, fallback string) string {
if strings.TrimSpace(v) != "" {
return v
@@ -753,6 +876,7 @@ func (s Service) urlOrDefault(v, fallback string) string {
return fallback
}
// documentReferer 负责documentReferer相关处理。
func (s Service) documentReferer() string {
if strings.TrimSpace(s.DocumentReferer) != "" {
return strings.TrimSpace(s.DocumentReferer)
@@ -760,7 +884,9 @@ func (s Service) documentReferer() string {
return "https://www.goofish.com/im"
}
// readRenewBody 负责readRenew请求体相关处理。
func readRenewBody(r io.Reader) ([]byte, error) {
// body、err 保存body、err,供当前处理流程使用
body, err := io.ReadAll(io.LimitReader(r, maxRenewBodyBytes+1))
if err != nil {
return nil, err
@@ -771,7 +897,9 @@ func readRenewBody(r io.Reader) ([]byte, error) {
return body, nil
}
// firstNonEmpty 负责firstNonEmpty相关处理。
func firstNonEmpty(values ...string) string {
// v 表示当前遍历过程中的v
for _, v := range values {
if strings.TrimSpace(v) != "" {
return v
@@ -780,11 +908,14 @@ func firstNonEmpty(values ...string) string {
return ""
}
// filterValidSetCookies 负责filter有效SetCookies相关处理。
func filterValidSetCookies(setCookies []string) []string {
if len(setCookies) == 0 {
return nil
}
// out 保存out,供当前处理流程使用
out := make([]string, 0, len(setCookies))
// sc 表示当前遍历过程中的sc
for _, sc := range setCookies {
if strings.TrimSpace(sc) == "" {
continue
@@ -796,9 +927,13 @@ func filterValidSetCookies(setCookies []string) []string {
// MergeSetCookies 将 Set-Cookie 头合并到 Cookie 头字符串。只保留 name=value,
// 忽略 Path/Domain/Expires 等属性,因为后续出站请求只需要 Cookie header。
// MergeSetCookies 负责MergeSetCookies相关处理。
func MergeSetCookies(original string, setCookies []string) string {
// cookies 保存cookies,供当前处理流程使用
cookies := protocol.TransCookies(original)
// sc 表示当前遍历过程中的sc
for _, sc := range setCookies {
// parsed、err 保存parsed、err,供当前处理流程使用
parsed, err := http.ParseSetCookie(sc)
if err != nil || strings.TrimSpace(parsed.Name) == "" {
continue
@@ -814,16 +949,23 @@ func MergeSetCookies(original string, setCookies []string) string {
// ChangedCookieNames 返回 newCookies 相对 original 变化过的字段名,按字典序排序。
func ChangedCookieNames(original, newCookies string) []string {
// oldMap 保存oldMap,供当前处理流程使用
oldMap := protocol.TransCookies(original)
// newMap 保存newMap,供当前处理流程使用
newMap := protocol.TransCookies(newCookies)
// changed 保存changed,供当前处理流程使用
changed := make([]string, 0)
// seen 保存seen,供当前处理流程使用
seen := make(map[string]struct{}, len(oldMap)+len(newMap))
// k 表示当前遍历过程中的k
for k := range oldMap {
seen[k] = struct{}{}
}
// k 表示当前遍历过程中的k
for k := range newMap {
seen[k] = struct{}{}
}
// k 表示当前遍历过程中的k
for k := range seen {
if oldMap[k] != newMap[k] {
changed = append(changed, k)
@@ -833,13 +975,18 @@ func ChangedCookieNames(original, newCookies string) []string {
return changed
}
// marshalCookies 负责marshalCookies相关处理。
func marshalCookies(cookies map[string]string) string {
// keys 保存keys,供当前处理流程使用
keys := make([]string, 0, len(cookies))
// k 表示当前遍历过程中的k
for k := range cookies {
keys = append(keys, k)
}
sort.Strings(keys)
// parts 保存parts,供当前处理流程使用
parts := make([]string, 0, len(keys))
// k 表示当前遍历过程中的k
for _, k := range keys {
parts = append(parts, k+"="+cookies[k])
}
+155 -10
View File
@@ -17,26 +17,36 @@ import (
"xianyu-go/internal/xianyu/cookierefresh"
)
// roundTripFunc 保存roundTripFunc,供当前处理流程使用
type roundTripFunc func(*http.Request) (*http.Response, error)
// RoundTrip 负责RoundTrip相关处理。
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
// failingReadCloser 保存failingReadCloser,供当前处理流程使用
type failingReadCloser struct {
err error
}
// Read 读取当前值。
func (r failingReadCloser) Read([]byte) (int, error) { return 0, r.err }
func (failingReadCloser) Close() error { return nil }
// Close 关闭当前值。
func (failingReadCloser) Close() error { return nil }
// futureMillis 负责futureMillis相关处理。
func futureMillis(d time.Duration) string {
return strconv.FormatInt(time.Now().Add(d).UnixMilli(), 10)
}
// useTestDesktopFingerprint 负责useTestDesktopFingerprint相关处理。
func useTestDesktopFingerprint(t *testing.T) xianyu.BrowserFingerprint {
t.Helper()
// old 保存old,供当前处理流程使用
old := xianyu.CurrentBrowserFingerprint()
// fingerprint 保存fingerprint,供当前处理流程使用
fingerprint := xianyu.BrowserFingerprint{
UserAgent: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/999.0.0.0 Safari/537.36`,
SecChUA: `"Chromium";v="999", "Google Chrome";v="999", "Not_A Brand";v="24"`,
@@ -48,9 +58,12 @@ func useTestDesktopFingerprint(t *testing.T) xianyu.BrowserFingerprint {
return fingerprint
}
// useTestLinuxFingerprint 负责useTestLinuxFingerprint相关处理。
func useTestLinuxFingerprint(t *testing.T) xianyu.BrowserFingerprint {
t.Helper()
// old 保存old,供当前处理流程使用
old := xianyu.CurrentBrowserFingerprint()
// fingerprint 保存fingerprint,供当前处理流程使用
fingerprint := xianyu.BrowserFingerprint{
UserAgent: `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36`,
SecChUA: `"Chromium";v="138", "Not_A Brand";v="24"`,
@@ -62,8 +75,11 @@ func useTestLinuxFingerprint(t *testing.T) xianyu.BrowserFingerprint {
return fingerprint
}
// TestAutoLoginModeMatchesBrowserPlugin 负责TestAuto登录模式Matches浏览器Plugin相关处理。
func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Now()
// tests 保存tests,供当前处理流程使用
tests := []struct {
name string
cookies map[string]string
@@ -76,8 +92,10 @@ func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
{name: "cookie3 backup", cookies: map[string]string{"havana_lgc_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10), "cookie3_bak_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeCookie3},
{name: "malformed long-login expiry follows browser Invalid Date branch", cookies: map[string]string{"havana_lgc_exp": "bad", "cookie3_bak_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeHavana},
}
// tt 表示当前遍历过程中的tt
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// mode、reason 保存mode、reason,供当前处理流程使用
mode, reason := autoLoginMode(tt.cookies, now)
if mode != tt.wantMode || reason != tt.wantReason {
t.Fatalf("mode=%q reason=%q, want mode=%q reason=%q", mode, reason, tt.wantMode, tt.wantReason)
@@ -86,22 +104,29 @@ func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
}
}
// TestAutoLoginDecisionUsesFirstCookieForDuplicatePaths 负责TestAuto登录DecisionUsesFirst登录凭证ForDuplicatePaths相关处理。
func TestAutoLoginDecisionUsesFirstCookieForDuplicatePaths(t *testing.T) {
// now 保存now,供当前处理流程使用
now := time.Now()
// cookies 保存cookies,供当前处理流程使用
cookies := strings.Join([]string{
"sdkSilent=" + strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10),
"sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10),
"havana_lgc_exp=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10),
"havana_lgc_exp=" + strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10),
}, "; ")
// mode、reason 保存mode、reason,供当前处理流程使用
mode, reason := autoLoginMode(firstCookieValues(cookies), now)
if mode != autoLoginModeHavana || reason != "" {
t.Fatalf("mode=%q reason=%q;应采用浏览器排序后的首个同名 Cookie", mode, reason)
}
}
// TestLongLoginSettingsMatchOfficialRequest 负责TestLong登录设置MatchOfficial请求相关处理。
func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) {
// calls 保存calls,供当前处理流程使用
var calls atomic.Int32
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
if r.Method != http.MethodPost {
@@ -117,7 +142,8 @@ func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) {
t.Fatalf("Cookie=%q", r.Header.Get("Cookie"))
}
if strings.Contains(r.URL.Path, "set") {
if err := r.ParseForm(); err != nil || r.Form.Get("status") != "0" {
if // err 保存err,供当前处理流程使用
err := r.ParseForm(); err != nil || r.Form.Get("status") != "0" {
t.Fatalf("set form=%v err=%v", r.Form, err)
}
}
@@ -130,16 +156,19 @@ func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) {
}))
defer srv.Close()
// service 保存service,供当前处理流程使用
service := Service{
HTTPClient: srv.Client(),
QueryLoginSettingsURL: srv.URL + "/queryLoginSettings.do",
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
DocumentReferer: "https://www.goofish.com/im",
}
// queried、err 保存queried、err,供当前处理流程使用
queried, err := service.QueryLongLoginSettings(context.Background(), "unb=1")
if err != nil || !queried.CanOpenLongLogin || !queried.Enabled {
t.Fatalf("query result=%+v err=%v", queried, err)
}
// set、err 保存set、err,供当前处理流程使用
set, err := service.SetLongLoginSettings(context.Background(), queried.NewCookies, true)
if err != nil || !set.Enabled || len(set.SetCookies) != 2 || !strings.Contains(set.NewCookies, "havana_lgc_exp=") {
t.Fatalf("set result=%+v err=%v", set, err)
@@ -149,36 +178,48 @@ func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) {
}
}
// TestRenewAfterSessionExpiredBypassesOnlyFatigue 负责TestRenewAfter会话ExpiredBypassesOnlyFatigue相关处理。
func TestRenewAfterSessionExpiredBypassesOnlyFatigue(t *testing.T) {
// calls 保存calls,供当前处理流程使用
var calls atomic.Int32
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls.Add(1)
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "recovered"})
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
}))
defer srv.Close()
// now 保存now,供当前处理流程使用
now := time.Now()
// cookies 保存cookies,供当前处理流程使用
cookies := "unb=1; sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) +
"; havana_lgc_exp=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)
// service 保存service,供当前处理流程使用
service := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
// proactive、err 保存proactive、err,供当前处理流程使用
proactive, err := service.RenewAPIFirst(context.Background(), cookies)
if err != nil || !proactive.Skipped || proactive.SkipReason != "fatigue" || calls.Load() != 0 {
t.Fatalf("proactive=%+v calls=%d err=%v", proactive, calls.Load(), err)
}
// recovered、err 保存recovered、err,供当前处理流程使用
recovered, err := service.RenewAfterSessionExpired(context.Background(), cookies)
if err != nil || !recovered.Success || calls.Load() != 1 || !strings.Contains(recovered.NewCookies, "havana_lgc2_77=recovered") {
t.Fatalf("recovered=%+v calls=%d err=%v", recovered, calls.Load(), err)
}
// expiredLongLogin 保存expiredLong登录,供当前处理流程使用
expiredLongLogin := "unb=1; sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) +
"; havana_lgc_exp=" + strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)
// blocked、err 保存blocked、err,供当前处理流程使用
blocked, err := service.RenewAfterSessionExpired(context.Background(), expiredLongLogin)
if err != nil || !blocked.Skipped || blocked.SkipReason != "long_login_expired" || calls.Load() != 1 {
t.Fatalf("blocked=%+v calls=%d err=%v", blocked, calls.Load(), err)
}
}
// TestLongLoginRequestKeepsResponseCookiesOnFailures 负责TestLong登录请求Keeps响应CookiesOnFailures相关处理。
func TestLongLoginRequestKeepsResponseCookiesOnFailures(t *testing.T) {
// tests 保存tests,供当前处理流程使用
tests := []struct {
name string
statusCode int
@@ -200,8 +241,10 @@ func TestLongLoginRequestKeepsResponseCookiesOnFailures(t *testing.T) {
body: io.NopCloser(strings.NewReader(`{"error":"busy"}`)),
},
}
// tt 表示当前遍历过程中的tt
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// client 保存client,供当前处理流程使用
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: tt.statusCode,
@@ -211,6 +254,7 @@ func TestLongLoginRequestKeepsResponseCookiesOnFailures(t *testing.T) {
Body: tt.body,
}, nil
})}
// settings、err 保存settings、err,供当前处理流程使用
settings, err := (Service{HTTPClient: client}).QueryLongLoginSettings(context.Background(), "unb=1")
if err == nil || settings == nil {
t.Fatalf("settings=%+v err=%v", settings, err)
@@ -222,8 +266,11 @@ func TestLongLoginRequestKeepsResponseCookiesOnFailures(t *testing.T) {
}
}
// TestSetLongLoginSettingsMergesSetAndFailedQueryCookies 负责TestSetLong登录设置MergesSetAnd失败查询Cookies相关处理。
func TestSetLongLoginSettingsMergesSetAndFailedQueryCookies(t *testing.T) {
// calls 保存calls,供当前处理流程使用
var calls atomic.Int32
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
if strings.Contains(r.URL.Path, "set") {
@@ -240,11 +287,13 @@ func TestSetLongLoginSettingsMergesSetAndFailedQueryCookies(t *testing.T) {
}))
defer srv.Close()
// svc 保存svc,供当前处理流程使用
svc := Service{
HTTPClient: srv.Client(),
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
QueryLoginSettingsURL: srv.URL + "/queryLoginSettings.do",
}
// settings、err 保存settings、err,供当前处理流程使用
settings, err := svc.SetLongLoginSettings(context.Background(), "unb=1", true)
if err == nil || settings == nil {
t.Fatalf("settings=%+v err=%v", settings, err)
@@ -257,8 +306,11 @@ func TestSetLongLoginSettingsMergesSetAndFailedQueryCookies(t *testing.T) {
}
}
// TestSetLongLoginSettingsScopesCompleteJarBetweenSetAndQuery 负责TestSetLong登录设置ScopesCompleteJarBetweenSetAnd查询相关处理。
func TestSetLongLoginSettingsScopesCompleteJarBetweenSetAndQuery(t *testing.T) {
// queryCookie 保存查询登录凭证,供当前处理流程使用
var queryCookie string
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "set") {
w.Header().Add("Set-Cookie", "set_only=hidden; Path=/ac/account/setLoginSettings.do; Secure")
@@ -270,15 +322,18 @@ func TestSetLongLoginSettingsScopesCompleteJarBetweenSetAndQuery(t *testing.T) {
_, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
}))
defer srv.Close()
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "shared", Value: "old", Domain: "passport.goofish.com", Path: "/ac/account", Secure: true},
{Name: "im_only", Value: "visible", Domain: "www.goofish.com", Path: "/im", Secure: true},
}
// svc 保存svc,供当前处理流程使用
svc := Service{
HTTPClient: srv.Client(),
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
QueryLoginSettingsURL: srv.URL + "/queryLoginSettings.do",
}
// settings、err 保存settings、err,供当前处理流程使用
settings, err := svc.SetLongLoginSettings(context.Background(), "fallback=must-not-leak", true, snapshot)
if err != nil {
t.Fatal(err)
@@ -294,9 +349,13 @@ func TestSetLongLoginSettingsScopesCompleteJarBetweenSetAndQuery(t *testing.T) {
}
}
// TestRenewAPIFirstHavanaSendsOneSilentRequest 负责TestRenewAPIFirstHavanaSendsOneSilent请求相关处理。
func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
// fingerprint 保存fingerprint,供当前处理流程使用
fingerprint := useTestDesktopFingerprint(t)
// calls 保存calls,供当前处理流程使用
var calls atomic.Int32
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
if r.Method != http.MethodPost || r.URL.Query().Get("appEntrance") != "xianyu_sdkSilent" || r.URL.Query().Get("ltl") != "true" {
@@ -305,13 +364,16 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
if r.URL.Query().Get("skipSessionFilter") != "" || r.URL.Query().Get("c2r") != "" {
t.Fatalf("havana mode included cookie3 flags: %s", r.URL.RawQuery)
}
if got := r.URL.Query().Get("documentReferer"); got != "https://www.goofish.com/im" {
if // got 保存got,供当前处理流程使用
got := r.URL.Query().Get("documentReferer"); got != "https://www.goofish.com/im" {
t.Fatalf("documentReferer=%q", got)
}
if got := r.Header.Get("User-Agent"); got != fingerprint.UserAgent {
if // got 保存got,供当前处理流程使用
got := r.Header.Get("User-Agent"); got != fingerprint.UserAgent {
t.Fatalf("User-Agent=%q", got)
}
if got := r.Header.Get("Cookie"); !strings.Contains(got, "unb=1") {
if // got 保存got,供当前处理流程使用
got := r.Header.Get("Cookie"); !strings.Contains(got, "unb=1") {
t.Fatalf("Cookie=%q", got)
}
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: futureMillis(time.Hour)})
@@ -319,8 +381,11 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
}))
defer srv.Close()
// svc 保存svc,供当前处理流程使用
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, DocumentReferer: "https://www.goofish.com/im", RetryDelay: -1}
// input 保存input,供当前处理流程使用
input := "unb=1; havana_lgc_exp=" + futureMillis(time.Hour)
// res、err 保存res、err,供当前处理流程使用
res, err := svc.RenewAPIFirst(context.Background(), input)
if err != nil {
t.Fatalf("RenewAPIFirst: %v", err)
@@ -333,23 +398,30 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
}
}
// TestRenewAPIFirstUsesBrowserCookieScopes 负责TestRenewAPIFirstUses浏览器登录凭证Scopes相关处理。
func TestRenewAPIFirstUsesBrowserCookieScopes(t *testing.T) {
useTestDesktopFingerprint(t)
// receivedCookie 保存received登录凭证,供当前处理流程使用
var receivedCookie string
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedCookie = r.Header.Get("Cookie")
_, _ = w.Write([]byte(`{"data":{"content":{"data":{"processFinished":true,"resultCode":100}}}}`))
}))
defer srv.Close()
// host 保存host,供当前处理流程使用
host := strings.TrimPrefix(srv.URL, "http://")
host = strings.Split(host, ":")[0]
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/", HTTPOnly: true},
{Name: "request_only", Value: "passport", Domain: host, Path: "/"},
{Name: "www_only", Value: "private", Domain: "www.goofish.com", Path: "/im"},
{Name: "http_only_document", Value: "hidden", Domain: ".goofish.com", Path: "/", HTTPOnly: true},
}
// svc 保存svc,供当前处理流程使用
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, DocumentReferer: "https://www.goofish.com/im", RetryDelay: -1}
// res、err 保存res、err,供当前处理流程使用
res, err := svc.RenewAPIFirst(context.Background(), "havana_lgc_exp="+futureMillis(time.Hour)+"; request_only=passport; www_only=private", snapshot)
if err != nil || !res.Success {
t.Fatalf("result=%+v err=%v", res, err)
@@ -362,53 +434,71 @@ func TestRenewAPIFirstUsesBrowserCookieScopes(t *testing.T) {
}
}
// TestRenewAPIFirstUsesHTTPOnlyLongLoginCookieForDecision 负责TestRenewAPIFirstUsesHTTPOnlyLong登录登录凭证ForDecision相关处理。
func TestRenewAPIFirstUsesHTTPOnlyLongLoginCookieForDecision(t *testing.T) {
useTestDesktopFingerprint(t)
// calls 保存calls,供当前处理流程使用
var calls atomic.Int32
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
_, _ = w.Write([]byte(`{"data":{"content":{"data":{"processFinished":true,"resultCode":100}}}}`))
}))
defer srv.Close()
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{{
Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/", HTTPOnly: true,
}}
// svc 保存svc,供当前处理流程使用
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
// res、err 保存res、err,供当前处理流程使用
res, err := svc.RenewAPIFirst(context.Background(), "", snapshot)
if err != nil || res == nil || !res.Success || res.Skipped || res.RequestCount != 1 || calls.Load() != 1 {
t.Fatalf("result=%+v calls=%d err=%v", res, calls.Load(), err)
}
}
// TestRenewAPIFirstRunsWithLinuxChromiumFingerprint 负责TestRenewAPIFirst运行记录WithLinuxChromiumFingerprint相关处理。
func TestRenewAPIFirstRunsWithLinuxChromiumFingerprint(t *testing.T) {
// fingerprint 保存fingerprint,供当前处理流程使用
fingerprint := useTestLinuxFingerprint(t)
// calls 保存calls,供当前处理流程使用
var calls atomic.Int32
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
if got := r.Header.Get("User-Agent"); got != fingerprint.UserAgent {
if // got 保存got,供当前处理流程使用
got := r.Header.Get("User-Agent"); got != fingerprint.UserAgent {
t.Fatalf("User-Agent=%q", got)
}
if got := r.Header.Get("sec-ch-ua-platform"); got != `"Linux"` {
if // got 保存got,供当前处理流程使用
got := r.Header.Get("sec-ch-ua-platform"); got != `"Linux"` {
t.Fatalf("sec-ch-ua-platform=%q", got)
}
_, _ = w.Write([]byte(`{"data":{"content":{"data":{"processFinished":true,"resultCode":100}}}}`))
}))
defer srv.Close()
// svc 保存svc,供当前处理流程使用
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
// res、err 保存res、err,供当前处理流程使用
res, err := svc.RenewAPIFirst(context.Background(), "havana_lgc_exp="+futureMillis(time.Hour))
if err != nil || res == nil || !res.Success || res.Skipped || res.RequestCount != 1 || calls.Load() != 1 {
t.Fatalf("result=%+v calls=%d err=%v", res, calls.Load(), err)
}
}
// TestRenewAPIFirstUsesTopSiteAndAppliesPartitionedSetCookie 负责TestRenewAPIFirstUsesTopSiteAndAppliesPartitionedSet登录凭证相关处理。
func TestRenewAPIFirstUsesTopSiteAndAppliesPartitionedSetCookie(t *testing.T) {
useTestDesktopFingerprint(t)
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
{Name: "passport_partitioned", Value: "right", Domain: "passport.goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
{Name: "wrong_partition", Value: "hidden", Domain: "passport.goofish.com", Path: "/", Secure: true, PartitionKey: "https://example.com"},
}
// client 保存client,供当前处理流程使用
client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
// cookies 保存cookies,供当前处理流程使用
cookies := req.Header.Get("Cookie")
if !strings.Contains(cookies, "passport_partitioned=right") || strings.Contains(cookies, "wrong_partition=hidden") {
t.Fatalf("partitioned request Cookie=%q", cookies)
@@ -421,7 +511,9 @@ func TestRenewAPIFirstUsesTopSiteAndAppliesPartitionedSetCookie(t *testing.T) {
Body: io.NopCloser(strings.NewReader(`{"data":{"content":{"data":{"processFinished":true,"resultCode":100}}}}`)),
}, nil
})}
// svc 保存svc,供当前处理流程使用
svc := Service{HTTPClient: client, RetryDelay: -1}
// res、err 保存res、err,供当前处理流程使用
res, err := svc.RenewAPIFirst(context.Background(), "", snapshot)
if err != nil || !res.Success {
t.Fatalf("result=%+v err=%v", res, err)
@@ -429,7 +521,9 @@ func TestRenewAPIFirstUsesTopSiteAndAppliesPartitionedSetCookie(t *testing.T) {
if !res.CookieSnapshotComplete || !strings.Contains(res.NewCookies, "rotated=fresh") {
t.Fatalf("authoritative renewal result=%+v", res)
}
// found 保存found,供当前处理流程使用
found := false
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range res.CookieSnapshot {
if cookie.Name == "rotated" && cookie.Value == "fresh" && cookie.PartitionKey == goofishTopSite {
found = true
@@ -440,11 +534,14 @@ func TestRenewAPIFirstUsesTopSiteAndAppliesPartitionedSetCookie(t *testing.T) {
}
}
// TestRenewAPIFirstKeepsSetCookieWhenBodyReadFails 负责TestRenewAPIFirstKeepsSet登录凭证When请求体ReadFails相关处理。
func TestRenewAPIFirstKeepsSetCookieWhenBodyReadFails(t *testing.T) {
useTestDesktopFingerprint(t)
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{
{Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/", Secure: true},
}
// client 保存client,供当前处理流程使用
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
@@ -454,7 +551,9 @@ func TestRenewAPIFirstKeepsSetCookieWhenBodyReadFails(t *testing.T) {
Body: failingReadCloser{err: errors.New("broken response body")},
}, nil
})}
// svc 保存svc,供当前处理流程使用
svc := Service{HTTPClient: client, RetryDelay: -1}
// res、err 保存res、err,供当前处理流程使用
res, err := svc.RenewAPIFirst(context.Background(), "", snapshot)
if err == nil || res == nil {
t.Fatalf("result=%+v err=%v", res, err)
@@ -464,9 +563,12 @@ func TestRenewAPIFirstKeepsSetCookieWhenBodyReadFails(t *testing.T) {
}
}
// TestRenewAPIFirstTreatsNonNilEmptySnapshotAsAuthoritative 负责TestRenewAPIFirstTreatsNonNilEmptySnapshotAsAuthoritative相关处理。
func TestRenewAPIFirstTreatsNonNilEmptySnapshotAsAuthoritative(t *testing.T) {
useTestDesktopFingerprint(t)
// emptySnapshot 保存emptySnapshot,供当前处理流程使用
emptySnapshot := make([]cookierefresh.BrowserCookie, 0)
// res、err 保存res、err,供当前处理流程使用
res, err := (Service{RetryDelay: -1}).RenewAPIFirst(context.Background(), "", emptySnapshot)
if err != nil || !res.Skipped || res.SkipReason != "long_login_expired" {
t.Fatalf("result=%+v err=%v", res, err)
@@ -476,8 +578,10 @@ func TestRenewAPIFirstTreatsNonNilEmptySnapshotAsAuthoritative(t *testing.T) {
}
}
// TestRenewAPIFirstCookie3UsesBackupFlags 负责TestRenewAPIFirstCookie3UsesBackupFlags相关处理。
func TestRenewAPIFirstCookie3UsesBackupFlags(t *testing.T) {
useTestDesktopFingerprint(t)
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("skipSessionFilter") != "true" || r.URL.Query().Get("c2r") != "true" || r.URL.Query().Get("ltl") != "" {
t.Fatalf("cookie3 query=%s", r.URL.RawQuery)
@@ -485,23 +589,31 @@ func TestRenewAPIFirstCookie3UsesBackupFlags(t *testing.T) {
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
}))
defer srv.Close()
// svc 保存svc,供当前处理流程使用
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
// res、err 保存res、err,供当前处理流程使用
res, err := svc.RenewAPIFirst(context.Background(), "cookie3_bak_exp="+futureMillis(time.Hour))
if err != nil || !res.Success || res.RequestCount != 1 {
t.Fatalf("result=%#v err=%v", res, err)
}
}
// TestRenewAPIFirstSkipsFatigueAndExpiredCookies 负责TestRenewAPIFirstSkipsFatigueAndExpiredCookies相关处理。
func TestRenewAPIFirstSkipsFatigueAndExpiredCookies(t *testing.T) {
// calls 保存calls,供当前处理流程使用
var calls atomic.Int32
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls.Add(1) }))
defer srv.Close()
// svc 保存svc,供当前处理流程使用
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
// input 表示当前遍历过程中的input
for _, input := range []string{
"sdkSilent=" + futureMillis(time.Hour) + "; havana_lgc_exp=" + futureMillis(2*time.Hour),
"havana_lgc_exp=1; cookie3_bak_exp=1",
} {
// res、err 保存res、err,供当前处理流程使用
res, err := svc.RenewAPIFirst(context.Background(), input)
if err != nil || !res.Skipped || res.Success || res.RequestCount != 0 {
t.Fatalf("input=%q result=%#v err=%v", input, res, err)
@@ -512,16 +624,21 @@ func TestRenewAPIFirstSkipsFatigueAndExpiredCookies(t *testing.T) {
}
}
// TestRenewAPIFirstDoesNotRetryOrEscalateFailure 负责TestRenewAPIFirstDoesNot重试OrEscalateFailure相关处理。
func TestRenewAPIFirstDoesNotRetryOrEscalateFailure(t *testing.T) {
useTestDesktopFingerprint(t)
// calls 保存calls,供当前处理流程使用
var calls atomic.Int32
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls.Add(1)
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"content":{"success":false}}`))
}))
defer srv.Close()
// svc 保存svc,供当前处理流程使用
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
// res、err 保存res、err,供当前处理流程使用
res, err := svc.RenewAPIFirst(context.Background(), "havana_lgc_exp="+futureMillis(time.Hour))
if err != nil {
t.Fatalf("RenewAPIFirst: %v", err)
@@ -531,17 +648,22 @@ func TestRenewAPIFirstDoesNotRetryOrEscalateFailure(t *testing.T) {
}
}
// TestMergeSetCookies 负责TestMergeSetCookies相关处理。
func TestMergeSetCookies(t *testing.T) {
// got 保存got,供当前处理流程使用
got := MergeSetCookies("unb=1; old=a", []string{"old=b; Path=/; HttpOnly", "new=c; Domain=.goofish.com; Path=/", "bad-cookie"})
if !strings.Contains(got, "old=b") || !strings.Contains(got, "new=c") || !strings.Contains(got, "unb=1") {
t.Fatalf("MergeSetCookies=%q", got)
}
if changed := strings.Join(ChangedCookieNames("unb=1; old=a", got), ","); changed != "new,old" {
if // changed 保存changed,供当前处理流程使用
changed := strings.Join(ChangedCookieNames("unb=1; old=a", got), ","); changed != "new,old" {
t.Fatalf("ChangedCookieNames=%s", changed)
}
}
// TestMergeSetCookiesAppliesServerDeletion 负责TestMergeSetCookiesAppliesServerDeletion相关处理。
func TestMergeSetCookiesAppliesServerDeletion(t *testing.T) {
// got 保存got,供当前处理流程使用
got := MergeSetCookies("unb=1; stale=a; expired=b", []string{
"stale=; Max-Age=0; Path=/",
"expired=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/",
@@ -549,12 +671,15 @@ func TestMergeSetCookiesAppliesServerDeletion(t *testing.T) {
if strings.Contains(got, "stale=") || strings.Contains(got, "expired=") {
t.Fatalf("deleted cookies survived: %q", got)
}
if changed := strings.Join(ChangedCookieNames("unb=1; stale=a; expired=b", got), ","); changed != "expired,stale" {
if // changed 保存changed,供当前处理流程使用
changed := strings.Join(ChangedCookieNames("unb=1; stale=a; expired=b", got), ","); changed != "expired,stale" {
t.Fatalf("ChangedCookieNames=%s", changed)
}
}
// TestMergeSetCookiesMaxAgeOverridesPastExpires 负责TestMergeSetCookiesMaxAgeOverridesPastExpires相关处理。
func TestMergeSetCookiesMaxAgeOverridesPastExpires(t *testing.T) {
// got 保存got,供当前处理流程使用
got := MergeSetCookies("session=old", []string{
"session=fresh; Max-Age=3600; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/",
})
@@ -563,6 +688,7 @@ func TestMergeSetCookiesMaxAgeOverridesPastExpires(t *testing.T) {
}
}
// TestRenewBusinessOKMatchesOfficialPlugin 负责TestRenewBusinessOKMatchesOfficialPlugin相关处理。
func TestRenewBusinessOKMatchesOfficialPlugin(t *testing.T) {
if renewBusinessOK([]byte(`{"content":{"success":true}}`)) {
t.Fatal("official plugin requires processFinished=true and resultCode=100")
@@ -572,9 +698,12 @@ func TestRenewBusinessOKMatchesOfficialPlugin(t *testing.T) {
}
}
// TestRenewAPIFirstReturnsAtPromiseTimeoutAndKeepsLateCookies 负责TestRenewAPIFirstReturnsAtPromiseTimeoutAndKeepsLateCookies相关处理。
func TestRenewAPIFirstReturnsAtPromiseTimeoutAndKeepsLateCookies(t *testing.T) {
useTestDesktopFingerprint(t)
// completed 保存completed,供当前处理流程使用
var completed atomic.Bool
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
time.Sleep(80 * time.Millisecond)
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: futureMillis(time.Hour), Path: "/"})
@@ -582,23 +711,29 @@ func TestRenewAPIFirstReturnsAtPromiseTimeoutAndKeepsLateCookies(t *testing.T) {
completed.Store(true)
}))
defer srv.Close()
// svc 保存svc,供当前处理流程使用
svc := Service{
HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1,
PromiseTimeout: 20 * time.Millisecond,
}
// started 保存started,供当前处理流程使用
started := time.Now()
// res、err 保存res、err,供当前处理流程使用
res, err := svc.RenewAPIFirst(context.Background(), "havana_lgc_exp="+futureMillis(time.Hour))
if err != nil || res == nil || !res.HasPending() {
t.Fatalf("result=%+v err=%v", res, err)
}
if elapsed := time.Since(started); elapsed >= 70*time.Millisecond {
if // elapsed 保存elapsed,供当前处理流程使用
elapsed := time.Since(started); elapsed >= 70*time.Millisecond {
t.Fatalf("外层 Promise 没有按时返回: %s", elapsed)
}
if completed.Load() || len(res.SetCookies) != 0 || res.Success || res.NeedPasswordLogin {
t.Fatalf("超时瞬间不应伪造底层结果或要求重新登录: %+v completed=%v", res, completed.Load())
}
// waitCtx、cancel 保存waitCtx、cancel,供当前处理流程使用
waitCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
// late、lateErr 保存late、lateErr,供当前处理流程使用
late, lateErr := res.AwaitPending(waitCtx)
if lateErr != nil || late == nil || len(late.SetCookies) != 1 || !strings.Contains(late.NewCookies, "sdkSilent=") {
t.Fatalf("迟到响应 Cookie 丢失: result=%+v err=%v", late, lateErr)
@@ -608,25 +743,33 @@ func TestRenewAPIFirstReturnsAtPromiseTimeoutAndKeepsLateCookies(t *testing.T) {
}
}
// TestRebaseResponseCookiesUsesLatestAuthoritativeJar 负责TestRebase响应CookiesUsesLatestAuthoritativeJar相关处理。
func TestRebaseResponseCookiesUsesLatestAuthoritativeJar(t *testing.T) {
// current 保存current,供当前处理流程使用
current := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "concurrent", Value: "kept", Domain: ".goofish.com", Path: "/", Secure: true},
}
// metadata 保存metadata,供当前处理流程使用
metadata := cookierefresh.MetadataWithSnapshot(`{"note":"keep"}`, current)
// late 保存late,供当前处理流程使用
late := &Result{
SetCookies: []string{"sdkSilent=9999999999999; Domain=goofish.com; Path=/; Secure; HttpOnly"},
responseCookieURL: SilentHasLoginURL,
}
// value、updatedMetadata、changed 保存value、updatedMetadata、changed,供当前处理流程使用
value, updatedMetadata, changed := RebaseResponseCookies("unb=1; concurrent=kept", metadata, late)
if !changed || !strings.Contains(value, "concurrent=kept") || !strings.Contains(value, "sdkSilent=9999999999999") {
t.Fatalf("迟到响应覆盖了并发 Cookie: value=%q changed=%v", value, changed)
}
// snapshot、complete 保存snapshot、complete,供当前处理流程使用
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(updatedMetadata)
if !complete {
t.Fatalf("权威快照被降级: %s", updatedMetadata)
}
// found 保存found,供当前处理流程使用
var found bool
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range snapshot {
if cookie.Name == "sdkSilent" && cookie.HTTPOnly && cookie.Domain == ".goofish.com" {
found = true
@@ -637,7 +780,9 @@ func TestRebaseResponseCookiesUsesLatestAuthoritativeJar(t *testing.T) {
}
}
// TestRenewBodyLimit 负责TestRenew请求体上限相关处理。
func TestRenewBodyLimit(t *testing.T) {
// err 保存err,供当前处理流程使用
_, err := readRenewBody(strings.NewReader(strings.Repeat("x", maxRenewBodyBytes+1)))
if err == nil || !strings.Contains(err.Error(), fmt.Sprint(maxRenewBodyBytes>>20)) {
t.Fatalf("err=%v", err)
+6
View File
@@ -8,6 +8,7 @@ import (
// BrowserFingerprint is populated from Playwright's bundled Chromium at
// runtime. It is the sole source for browser-identifying HTTP headers.
// BrowserFingerprint 保存浏览器Fingerprint,供当前处理流程使用
type BrowserFingerprint struct {
UserAgent string
SecChUA string
@@ -15,11 +16,13 @@ type BrowserFingerprint struct {
Mobile string
}
// browserFingerprint 保存浏览器Fingerprint,供当前处理流程使用
var browserFingerprint struct {
sync.RWMutex
value BrowserFingerprint
}
// SetBrowserFingerprint 设置浏览器Fingerprint。
func SetBrowserFingerprint(value BrowserFingerprint) {
value.UserAgent = strings.TrimSpace(value.UserAgent)
value.SecChUA = strings.TrimSpace(value.SecChUA)
@@ -30,6 +33,7 @@ func SetBrowserFingerprint(value BrowserFingerprint) {
browserFingerprint.Unlock()
}
// CurrentBrowserFingerprint 负责Current浏览器Fingerprint相关处理。
func CurrentBrowserFingerprint() BrowserFingerprint {
browserFingerprint.RLock()
defer browserFingerprint.RUnlock()
@@ -38,7 +42,9 @@ func CurrentBrowserFingerprint() BrowserFingerprint {
// ApplyBrowserFingerprint applies only headers observed from Chromium. Before
// browser initialization it intentionally adds no synthetic browser identity.
// ApplyBrowserFingerprint 负责Apply浏览器Fingerprint相关处理。
func ApplyBrowserFingerprint(h http.Header) {
// fp 保存fp,供当前处理流程使用
fp := CurrentBrowserFingerprint()
if fp.UserAgent != "" {
h.Set("user-agent", fp.UserAgent)
+2
View File
@@ -5,6 +5,7 @@ import (
"testing"
)
// TestApplyBrowserFingerprintUsesRuntimeValues 负责TestApply浏览器FingerprintUsesRuntimeValues相关处理。
func TestApplyBrowserFingerprintUsesRuntimeValues(t *testing.T) {
SetBrowserFingerprint(BrowserFingerprint{
UserAgent: "runtime-chromium-ua",
@@ -12,6 +13,7 @@ func TestApplyBrowserFingerprintUsesRuntimeValues(t *testing.T) {
Platform: "macOS",
Mobile: "?0",
})
// h 保存h,供当前处理流程使用
h := http.Header{}
ApplyBrowserFingerprint(h)
if h.Get("User-Agent") != "runtime-chromium-ua" ||
+25 -2
View File
@@ -6,8 +6,10 @@ import (
"strings"
)
// RegErrorKind 保存Reg错误类型,供当前处理流程使用
type RegErrorKind string
// RegErrorInvalidToken 保存Reg错误Invalid令牌,供当前处理流程使用
const (
RegErrorInvalidToken RegErrorKind = "invalid_token"
RegErrorConnectLimit RegErrorKind = "connect_limit"
@@ -16,12 +18,14 @@ const (
// RegError describes a server-side /reg rejection after the WebSocket itself
// has opened successfully.
// RegError 保存Reg错误,供当前处理流程使用
type RegError struct {
Kind RegErrorKind
Code int
Reason string
}
// Error 负责错误相关处理。
func (e *RegError) Error() string {
if e == nil {
return ""
@@ -29,24 +33,34 @@ func (e *RegError) Error() string {
return fmt.Sprintf("WS /reg 被拒绝: kind=%s code=%d reason=%s", e.Kind, e.Code, e.Reason)
}
// IsInvalidTokenError 负责IsInvalid令牌错误相关处理。
func IsInvalidTokenError(err error) bool {
// regErr 保存regErr,供当前处理流程使用
var regErr *RegError
return errors.As(err, &regErr) && regErr.Kind == RegErrorInvalidToken
}
// IsConnectLimitError 负责IsConnect上限错误相关处理。
func IsConnectLimitError(err error) bool {
// regErr 保存regErr,供当前处理流程使用
var regErr *RegError
return errors.As(err, &regErr) && regErr.Kind == RegErrorConnectLimit
}
// IsAuthenticationError 负责IsAuthentication错误相关处理。
func IsAuthenticationError(err error) bool {
// regErr 保存regErr,供当前处理流程使用
var regErr *RegError
return errors.As(err, &regErr) && regErr.Kind == RegErrorAuthentication
}
// newRegError 负责newReg错误相关处理。
func newRegError(code int, frame map[string]any) error {
// reason 保存原因,供当前处理流程使用
reason := regErrorReason(frame)
// lower 保存lower,供当前处理流程使用
lower := strings.ToLower(reason)
// kind 保存类型,供当前处理流程使用
kind := RegErrorAuthentication
switch {
case code == 401,
@@ -63,26 +77,35 @@ func newRegError(code int, frame map[string]any) error {
return &RegError{Kind: kind, Code: code, Reason: reason}
}
// regErrorReason 负责reg错误原因相关处理。
func regErrorReason(frame map[string]any) string {
// values 保存values,供当前处理流程使用
values := make([]string, 0, 8)
// appendValue 保存append值,供当前处理流程使用
appendValue := func(value any) {
if value == nil {
return
}
// text 保存文本,供当前处理流程使用
text := strings.TrimSpace(fmt.Sprint(value))
if text != "" && text != "<nil>" {
values = append(values, text)
}
}
// key 表示当前遍历过程中的key
for _, key := range []string{"message", "msg", "reason", "ret"} {
appendValue(frame[key])
}
if body, ok := frame["body"].(map[string]any); ok {
if // body、ok 保存body、ok,供当前处理流程使用
body, ok := frame["body"].(map[string]any); ok {
// key 表示当前遍历过程中的key
for _, key := range []string{"message", "msg", "reason", "moreInfo"} {
appendValue(body[key])
}
}
if headers, ok := frame["headers"].(map[string]any); ok {
if // headers、ok 保存headers、ok,供当前处理流程使用
headers, ok := frame["headers"].(map[string]any); ok {
// key 表示当前遍历过程中的key
for _, key := range []string{"message", "msg", "reason", "error", "error-message"} {
appendValue(headers[key])
}
+178 -34
View File
@@ -25,11 +25,13 @@ import (
// WSURL 闲鱼 IM WebSocket 地址。
const WSURL = "wss://wss-goofish.dingtalk.com:443"
// wsOpenTimeout 保存wsOpenTimeout,供当前处理流程使用
const (
wsOpenTimeout = 30 * time.Second
regResponseTimeout = 30 * time.Second
)
// heartbeatResponseTimeout 保存heartbeat响应Timeout,供当前处理流程使用
var (
heartbeatResponseTimeout = 30 * time.Second
batchConnectDelays = []time.Duration{0, 200 * time.Millisecond, 900 * time.Millisecond, 1500 * time.Millisecond, 4 * time.Second}
@@ -67,6 +69,7 @@ type Conn struct {
pushes chan incomingFrame
}
// incomingFrame 保存incomingFrame,供当前处理流程使用
type incomingFrame struct {
messageType websocket.MessageType
data []byte
@@ -80,8 +83,10 @@ func (c *Conn) SetRecorder(rec func(direction, rawText, parsedJSON, parseStatus,
c.recorderMu.Unlock()
}
// recorderSnapshot 负责recorderSnapshot相关处理。
func (c *Conn) recorderSnapshot() func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
c.recorderMu.RLock()
// recorder 保存recorder,供当前处理流程使用
recorder := c.recorder
c.recorderMu.RUnlock()
return recorder
@@ -89,12 +94,15 @@ func (c *Conn) recorderSnapshot() func(direction, rawText, parsedJSON, parseStat
// Dial 保留旧的一步式入口;新账号主循环使用 Open → 获取 token → Register,
// 从而与官网 authConnect 的顺序一致。
// Dial 负责Dial相关处理。
func Dial(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) {
// conn、err 保存conn、err,供当前处理流程使用
conn, err := Open(ctx, cfg, logger)
if err != nil {
return nil, err
}
if err := conn.Register(ctx, cfg.DeviceID, cfg.AccessToken); err != nil {
if // err 保存err,供当前处理流程使用
err := conn.Register(ctx, cfg.DeviceID, cfg.AccessToken); err != nil {
_ = conn.Close()
return nil, err
}
@@ -104,6 +112,7 @@ func Dial(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) {
// Open 按官网 batchConnectWs 策略并行打开最多五条原生 WebSocket,由最先
// settle 的成功或失败决定本轮结果,并关闭迟到连接。此阶段不请求 token,
// 也不发送 /reg。
// Open 打开当前值。
func Open(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) {
if logger == nil {
logger = slog.Default()
@@ -112,15 +121,19 @@ func Open(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) {
return openBatch(ctx, WSURL, cfg, logger)
}
// websocketHeaders 负责websocketHeaders相关处理。
func websocketHeaders() http.Header {
// hdr 保存hdr,供当前处理流程使用
hdr := http.Header{}
hdr.Set("Origin", "https://www.goofish.com")
if ua := xianyu.CurrentBrowserFingerprint().UserAgent; ua != "" {
if // ua 保存ua,供当前处理流程使用
ua := xianyu.CurrentBrowserFingerprint().UserAgent; ua != "" {
hdr.Set("User-Agent", ua)
}
return hdr
}
// chromeVersionPattern 保存chromeVersionPattern,供当前处理流程使用
var (
chromeVersionPattern = regexp.MustCompile(`(?:Chrome|CriOS)/([\d.]+)`)
headlessChromePattern = regexp.MustCompile(`HeadlessChrome/([\d.]+)`)
@@ -135,12 +148,15 @@ var (
// OfficialRegistrationUA mirrors IMPaaS 2.2.0's ua-parser-js composition.
// The raw UA (and therefore its browser version) comes from local Chromium;
// all wrapper fields and ordering are fixed to the official web implementation.
// OfficialRegistrationUA 负责OfficialRegistrationUA相关处理。
func OfficialRegistrationUA(rawUA string) string {
rawUA = strings.TrimSpace(rawUA)
if rawUA == "" {
return ""
}
// osName、osVersion 保存osName、osVersion,供当前处理流程使用
osName, osVersion := parseOfficialOS(rawUA)
// browserName、browserVersion 保存浏览器Name、browserVersion,供当前处理流程使用
browserName, browserVersion := parseOfficialBrowser(rawUA)
return strings.Join([]string{
rawUA,
@@ -153,18 +169,24 @@ func OfficialRegistrationUA(rawUA string) string {
}, " ")
}
// parseOfficialOS 负责parseOfficialOS相关处理。
func parseOfficialOS(ua string) (string, string) {
if match := macVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
if // match 保存match,供当前处理流程使用
match := macVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
return "Mac OS", strings.ReplaceAll(match[1], "_", ".")
}
if match := windowsVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
if // match 保存match,供当前处理流程使用
match := windowsVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
// versions 保存versions,供当前处理流程使用
versions := map[string]string{"10.0": "10", "6.3": "8.1", "6.2": "8", "6.1": "7", "6.0": "Vista", "5.1": "XP"}
if version := versions[match[1]]; version != "" {
if // version 保存version,供当前处理流程使用
version := versions[match[1]]; version != "" {
return "Windows", version
}
return "Windows", match[1]
}
if match := androidVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
if // match 保存match,供当前处理流程使用
match := androidVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
return "Android", match[1]
}
if strings.Contains(ua, "Linux") {
@@ -173,34 +195,45 @@ func parseOfficialOS(ua string) (string, string) {
return "other", "other"
}
// parseOfficialBrowser 负责parseOfficial浏览器相关处理。
func parseOfficialBrowser(ua string) (string, string) {
// candidate 表示当前遍历过程中的candidate
for _, candidate := range []struct {
name string
pattern *regexp.Regexp
}{{"Edge", edgeVersionPattern}, {"Chrome Headless", headlessChromePattern}, {"Chrome", chromeVersionPattern}, {"Firefox", firefoxVersionPattern}, {"Safari", safariVersionPattern}} {
if match := candidate.pattern.FindStringSubmatch(ua); len(match) == 2 {
if // match 保存match,供当前处理流程使用
match := candidate.pattern.FindStringSubmatch(ua); len(match) == 2 {
return candidate.name, match[1]
}
}
return "other", "other"
}
// dialResult 保存dial结果,供当前处理流程使用
type dialResult struct {
conn *websocket.Conn
err error
}
// openBatch 负责open批次相关处理。
func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logger) (*Conn, error) {
// delays 保存delays,供当前处理流程使用
delays := append([]time.Duration(nil), batchConnectDelays...)
if len(delays) == 0 {
return nil, fmt.Errorf("WS dial: batchConnect 未配置竞速连接")
}
// batchCtx、cancel 保存批次Ctx、cancel,供当前处理流程使用
batchCtx, cancel := context.WithCancel(ctx)
// results 保存results,供当前处理流程使用
results := make(chan dialResult, len(delays))
// delay 表示当前遍历过程中的延迟
for _, delay := range delays {
// delay 保存延迟,供当前处理流程使用
delay := delay
go func() {
if delay > 0 {
// timer 保存定时器,供当前处理流程使用
timer := time.NewTimer(delay)
defer timer.Stop()
select {
@@ -210,8 +243,10 @@ func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logg
case <-timer.C:
}
}
// dialCtx、dialCancel 保存dialCtx、dial取消,供当前处理流程使用
dialCtx, dialCancel := context.WithTimeout(batchCtx, wsOpenTimeout)
defer dialCancel()
// conn、err 保存conn、err,供当前处理流程使用
conn, _, err := websocket.Dial(dialCtx, target, &websocket.DialOptions{HTTPHeader: websocketHeaders()})
results <- dialResult{conn: conn, err: err}
}()
@@ -219,10 +254,13 @@ func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logg
// 官网使用 Promise.race:第一条完成的连接无论成功或失败都会决定本轮
// batchConnect 的结果;不会在先收到失败后继续等待其他竞速连接。
// result 保存结果,供当前处理流程使用
result := <-results
go func() {
defer cancel()
for i := 1; i < len(delays); i++ {
for // i 保存i,供当前处理流程使用
i := 1; i < len(delays); i++ {
// late 保存late,供当前处理流程使用
late := <-results
if late.conn != nil {
_ = late.conn.CloseNow()
@@ -241,10 +279,12 @@ func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logg
return newConn(result.conn, cfg, logger), nil
}
// newConn 负责newConn相关处理。
func newConn(raw *websocket.Conn, cfg Config, logger *slog.Logger) *Conn {
if logger == nil {
logger = slog.Default()
}
// c 保存c,供当前处理流程使用
c := &Conn{
ws: raw,
cfg: cfg,
@@ -256,6 +296,7 @@ func newConn(raw *websocket.Conn, cfg Config, logger *slog.Logger) *Conn {
return c
}
// ensureReadPump 负责ensureReadPump相关处理。
func (c *Conn) ensureReadPump() {
c.initOnce.Do(func() {
if c.logger == nil {
@@ -276,6 +317,7 @@ func (c *Conn) Register(ctx context.Context, deviceID, accessToken string) error
// 官网 authConnect 在 _auth 前对 MTOP accessToken 执行
// decodeURIComponent。保留原始值供重试,再把解码值写入 /reg。
c.cfg.AccessToken = accessToken
// decodedAccessToken、err 保存decodedAccessToken、err,供当前处理流程使用
decodedAccessToken, err := url.PathUnescape(accessToken)
if err != nil {
return fmt.Errorf("解码 WebSocket accessToken 失败: %w", err)
@@ -283,6 +325,7 @@ func (c *Conn) Register(ctx context.Context, deviceID, accessToken string) error
if !utf8.ValidString(decodedAccessToken) {
return fmt.Errorf("解码 WebSocket accessToken 失败: 非法 UTF-8")
}
// response、err 保存response、err,供当前处理流程使用
response, err := c.request(ctx, "/reg", map[string]any{
"cache-header": "app-key token ua wv",
"app-key": RegAppKey,
@@ -296,6 +339,7 @@ func (c *Conn) Register(ctx context.Context, deviceID, accessToken string) error
if err != nil {
return fmt.Errorf("等待 /reg 响应失败: %w", err)
}
// code、ok 保存code、ok,供当前处理流程使用
code, ok := responseCode(response["code"])
if ok && code == 200 {
c.logger.Info("WS 注册完成")
@@ -309,7 +353,9 @@ func (c *Conn) register(ctx context.Context) error {
return c.Register(ctx, c.cfg.DeviceID, c.cfg.AccessToken)
}
// midKey 负责midKey相关处理。
func midKey(mid string) string {
// fields 保存字段列表,供当前处理流程使用
fields := strings.Fields(mid)
if len(fields) == 0 {
return ""
@@ -317,27 +363,35 @@ func midKey(mid string) string {
return fields[0]
}
// responseCode 负责响应Code相关处理。
func responseCode(value any) (int, bool) {
switch code := value.(type) {
switch // code 保存code,供当前处理流程使用
code := value.(type) {
case float64:
return int(code), true
case int:
return code, true
case json.Number:
// parsed、err 保存parsed、err,供当前处理流程使用
parsed, err := code.Int64()
return int(parsed), err == nil
case string:
// parsed 保存解析结果,供当前处理流程使用
var parsed int
if _, err := fmt.Sscanf(strings.TrimSpace(code), "%d", &parsed); err == nil {
if // err 保存err,供当前处理流程使用
_, err := fmt.Sscanf(strings.TrimSpace(code), "%d", &parsed); err == nil {
return parsed, true
}
}
return 0, false
}
// request 负责请求相关处理。
func (c *Conn) request(ctx context.Context, path string, headers map[string]any, body any, timeout time.Duration) (map[string]any, error) {
c.ensureReadPump()
// requestCtx 保存请求Ctx,供当前处理流程使用
requestCtx := ctx
// cancel 保存取消,供当前处理流程使用
cancel := func() {}
if timeout > 0 {
requestCtx, cancel = context.WithTimeout(ctx, timeout)
@@ -347,14 +401,18 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
if headers == nil {
headers = make(map[string]any)
}
// mid 保存mid,供当前处理流程使用
mid := strings.TrimSpace(fmt.Sprint(headers["mid"]))
if mid == "" || mid == "<nil>" {
mid = protocol.GenerateMid()
headers["mid"] = mid
}
// key 保存key,供当前处理流程使用
key := midKey(mid)
// started 保存started,供当前处理流程使用
started := time.Now()
c.logger.Debug("WS 请求发送", "path", path, "mid", key)
// responseCh 保存响应Ch,供当前处理流程使用
responseCh := make(chan map[string]any, 1)
c.pendingMu.Lock()
c.pending[key] = responseCh
@@ -365,16 +423,20 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
c.pendingMu.Unlock()
}()
// frame 保存frame,供当前处理流程使用
frame := map[string]any{"lwp": path, "headers": headers}
if body != nil {
frame["body"] = body
}
if err := c.sendJSON(requestCtx, frame); err != nil {
if // err 保存err,供当前处理流程使用
err := c.sendJSON(requestCtx, frame); err != nil {
c.logger.Warn("WS 请求发送失败", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
return nil, err
}
select {
case response := <-responseCh:
case // response 保存响应,供当前处理流程使用
response := <-responseCh:
// code 保存code,供当前处理流程使用
code, _ := responseCode(response["code"])
c.logResponse(path, key, code, time.Since(started))
return response, nil
@@ -383,16 +445,20 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
// following close. Prefer that already-resolved response over readDone,
// matching browser event ordering (message before close).
select {
case response := <-responseCh:
case // response 保存响应,供当前处理流程使用
response := <-responseCh:
// code 保存code,供当前处理流程使用
code, _ := responseCode(response["code"])
c.logResponse(path, key, code, time.Since(started))
return response, nil
default:
}
// err 保存err,供当前处理流程使用
err := c.connectionReadError()
c.logger.Warn("WS 请求因连接结束失败", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
return nil, err
case <-requestCtx.Done():
// err 保存err,供当前处理流程使用
err := requestCtx.Err()
if errors.Is(err, context.Canceled) {
c.logger.Debug("WS 请求取消", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
@@ -405,6 +471,7 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
// ListUserMessages retrieves one page of official IM history for a conversation.
// The cursor is opaque to callers; zero selects the newest page.
// ListUserMessages 读取用户消息列表。
func (c *Conn) ListUserMessages(ctx context.Context, cid string, cursor int64, limit int) (map[string]any, error) {
cid = strings.TrimSpace(cid)
if cid == "" {
@@ -419,25 +486,30 @@ func (c *Conn) ListUserMessages(ctx context.Context, cid string, cursor int64, l
if limit <= 0 || limit > 100 {
limit = 50
}
// response、err 保存response、err,供当前处理流程使用
response, err := c.request(ctx, "/r/MessageManager/listUserMessages", nil,
[]any{cid, false, cursor, limit, false}, regResponseTimeout)
if err != nil {
return nil, err
}
if code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
if // code、ok 保存code、ok,供当前处理流程使用
code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
return nil, fmt.Errorf("聊天历史接口返回状态 %d", code)
}
// body、ok 保存body、ok,供当前处理流程使用
body, ok := response["body"].(map[string]any)
if !ok {
return nil, errors.New("聊天历史接口响应缺少 body")
}
if reason := strings.TrimSpace(fmt.Sprint(body["reason"])); reason != "" && reason != "<nil>" {
if // reason 保存原因,供当前处理流程使用
reason := strings.TrimSpace(fmt.Sprint(body["reason"])); reason != "" && reason != "<nil>" {
return nil, fmt.Errorf("聊天历史接口失败: %s", reason)
}
return body, nil
}
// ListConversations retrieves one page of the account's official IM contacts.
// ListConversations 读取Conversations。
func (c *Conn) ListConversations(ctx context.Context, cursor int64, limit int) (map[string]any, error) {
if cursor <= 0 {
cursor = 9007199254740991
@@ -445,24 +517,30 @@ func (c *Conn) ListConversations(ctx context.Context, cursor int64, limit int) (
if limit <= 0 || limit > 100 {
limit = 100
}
// response、err 保存response、err,供当前处理流程使用
response, err := c.request(ctx, "/r/Conversation/listNewestPagination", nil, []any{cursor, limit}, regResponseTimeout)
if err != nil {
return nil, err
}
if code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
if // code、ok 保存code、ok,供当前处理流程使用
code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
return nil, fmt.Errorf("会话列表接口返回状态 %d", code)
}
// body、ok 保存body、ok,供当前处理流程使用
body, ok := response["body"].(map[string]any)
if !ok {
return nil, errors.New("会话列表接口响应缺少 body")
}
if reason := strings.TrimSpace(fmt.Sprint(body["reason"])); reason != "" && reason != "<nil>" {
if // reason 保存原因,供当前处理流程使用
reason := strings.TrimSpace(fmt.Sprint(body["reason"])); reason != "" && reason != "<nil>" {
return nil, fmt.Errorf("会话列表接口失败: %s", reason)
}
return body, nil
}
// logResponse 负责log响应相关处理。
func (c *Conn) logResponse(path, mid string, code int, duration time.Duration) {
// attrs 保存attrs,供当前处理流程使用
attrs := []any{"path", path, "mid", mid, "code", code, "duration", duration.Round(time.Millisecond)}
if code >= 400 {
c.logger.Warn("WS 业务响应异常", attrs...)
@@ -471,9 +549,11 @@ func (c *Conn) logResponse(path, mid string, code int, duration time.Duration) {
c.logger.Debug("WS 响应收到", attrs...)
}
// readPump 负责readPump相关处理。
func (c *Conn) readPump() {
defer close(c.readDone)
for {
// messageType、data、err 保存消息Type、data、err,供当前处理流程使用
messageType, data, err := c.ws.Read(c.readCtx)
if err != nil {
c.readErrMu.Lock()
@@ -481,28 +561,37 @@ func (c *Conn) readPump() {
c.readErrMu.Unlock()
return
}
// parsed 保存解析结果,供当前处理流程使用
var parsed map[string]any
if err := json.Unmarshal(data, &parsed); err != nil {
if recorder := c.recorderSnapshot(); recorder != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal(data, &parsed); err != nil {
if // recorder 保存recorder,供当前处理流程使用
recorder := c.recorderSnapshot(); recorder != nil {
recorder("in", string(data), "", "non_json", err.Error())
}
continue
}
c.recordParsedIncoming(data, parsed)
if _, hasCode := parsed["code"]; hasCode {
if _, hasHeaders := parsed["headers"].(map[string]any); hasHeaders {
if // hasCode 保存hasCode,供当前处理流程使用
_, hasCode := parsed["code"]; hasCode {
if // hasHeaders 保存hasHeaders,供当前处理流程使用
_, hasHeaders := parsed["headers"].(map[string]any); hasHeaders {
c.dispatchResponse(parsed)
continue
}
}
// lwp、hasLWP 保存lwp、hasLWP,供当前处理流程使用
lwp, hasLWP := parsed["lwp"].(string)
// hasHeaders 保存hasHeaders,供当前处理流程使用
_, hasHeaders := parsed["headers"].(map[string]any)
if !hasLWP || strings.TrimSpace(lwp) == "" || !hasHeaders {
if recorder := c.recorderSnapshot(); recorder != nil {
if // recorder 保存recorder,供当前处理流程使用
recorder := c.recorderSnapshot(); recorder != nil {
recorder("in", string(data), string(data), "skip_invalid_lwp", "")
}
continue
}
// incoming 保存incoming,供当前处理流程使用
incoming := incomingFrame{messageType: messageType, data: append([]byte(nil), data...), parsed: parsed}
select {
case c.pushes <- incoming:
@@ -512,10 +601,14 @@ func (c *Conn) readPump() {
}
}
// dispatchResponse 负责dispatch响应相关处理。
func (c *Conn) dispatchResponse(frame map[string]any) bool {
// headers 保存headers,供当前处理流程使用
headers, _ := frame["headers"].(map[string]any)
// key 保存key,供当前处理流程使用
key := midKey(strings.TrimSpace(fmt.Sprint(headers["mid"])))
c.pendingMu.Lock()
// ch 保存ch,供当前处理流程使用
ch := c.pending[key]
c.pendingMu.Unlock()
if ch == nil {
@@ -528,6 +621,7 @@ func (c *Conn) dispatchResponse(frame map[string]any) bool {
return true
}
// connectionReadError 负责connectionRead错误相关处理。
func (c *Conn) connectionReadError() error {
c.readErrMu.Lock()
defer c.readErrMu.Unlock()
@@ -537,13 +631,17 @@ func (c *Conn) connectionReadError() error {
return fmt.Errorf("WebSocket 读取循环已结束")
}
// recordParsedIncoming 负责record解析结果Incoming相关处理。
func (c *Conn) recordParsedIncoming(data []byte, parsed map[string]any) {
// recorder 保存recorder,供当前处理流程使用
recorder := c.recorderSnapshot()
if recorder == nil {
return
}
// parsedJSON 保存解析结果JSON,供当前处理流程使用
parsedJSON := string(data)
if normalized, err := json.Marshal(parsed); err == nil {
if // normalized、err 保存normalized、err,供当前处理流程使用
normalized, err := json.Marshal(parsed); err == nil {
parsedJSON = string(normalized)
}
recorder("in", string(data), parsedJSON, "json", "")
@@ -552,12 +650,16 @@ func (c *Conn) recordParsedIncoming(data []byte, parsed map[string]any) {
// HeartbeatLoop 对齐官网:注册后以固定 15 秒节拍发送 /!,即使上一请求仍在
// 等待也不推迟下一次;任一请求失败或 30 秒无响应即结束连接。官网只以
// Promise 是否 reject 判断心跳,不因已收到的非 200 响应主动断线。
// HeartbeatLoop 负责HeartbeatLoop相关处理。
func (c *Conn) HeartbeatLoop(ctx context.Context, interval time.Duration) error {
c.ensureReadPump()
// heartbeatCtx、cancel 保存heartbeatCtx、cancel,供当前处理流程使用
heartbeatCtx, cancel := context.WithCancel(ctx)
defer cancel()
// ticker 保存ticker,供当前处理流程使用
ticker := time.NewTicker(interval)
defer ticker.Stop()
// heartbeatErr 保存heartbeatErr,供当前处理流程使用
heartbeatErr := make(chan error, 1)
for {
select {
@@ -565,11 +667,13 @@ func (c *Conn) HeartbeatLoop(ctx context.Context, interval time.Duration) error
return heartbeatCtx.Err()
case <-c.readDone:
return c.connectionReadError()
case err := <-heartbeatErr:
case // err 保存err,供当前处理流程使用
err := <-heartbeatErr:
_ = c.Close()
return fmt.Errorf("心跳响应失败: %w", err)
case <-ticker.C:
go func() {
// err 保存err,供当前处理流程使用
_, err := c.request(heartbeatCtx, "/!", map[string]any{}, nil, heartbeatResponseTimeout)
if err == nil || heartbeatCtx.Err() != nil {
return
@@ -585,9 +689,11 @@ func (c *Conn) HeartbeatLoop(ctx context.Context, interval time.Duration) error
// ReceiveLoop 消费 readPump 分发的 Push。响应帧永远不会进入这里,因此不会被
// 错误 ACK;Push ACK 原样复用服务端完整 headers。
// ReceiveLoop 负责ReceiveLoop相关处理。
func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[string]any)) error {
c.ensureReadPump()
for {
// frame 保存frame,供当前处理流程使用
var frame incomingFrame
select {
case <-ctx.Done():
@@ -603,7 +709,9 @@ func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[str
}
case frame = <-c.pushes:
}
// raw 保存原始,供当前处理流程使用
raw := frame.parsed
// rawText 保存原始文本,供当前处理流程使用
rawText := string(frame.data)
switch strings.TrimSpace(fmt.Sprint(raw["lwp"])) {
case "/push/kickout":
@@ -618,7 +726,8 @@ func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[str
// 官网异步启动 sync state 恢复,并立即完成当前 Push handler;不能
// 为 getState/ackDiff 最多阻塞 Push ACK 60 秒。
go func(message map[string]any) {
if err := c.handleSyncExtra(c.readCtx, message); err != nil && c.readCtx.Err() == nil {
if // err 保存err,供当前处理流程使用
err := c.handleSyncExtra(c.readCtx, message); err != nil && c.readCtx.Err() == nil {
c.logger.Error("同步状态恢复失败", "err", err)
}
}(raw)
@@ -627,22 +736,27 @@ func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[str
syncData, ok := extractSyncPayload(raw)
if !ok {
c.sendACK(ctx, raw)
if recorder := c.recorderSnapshot(); recorder != nil {
if // recorder 保存recorder,供当前处理流程使用
recorder := c.recorderSnapshot(); recorder != nil {
recorder("in", rawText, "", "skip_non_sync", "")
}
continue
}
// decoded、err 保存decoded、err,供当前处理流程使用
decoded, err := decodeSyncData(syncData)
if err != nil {
c.sendACK(ctx, raw)
if recorder := c.recorderSnapshot(); recorder != nil {
if // recorder 保存recorder,供当前处理流程使用
recorder := c.recorderSnapshot(); recorder != nil {
recorder("in", rawText, "", "decrypt_failed", err.Error())
}
c.logger.Error("消息解密失败", "err", err)
continue
}
if recorder := c.recorderSnapshot(); recorder != nil {
if b, e := json.Marshal(decoded); e == nil {
if // recorder 保存recorder,供当前处理流程使用
recorder := c.recorderSnapshot(); recorder != nil {
if // b、e 保存b、e,供当前处理流程使用
b, e := json.Marshal(decoded); e == nil {
recorder("in", rawText, string(b), "decrypted", "")
}
}
@@ -653,25 +767,33 @@ func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[str
}
}
// handleSyncExtra 负责handleSyncExtra相关处理。
func (c *Conn) handleSyncExtra(ctx context.Context, msg map[string]any) error {
// body 保存请求体,供当前处理流程使用
body, _ := msg["body"].(map[string]any)
// extra 保存extra,供当前处理流程使用
extra, _ := body["syncExtraType"].(map[string]any)
// typeCode、ok 保存类型Code、ok,供当前处理流程使用
typeCode, ok := responseCode(extra["type"])
if !ok || (typeCode != 1 && typeCode != 2) {
return nil
}
// state、err 保存state、err,供当前处理流程使用
state, err := c.request(ctx, "/r/SyncStatus/getState", map[string]any{}, []any{map[string]any{"topic": "sync"}}, regResponseTimeout)
if err != nil {
return fmt.Errorf("getState: %w", err)
}
if code, ok := responseCode(state["code"]); !ok || code != http.StatusOK || state["body"] == nil {
if // code、ok 保存code、ok,供当前处理流程使用
code, ok := responseCode(state["code"]); !ok || code != http.StatusOK || state["body"] == nil {
return fmt.Errorf("getState 返回异常: code=%v", state["code"])
}
// response、err 保存response、err,供当前处理流程使用
response, err := c.request(ctx, "/r/SyncStatus/ackDiff", map[string]any{}, []any{state["body"]}, regResponseTimeout)
if err != nil {
return fmt.Errorf("ackDiff: %w", err)
}
if code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
if // code、ok 保存code、ok,供当前处理流程使用
code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
return fmt.Errorf("ackDiff 返回异常: code=%d", code)
}
return nil
@@ -679,11 +801,15 @@ func (c *Conn) handleSyncExtra(ctx context.Context, msg map[string]any) error {
// sendACK 回复 {"code":200, headers:<服务端完整 headers>}。
func (c *Conn) sendACK(ctx context.Context, msg map[string]any) {
// headers 保存headers,供当前处理流程使用
headers, _ := msg["headers"].(map[string]any)
// ackHeaders 保存ackHeaders,供当前处理流程使用
ackHeaders := make(map[string]any, len(headers))
// key、value 表示当前遍历过程中的key、value
for key, value := range headers {
ackHeaders[key] = value
}
// ack 保存ack,供当前处理流程使用
ack := map[string]any{
"code": 200,
"headers": ackHeaders,
@@ -696,22 +822,27 @@ func (c *Conn) sendACK(ctx context.Context, msg map[string]any) {
// extractSyncPayload 取出 body.syncPushPackage.data[0].data(字符串)。
func extractSyncPayload(msg map[string]any) (string, bool) {
// body 保存请求体,供当前处理流程使用
body, _ := msg["body"].(map[string]any)
if body == nil {
return "", false
}
// pkg 保存pkg,供当前处理流程使用
pkg, _ := body["syncPushPackage"].(map[string]any)
if pkg == nil {
return "", false
}
// arr 保存arr,供当前处理流程使用
arr, _ := pkg["data"].([]any)
if len(arr) == 0 {
return "", false
}
// first 保存first,供当前处理流程使用
first, _ := arr[0].(map[string]any)
if first == nil {
return "", false
}
// d、ok 保存d、ok,供当前处理流程使用
d, ok := first["data"].(string)
return d, ok && d != ""
}
@@ -720,8 +851,10 @@ func extractSyncPayload(msg map[string]any) (string, bool) {
func decodeSyncData(data string) (map[string]any, error) {
// 1) base64 解码后尝试解析 JSON。
if dec, err := base64.StdEncoding.DecodeString(data); err == nil {
// parsed 保存解析结果,供当前处理流程使用
var parsed map[string]any
if jsonErr := json.Unmarshal(dec, &parsed); jsonErr == nil {
if // jsonErr 保存jsonErr,供当前处理流程使用
jsonErr := json.Unmarshal(dec, &parsed); jsonErr == nil {
return parsed, nil
}
}
@@ -730,8 +863,10 @@ func decodeSyncData(data string) (map[string]any, error) {
if err != nil {
return nil, err
}
// parsed 保存解析结果,供当前处理流程使用
var parsed map[string]any
if err := json.Unmarshal([]byte(out), &parsed); err != nil {
if // err 保存err,供当前处理流程使用
err := json.Unmarshal([]byte(out), &parsed); err != nil {
return nil, fmt.Errorf("解密后非 JSON: %w", err)
}
return parsed, nil
@@ -739,11 +874,13 @@ func decodeSyncData(data string) (map[string]any, error) {
// sendJSON 发送一条 JSON 文本帧。
func (c *Conn) sendJSON(ctx context.Context, v any) error {
// b、err 保存b、err,供当前处理流程使用
b, err := json.Marshal(v)
if err != nil {
return err
}
if recorder := c.recorderSnapshot(); recorder != nil {
if // recorder 保存recorder,供当前处理流程使用
recorder := c.recorderSnapshot(); recorder != nil {
recorder("out", string(b), string(b), "json", "")
}
select {
@@ -757,6 +894,7 @@ func (c *Conn) sendJSON(ctx context.Context, v any) error {
// SendText 发送一条闲鱼聊天文本消息。
func (c *Conn) SendText(ctx context.Context, myID, cid, toID, text string) error {
// content 保存内容,供当前处理流程使用
content := map[string]any{
"contentType": 1,
"text": map[string]any{
@@ -774,6 +912,7 @@ func (c *Conn) SendImage(ctx context.Context, myID, cid, toID, imageURL string,
if height <= 0 {
height = 600
}
// content 保存内容,供当前处理流程使用
content := map[string]any{
"contentType": 2,
"image": map[string]any{
@@ -788,6 +927,7 @@ func (c *Conn) SendImage(ctx context.Context, myID, cid, toID, imageURL string,
return c.sendChatContent(ctx, myID, cid, toID, content)
}
// sendChatContent 负责send聊天内容相关处理。
func (c *Conn) sendChatContent(ctx context.Context, myID, cid, toID string, content any) error {
myID = stripGoofish(myID)
cid = stripGoofish(cid)
@@ -795,11 +935,14 @@ func (c *Conn) sendChatContent(ctx context.Context, myID, cid, toID string, cont
if myID == "" || cid == "" || toID == "" {
return fmt.Errorf("发送消息缺少必要参数: myID=%q cid=%q toID=%q", myID, cid, toID)
}
// raw、err 保存raw、err,供当前处理流程使用
raw, err := json.Marshal(content)
if err != nil {
return err
}
// encoded 保存encoded,供当前处理流程使用
encoded := base64.StdEncoding.EncodeToString(raw)
// msg 保存msg,供当前处理流程使用
msg := map[string]any{
"lwp": "/r/MessageSend/sendByReceiverScope",
"headers": map[string]any{
@@ -839,6 +982,7 @@ func (c *Conn) sendChatContent(ctx context.Context, myID, cid, toID string, cont
return c.sendJSON(ctx, msg)
}
// stripGoofish 负责stripGoofish相关处理。
func stripGoofish(s string) string {
s = strings.TrimSpace(s)
return strings.TrimSuffix(s, "@goofish")
+27 -6
View File
@@ -7,8 +7,10 @@ import (
"xianyu-go/internal/xianyu"
)
// TestWebsocketHeadersMatchBrowserHandshake 负责TestWebsocketHeadersMatch浏览器Handshake相关处理。
func TestWebsocketHeadersMatchBrowserHandshake(t *testing.T) {
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "runtime-browser-ua"})
// got 保存got,供当前处理流程使用
got := websocketHeaders()
if got.Get("Origin") != "https://www.goofish.com" || got.Get("User-Agent") != "runtime-browser-ua" {
t.Fatalf("websocket headers = %#v", got)
@@ -18,49 +20,68 @@ func TestWebsocketHeadersMatchBrowserHandshake(t *testing.T) {
}
}
// TestOfficialRegistrationUAUsesRuntimeBrowserVersion 负责TestOfficialRegistrationUAUsesRuntime浏览器Version相关处理。
func TestOfficialRegistrationUAUsesRuntimeBrowserVersion(t *testing.T) {
// raw 保存原始,供当前处理流程使用
raw := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/138.0.7204.92 Safari/537.36"
// want 保存want,供当前处理流程使用
want := raw + " DingTalk(2.2.0) OS(Mac OS/10.15.7) Browser(Chrome/138.0.7204.92) DingWeb/2.2.0 IMPaaS DingWeb/2.2.0"
if got := OfficialRegistrationUA(raw); got != want {
if // got 保存got,供当前处理流程使用
got := OfficialRegistrationUA(raw); got != want {
t.Fatalf("OfficialRegistrationUA() = %q, want %q", got, want)
}
}
// TestOfficialRegistrationUARecognizesHeadlessChrome 负责TestOfficialRegistrationUARecognizesHeadlessChrome相关处理。
func TestOfficialRegistrationUARecognizesHeadlessChrome(t *testing.T) {
// raw 保存原始,供当前处理流程使用
raw := "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 HeadlessChrome/138.0.7204.92 Safari/537.36"
// want 保存want,供当前处理流程使用
want := raw + " DingTalk(2.2.0) OS(Linux/other) Browser(Chrome Headless/138.0.7204.92) DingWeb/2.2.0 IMPaaS DingWeb/2.2.0"
if got := OfficialRegistrationUA(raw); got != want {
if // got 保存got,供当前处理流程使用
got := OfficialRegistrationUA(raw); got != want {
t.Fatalf("OfficialRegistrationUA() = %q, want %q", got, want)
}
}
// TestExtractSyncPayload 负责TestExtractSync请求载荷相关处理。
func TestExtractSyncPayload(t *testing.T) {
// msg 保存msg,供当前处理流程使用
msg := map[string]any{"body": map[string]any{"syncPushPackage": map[string]any{
"data": []any{map[string]any{"data": "payload"}},
}}}
if got, ok := extractSyncPayload(msg); !ok || got != "payload" {
if // got、ok 保存got、ok,供当前处理流程使用
got, ok := extractSyncPayload(msg); !ok || got != "payload" {
t.Fatalf("extractSyncPayload() = %q, %v", got, ok)
}
// invalid 表示当前遍历过程中的invalid
for _, invalid := range []map[string]any{{}, {"body": map[string]any{}}, {"body": map[string]any{"syncPushPackage": map[string]any{"data": []any{}}}}} {
if _, ok := extractSyncPayload(invalid); ok {
if // ok 保存ok,供当前处理流程使用
_, ok := extractSyncPayload(invalid); ok {
t.Fatalf("invalid payload accepted: %#v", invalid)
}
}
}
// TestDecodeSyncDataJSONAndInvalid 负责TestDecodeSync数据JSONAndInvalid相关处理。
func TestDecodeSyncDataJSONAndInvalid(t *testing.T) {
// raw 保存原始,供当前处理流程使用
raw := base64.StdEncoding.EncodeToString([]byte(`{"event":"paid","count":2}`))
// got、err 保存got、err,供当前处理流程使用
got, err := decodeSyncData(raw)
if err != nil || got["event"] != "paid" || got["count"] != float64(2) {
t.Fatalf("decodeSyncData() = %#v, %v", got, err)
}
if _, err := decodeSyncData("not-base64"); err == nil {
if // err 保存err,供当前处理流程使用
_, err := decodeSyncData("not-base64"); err == nil {
t.Fatal("invalid payload should fail")
}
}
// TestWSHelpers 负责TestWSHelpers相关处理。
func TestWSHelpers(t *testing.T) {
if got := stripGoofish(" 123@goofish "); got != "123" {
if // got 保存got,供当前处理流程使用
got := stripGoofish(" 123@goofish "); got != "123" {
t.Fatalf("stripGoofish = %q", got)
}
}
File diff suppressed because it is too large. Load diff
+39 -3
View File
@@ -17,9 +17,12 @@ import (
// startWSEchoServer 启动一个本地 WS 服务:升级后发送一条同步推送消息,再读取并忽略 ACK,
// 最后关闭连接。返回服务 URL。用于驱动 ReceiveLoop 的消息分发测试。
// startWSEchoServer 负责开始WSEchoServer相关处理。
func startWSEchoServer(t *testing.T, payload string) *httptest.Server {
t.Helper()
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// c、err 保存c、err,供当前处理流程使用
c, err := websocket.Accept(w, r, nil)
if err != nil {
return
@@ -27,6 +30,7 @@ func startWSEchoServer(t *testing.T, payload string) *httptest.Server {
defer c.Close(websocket.StatusNormalClosure, "")
// 构造同步推送帧:body.syncPushPackage.data[0].data = base64(payload)。
b64 := base64.StdEncoding.EncodeToString([]byte(payload))
// frame 保存frame,供当前处理流程使用
frame := map[string]any{
"lwp": "/s/sync",
"headers": map[string]any{"mid": "m1", "sid": "s1"},
@@ -34,8 +38,10 @@ func startWSEchoServer(t *testing.T, payload string) *httptest.Server {
"data": []any{map[string]any{"data": b64}},
}},
}
// raw 保存原始,供当前处理流程使用
raw, _ := json.Marshal(frame)
if err := c.Write(r.Context(), websocket.MessageText, raw); err != nil {
if // err 保存err,供当前处理流程使用
err := c.Write(r.Context(), websocket.MessageText, raw); err != nil {
return
}
// 读掉 ACK 后关闭(触发客户端 Read 返回错误,结束 ReceiveLoop)。
@@ -54,12 +60,17 @@ func wsURL(srv *httptest.Server) string {
// TestReceiveLoop_DecodesSyncPayload 验证 ReceiveLoop 收到同步推送帧后:
// 解码 base64+JSON → 调用 onMessage → 回 ACK(服务端能读到)→ 连接关闭后退出。
// TestReceiveLoop_DecodesSyncPayload 负责TestReceiveLoopDecodesSync请求载荷相关处理。
func TestReceiveLoop_DecodesSyncPayload(t *testing.T) {
// payload 保存请求载荷,供当前处理流程使用
payload := `{"event":"paid","order_id":"o1"}`
// srv 保存srv,供当前处理流程使用
srv := startWSEchoServer(t, payload)
// dialCtx、dialCancel 保存dialCtx、dial取消,供当前处理流程使用
dialCtx, dialCancel := context.WithTimeout(context.Background(), 2*time.Second)
defer dialCancel()
// dialed、err 保存dialed、err,供当前处理流程使用
dialed, _, err := websocket.Dial(dialCtx, wsURL(srv), nil)
if err != nil {
t.Fatalf("dial: %v", err)
@@ -67,10 +78,14 @@ func TestReceiveLoop_DecodesSyncPayload(t *testing.T) {
defer dialed.CloseNow()
dialed.SetReadLimit(8 << 20)
// conn 保存conn,供当前处理流程使用
conn := newConn(dialed, Config{}, nilLogger())
// got 保存got,供当前处理流程使用
var got map[string]any
// loopDone 保存loopDone,供当前处理流程使用
loopDone := make(chan error, 1)
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
go func() {
@@ -91,7 +106,9 @@ func TestReceiveLoop_DecodesSyncPayload(t *testing.T) {
// TestReceiveLoop_NonJSONSkipped 非 JSON 消息应被跳过,不回调 onMessage,循环继续。
func TestReceiveLoop_NonJSONSkipped(t *testing.T) {
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// c、err 保存c、err,供当前处理流程使用
c, err := websocket.Accept(w, r, nil)
if err != nil {
return
@@ -99,22 +116,28 @@ func TestReceiveLoop_NonJSONSkipped(t *testing.T) {
defer c.Close(websocket.StatusNormalClosure, "")
// 先发一条非 JSON,再发一条合法同步推送。
c.Write(r.Context(), websocket.MessageText, []byte("not-json"))
// b64 保存b64,供当前处理流程使用
b64 := base64.StdEncoding.EncodeToString([]byte(`{"ok":true}`))
// frame 保存frame,供当前处理流程使用
frame := map[string]any{
"lwp": "/s/sync",
"headers": map[string]any{"mid": "m2"},
"body": map[string]any{"syncPushPackage": map[string]any{"data": []any{map[string]any{"data": b64}}}},
}
// raw 保存原始,供当前处理流程使用
raw, _ := json.Marshal(frame)
c.Write(r.Context(), websocket.MessageText, raw)
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
defer cancel()
_, _, _ = c.Read(ctx) // ACK
}))
defer srv.Close()
// dialCtx、dialCancel 保存dialCtx、dial取消,供当前处理流程使用
dialCtx, dialCancel := context.WithTimeout(context.Background(), 2*time.Second)
defer dialCancel()
// dialed、err 保存dialed、err,供当前处理流程使用
dialed, _, err := websocket.Dial(dialCtx, wsURL(srv), nil)
if err != nil {
t.Fatalf("dial: %v", err)
@@ -122,9 +145,13 @@ func TestReceiveLoop_NonJSONSkipped(t *testing.T) {
defer dialed.CloseNow()
dialed.SetReadLimit(8 << 20)
// conn 保存conn,供当前处理流程使用
conn := newConn(dialed, Config{}, nilLogger())
// got 保存got,供当前处理流程使用
var got map[string]any
// loopDone 保存loopDone,供当前处理流程使用
loopDone := make(chan error, 1)
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
go func() {
@@ -138,7 +165,9 @@ func TestReceiveLoop_NonJSONSkipped(t *testing.T) {
// TestHeartbeatLoop_ContextCancel HeartbeatLoop 应在 ctx 取消时及时退出。
func TestHeartbeatLoop_ContextCancel(t *testing.T) {
// srv 保存srv,供当前处理流程使用
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// c、err 保存c、err,供当前处理流程使用
c, err := websocket.Accept(w, r, nil)
if err != nil {
return
@@ -148,15 +177,18 @@ func TestHeartbeatLoop_ContextCancel(t *testing.T) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
for {
if _, _, err := c.Read(ctx); err != nil {
if // err 保存err,供当前处理流程使用
_, _, err := c.Read(ctx); err != nil {
return
}
}
}))
defer srv.Close()
// dialCtx、dialCancel 保存dialCtx、dial取消,供当前处理流程使用
dialCtx, dialCancel := context.WithTimeout(context.Background(), 2*time.Second)
defer dialCancel()
// dialed、err 保存dialed、err,供当前处理流程使用
dialed, _, err := websocket.Dial(dialCtx, wsURL(srv), nil)
if err != nil {
t.Fatalf("dial: %v", err)
@@ -164,8 +196,11 @@ func TestHeartbeatLoop_ContextCancel(t *testing.T) {
defer dialed.CloseNow()
dialed.SetReadLimit(8 << 20)
// conn 保存conn,供当前处理流程使用
conn := newConn(dialed, Config{}, nilLogger())
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// loopDone 保存loopDone,供当前处理流程使用
loopDone := make(chan error, 1)
go func() {
loopDone <- conn.HeartbeatLoop(ctx, 50*time.Millisecond)
@@ -174,7 +209,8 @@ func TestHeartbeatLoop_ContextCancel(t *testing.T) {
time.Sleep(200 * time.Millisecond)
cancel()
select {
case err := <-loopDone:
case // err 保存err,供当前处理流程使用
err := <-loopDone:
if err != nil && err != context.Canceled {
t.Fatalf("HeartbeatLoop 退出 err=%v", err)
}