阶段十:完成非冻结 Browser 注释基线清零

This commit is contained in:
Christ committed 2026-08-15 05:36:32 +08:00
1 parent a45a82a149
commit 393c45a1e3
22 files changed
+684 -4177

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -637,3 +637,4 @@ npm --prefix frontend run build
| 2026-08-15 | 完成阶段 10 第十一个 PR 切片“Go internal/renewal 注释基线按领域清零” | 为续期冷却、调度器、平台运行凭证范围和相关测试补齐函数、变量、字段及常量中文注释;`internal/renewal` 注释基线清零;Renewal 定向测试、`go test -race ./internal/renewal`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/notify、internal/chat 等领域注释基线 |
| 2026-08-15 | 完成阶段 10 第十二个 PR 切片“Go internal/notify 注释基线按领域清零” | 为通知器、渠道与账号绑定、通知 outbox、SMTP 守卫及其测试补齐函数、变量、字段和常量中文注释;`internal/notify` 注释基线清零;Notify 定向测试、`go test -race ./internal/notify`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/chat 领域注释基线 |
| 2026-08-15 | 完成阶段 10 第十三个 PR 切片“Go internal/chat 注释基线按领域清零” | 为聊天 repository、消息服务、账号订阅、已读状态、事件广播及其测试补齐函数、变量、字段和常量中文注释;`internal/chat` 注释基线清零;Chat 定向测试、`go test -race ./internal/chat`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:进入非冻结 browser、cmd 与 tools 注释基线清理 |
| 2026-08-15 | 完成阶段 10 第十四个 PR 切片“Go 非冻结 internal/browser 注释基线按领域清零” | 为 Cookie、订单、密码登录、二维码刷新、生命周期、用户数据目录和浏览器辅助测试补齐函数、变量、字段及常量中文注释;严格跳过冻结的 slider/CAPTCHA 实现与测试;非冻结 browser 注释基线清零,冻结文件保留 664 项原有基线;Browser 定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 cmd 与 tools 注释基线,并保留冻结基线边界 |
+110 -13
View File
@@ -15,6 +15,7 @@ import (
"xianyu-go/internal/xianyu/cookierefresh"
)
// quickRenewPageLoadWait 保存quickRenew页码LoadWait,供当前处理流程使用
const (
quickRenewPageLoadWait = 3 * time.Second
quickRenewAfterClick = 5 * time.Second
@@ -24,6 +25,7 @@ const (
officialReloadWait = 5 * time.Second
)
// ErrInteractiveLoginRequired 保存ErrInteractive登录Required,供当前处理流程使用
var (
ErrInteractiveLoginRequired = errors.New("浏览器会话已退出登录,需要交互式登录")
ErrSecurityVerification = errors.New("闲鱼要求安全验证,需要人工处理")
@@ -33,7 +35,9 @@ var (
//
// 这个方法位于密码登录之前:如果 Cookie 仍保留可续期的浏览器会话,页面通常会给出
// 免输密码的快速进入入口。成功点击后提取完整 Cookie,可避免更重的账号密码登录。
// CookieRenew 负责登录凭证Renew相关处理。
func (m *Manager) CookieRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (map[string]string, error) {
// newCookies、err 保存newCookies、err,供当前处理流程使用
newCookies, err := m.BrowserQuickRenew(ctx, cookieID, cookieStr, headless)
if err != nil {
return nil, err
@@ -41,17 +45,22 @@ func (m *Manager) CookieRenew(ctx context.Context, cookieID, cookieStr string, h
return cookierefresh.ParseCookieString(newCookies), nil
}
// newPersistentPasswordContext 负责newPersistent密码上下文相关处理。
func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, userDataDir string, headless bool) (playwright.BrowserContext, func(), error) {
// lock 保存锁,供当前处理流程使用
lock := m.accountRenewLock(cookieID)
lock.Lock()
// unlock 保存unlock,供当前处理流程使用
unlock := func() { lock.Unlock() }
// releaseSlot、err 保存releaseSlot、err,供当前处理流程使用
releaseSlot, err := m.acquireRenewSlot(ctx)
if err != nil {
unlock()
return nil, nil, err
}
if err := m.init(); err != nil {
if // err 保存err,供当前处理流程使用
err := m.init(); err != nil {
releaseSlot()
unlock()
return nil, nil, err
@@ -63,9 +72,12 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us
return nil, nil, err
}
cleanSingletonFiles(userDataDir)
// bctx 保存bctx,供当前处理流程使用
var bctx playwright.BrowserContext
// lastErr 保存lastErr,供当前处理流程使用
var lastErr error
for attempt := 1; attempt <= 2; attempt++ {
for // attempt 保存尝试次数,供当前处理流程使用
attempt := 1; attempt <= 2; attempt++ {
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, passwordPersistentContextOptions(headless))
if err == nil {
break
@@ -79,6 +91,7 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us
unlock()
return nil, nil, fmt.Errorf("启动持久化浏览器失败: %w", lastErr)
}
// release 保存release,供当前处理流程使用
release := func() {
_ = bctx.Close()
releaseSlot()
@@ -87,6 +100,7 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us
return bctx, release, nil
}
// passwordPersistentContextOptions 负责密码Persistent上下文Options相关处理。
func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunchPersistentContextOptions {
return playwright.BrowserTypeLaunchPersistentContextOptions{
Headless: playwright.Bool(headless),
@@ -106,6 +120,7 @@ func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunc
// BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。
func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error) {
// newCookies、err 保存newCookies、err,供当前处理流程使用
newCookies, _, err := m.BrowserQuickRenewSnapshot(ctx, cookieID, cookieStr, nil, headless)
return newCookies, err
}
@@ -113,27 +128,32 @@ func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr str
// BrowserQuickRenewSnapshot is the full-fidelity variant of BrowserQuickRenew.
// Callers that persist cookie metadata should use it directly: Chromium's final
// jar is authoritative for both deletions and attributes such as expiry/path.
// BrowserQuickRenewSnapshot 负责浏览器QuickRenewSnapshot相关处理。
func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
if cookieStr == "" && snapshot == nil {
return "", nil, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法浏览器续期")
}
// 持久化的扁平值始终以消息页为 canonical scope;这里也必须按 /im
// 解释,避免漏掉或错误映射 Path=/im 的连接凭证。
// effectiveSnapshot 保存effectiveSnapshot,供当前处理流程使用
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
// bctx、release、err 保存bctx、release、err,供当前处理流程使用
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, quickRenewHeadless(headless))
if err != nil {
return "", nil, err
}
defer release()
// page、err 保存page、err,供当前处理流程使用
page, err := bctx.NewPage()
if err != nil {
return "", nil, fmt.Errorf("新建 page 失败: %w", err)
}
defer func() { _ = page.Close() }()
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
if // err 保存err,供当前处理流程使用
_, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(quickRenewTimeoutMS),
}); err != nil {
@@ -141,9 +161,12 @@ func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cooki
}
time.Sleep(quickRenewPageLoadWait)
// hasQuickEnter 保存hasQuickEnter,供当前处理流程使用
hasQuickEnter := false
// renewErr 保存renewErr,供当前处理流程使用
var renewErr error
if err := verifyHomeLoginState(page); err != nil {
if // err 保存err,供当前处理流程使用
err := verifyHomeLoginState(page); err != nil {
if errors.Is(err, ErrSecurityVerification) {
renewErr = err
} else {
@@ -157,6 +180,7 @@ func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cooki
}
}
// newCookies、newSnapshot、err 保存newCookies、newSnapshot、err,供当前处理流程使用
newCookies, newSnapshot, err := readAuthoritativeCookieJar(bctx, goofishIMURL)
if err != nil {
return "", nil, errors.Join(renewErr, err)
@@ -175,28 +199,34 @@ func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cooki
// account's persistent profile. One ordinary page load is enough to run the
// site's own auto-login plugin; repeated reloads create an avoidable risk
// signal and are deliberately not used.
// CookiesRefreshSnapshot 负责CookiesRefreshSnapshot相关处理。
func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, bool, error) {
if cookieStr == "" && snapshot == nil {
return "", nil, false, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法执行续期")
}
// effectiveSnapshot 保存effectiveSnapshot,供当前处理流程使用
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
// bctx、release、err 保存bctx、release、err,供当前处理流程使用
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, cookiesRefreshHeadless(headless))
if err != nil {
return "", nil, false, err
}
defer release()
// page、err 保存page、err,供当前处理流程使用
page, err := bctx.NewPage()
if err != nil {
return "", nil, false, fmt.Errorf("新建 page 失败: %w", err)
}
defer func() { _ = page.Close() }()
// reloaded、renewErr 保存reloaded、renewErr,供当前处理流程使用
reloaded, renewErr := navigateOfficialRenewPage(ctx, page)
if renewErr == nil {
renewErr = verifyHomeLoginState(page)
}
// newCookies、newSnapshot、err 保存newCookies、newSnapshot、err,供当前处理流程使用
newCookies, newSnapshot, err := readAuthoritativeCookieJar(bctx, goofishIMURL)
if err != nil {
return "", nil, reloaded, errors.Join(renewErr, err)
@@ -211,10 +241,15 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt
return newCookies, newSnapshot, reloaded, nil
}
// navigateOfficialRenewPage 负责navigateOfficialRenew页码相关处理。
func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool, error) {
// silentStarted 保存silentStarted,供当前处理流程使用
silentStarted := make(chan struct{}, 1)
// silentSettled 保存silentSettled,供当前处理流程使用
silentSettled := make(chan bool, 1)
// reloadCommitted 保存reloadCommitted,供当前处理流程使用
reloadCommitted := make(chan struct{}, 1)
// navigationArmed 保存navigationArmed,供当前处理流程使用
var navigationArmed atomic.Bool
page.OnRequest(func(request playwright.Request) {
if isSilentHasLoginURL(request.URL()) {
@@ -249,7 +284,8 @@ func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool,
}
})
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
if // err 保存err,供当前处理流程使用
_, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(60000),
}); err != nil {
@@ -260,7 +296,9 @@ func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool,
// silentHasLogin. Observe the actual request instead of assuming hydration
// completed at DOMContentLoaded; navigation Set-Cookie may also change the
// sdkSilent/long-login branch.
// observeTimer 保存observe定时器,供当前处理流程使用
observeTimer := time.NewTimer(officialAutoLoginWait)
// requestStarted 保存请求Started,供当前处理流程使用
requestStarted := false
select {
case <-ctx.Done():
@@ -275,7 +313,9 @@ func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool,
// The plugin's 2s Promise timeout does not abort fetch. Keep the page
// alive until Chromium finishes the response body (and applies Set-Cookie), while
// leaving reload/no-reload entirely to the official JavaScript.
// drainTimer 保存drain定时器,供当前处理流程使用
drainTimer := time.NewTimer(officialFetchDrainWait)
// requestFinished 保存请求Finished,供当前处理流程使用
requestFinished := false
select {
case requestFinished = <-silentSettled:
@@ -286,11 +326,13 @@ func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool,
case <-drainTimer.C:
}
if requestFinished {
// reloadTimer 保存reload定时器,供当前处理流程使用
reloadTimer := time.NewTimer(officialReloadWait)
select {
case <-reloadCommitted:
reloadTimer.Stop()
if err := page.WaitForLoadState(playwright.PageWaitForLoadStateOptions{
if // err 保存err,供当前处理流程使用
err := page.WaitForLoadState(playwright.PageWaitForLoadStateOptions{
State: playwright.LoadStateDomcontentloaded, Timeout: playwright.Float(10000),
}); err != nil {
return true, fmt.Errorf("等待官网续期 reload 完成: %w", err)
@@ -308,11 +350,14 @@ func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool,
return false, nil
}
// readAuthoritativeCookieJar 负责readAuthoritative登录凭证Jar相关处理。
func readAuthoritativeCookieJar(bctx playwright.BrowserContext, rawURL string) (string, []cookierefresh.BrowserCookie, error) {
// all、err 保存all、err,供当前处理流程使用
all, err := bctx.Cookies()
if err != nil {
return "", nil, fmt.Errorf("提取浏览器 Cookie Jar: %w", err)
}
// snapshot 保存snapshot,供当前处理流程使用
snapshot := cookieSnapshotFromPlaywright(all)
if snapshot == nil {
snapshot = []cookierefresh.BrowserCookie{}
@@ -320,10 +365,12 @@ func readAuthoritativeCookieJar(bctx playwright.BrowserContext, rawURL string) (
return currentCookieHeader(snapshot, rawURL), snapshot, nil
}
// isSilentHasLoginURL 负责isSilentHas登录URL相关处理。
func isSilentHasLoginURL(rawURL string) bool {
return strings.Contains(rawURL, "/newlogin/silentHasLogin.do")
}
// reconcileSnapshotWithCurrentCookie 负责reconcileSnapshotWithCurrent登录凭证相关处理。
func reconcileSnapshotWithCurrentCookie(snapshot []cookierefresh.BrowserCookie, cookieStr, rawURL string) []cookierefresh.BrowserCookie {
if snapshot == nil {
return nil
@@ -339,26 +386,36 @@ func reconcileSnapshotWithCurrentCookie(snapshot []cookierefresh.BrowserCookie,
// CookieRenewSnapshot 兼容旧调用,等价于定时 COOKIES 快照续期。
func (m *Manager) CookieRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
// cookies、refreshed、err 保存cookies、refreshed、err,供当前处理流程使用
cookies, refreshed, _, err := m.CookiesRefreshSnapshot(ctx, cookieID, cookieStr, snapshot, headless)
return cookies, refreshed, err
}
// clickQuickEnter 负责clickQuickEnter相关处理。
func clickQuickEnter(page playwright.Page) bool {
// frames 保存frames,供当前处理流程使用
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
// f 表示当前遍历过程中的f
for _, f := range frames {
// sel 表示当前遍历过程中的sel
for _, sel := range quickEnterSelectors {
// el、err 保存el、err,供当前处理流程使用
el, err := f.QuerySelector(sel)
if err == nil && el != nil && elementVisible(el) {
if err := el.Click(); err == nil {
if // err 保存err,供当前处理流程使用
err := el.Click(); err == nil {
return true
}
}
}
// buttons、err 保存buttons、err,供当前处理流程使用
buttons, err := f.QuerySelectorAll("button")
if err != nil {
continue
}
// btn 表示当前遍历过程中的btn
for _, btn := range buttons {
// text 保存文本,供当前处理流程使用
text, _ := btn.TextContent()
if strings.Contains(strings.TrimSpace(text), "快速进入") && elementVisible(btn) {
_ = btn.Click()
@@ -369,6 +426,7 @@ func clickQuickEnter(page playwright.Page) bool {
return false
}
// quickEnterSelectors 保存quickEnterSelectors,供当前处理流程使用
var quickEnterSelectors = []string{
`button:has-text("快速进入")`,
`button[type="submit"]:has-text("快速进入")`,
@@ -376,10 +434,12 @@ var quickEnterSelectors = []string{
`.fn-button:has-text("快速进入")`,
}
// verifyHomeLoginState 负责verifyHome登录状态相关处理。
func verifyHomeLoginState(page playwright.Page) error {
if pageHasSecurityVerification(page) {
return ErrSecurityVerification
}
// result、err 保存result、err,供当前处理流程使用
result, err := page.Evaluate(`() => {
const visible = (el) => {
const rect = el.getBoundingClientRect();
@@ -400,11 +460,14 @@ func verifyHomeLoginState(page playwright.Page) error {
if err != nil {
return fmt.Errorf("读取浏览器登录状态失败: %w", err)
}
// signals、ok 保存signals、ok,供当前处理流程使用
signals, ok := result.(map[string]any)
if !ok {
return fmt.Errorf("浏览器登录状态返回格式异常")
}
// personal 保存personal,供当前处理流程使用
personal, _ := signals["personal"].(bool)
// login 保存登录,供当前处理流程使用
login, _ := signals["login"].(bool)
if personal && !login {
return nil
@@ -415,18 +478,24 @@ func verifyHomeLoginState(page playwright.Page) error {
return fmt.Errorf("%w: 页面未出现个人主页入口", ErrInteractiveLoginRequired)
}
// pageHasSecurityVerification 负责页码HasSecurityVerification相关处理。
func pageHasSecurityVerification(page playwright.Page) bool {
// frame 表示当前遍历过程中的frame
for _, frame := range page.Frames() {
// lowerURL 保存lowerURL,供当前处理流程使用
lowerURL := strings.ToLower(frame.URL())
// marker 表示当前遍历过程中的marker
for _, marker := range []string{"photoverify", "normal_validate", "identity_verify", "baxia-punish", "/punish"} {
if strings.Contains(lowerURL, marker) {
return true
}
}
// content、err 保存content、err,供当前处理流程使用
content, err := frame.Content()
if err != nil {
continue
}
// marker 表示当前遍历过程中的marker
for _, marker := range []string{"拍摄脸部", "请拖动下方滑块完成验证", "请按住滑块", "安全验证未通过"} {
if strings.Contains(content, marker) {
return true
@@ -436,34 +505,44 @@ func pageHasSecurityVerification(page playwright.Page) bool {
return false
}
// elementVisible 负责elementVisible相关处理。
func elementVisible(el playwright.ElementHandle) bool {
// visible、err 保存visible、err,供当前处理流程使用
visible, err := el.IsVisible()
return err == nil && visible
}
// cleanSingletonFiles 负责cleanSingleton文件列表相关处理。
func cleanSingletonFiles(userDataDir string) {
// name 表示当前遍历过程中的名称
for _, name := range []string{"SingletonLock", "SingletonSocket", "SingletonCookie"} {
_ = os.Remove(filepath.Join(userDataDir, name))
}
}
// newPersistentRenewContext 负责newPersistentRenew上下文相关处理。
func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool, captchaProfile ...bool) (playwright.BrowserContext, func(), error) {
// lock 保存锁,供当前处理流程使用
lock := m.accountRenewLock(cookieID)
lock.Lock()
// unlock 保存unlock,供当前处理流程使用
unlock := func() { lock.Unlock() }
// releaseSlot、err 保存releaseSlot、err,供当前处理流程使用
releaseSlot, err := m.acquireRenewSlot(ctx)
if err != nil {
unlock()
return nil, nil, err
}
if err := m.init(); err != nil {
if // err 保存err,供当前处理流程使用
err := m.init(); err != nil {
releaseSlot()
unlock()
return nil, nil, err
}
// userDataDir、err 保存用户数据Dir、err,供当前处理流程使用
userDataDir, err := resolvePersistentUserDataDir(filepath.Join("browser_data", "user_"+pureUserID(cookieID)))
if err != nil {
releaseSlot()
@@ -471,13 +550,17 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
return nil, nil, err
}
cleanSingletonFiles(userDataDir)
// viewport 保存viewport,供当前处理流程使用
viewport := &playwright.Size{Width: 1280, Height: 720}
if len(captchaProfile) > 0 && captchaProfile[0] {
viewport = &playwright.Size{Width: 1980, Height: 1024}
}
// bctx 保存bctx,供当前处理流程使用
var bctx playwright.BrowserContext
// lastErr 保存lastErr,供当前处理流程使用
var lastErr error
for attempt := 1; attempt <= 2; attempt++ {
for // attempt 保存尝试次数,供当前处理流程使用
attempt := 1; attempt <= 2; attempt++ {
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, playwright.BrowserTypeLaunchPersistentContextOptions{
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
@@ -500,24 +583,28 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
return nil, nil, fmt.Errorf("启动持久化浏览器失败: %w", lastErr)
}
if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
if // err 保存err,供当前处理流程使用
err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
m.logger.Warn("注入 stealth 脚本失败", "err", err)
}
if snapshot != nil {
if err := bctx.ClearCookies(); err != nil {
if // err 保存err,供当前处理流程使用
err := bctx.ClearCookies(); err != nil {
_ = bctx.Close()
releaseSlot()
unlock()
return nil, nil, fmt.Errorf("浏览器续期清理旧 Cookie 失败: %w", err)
}
if err := bctx.AddCookies(snapshotToOptionalCookies(snapshot)); err != nil {
if // err 保存err,供当前处理流程使用
err := bctx.AddCookies(snapshotToOptionalCookies(snapshot)); err != nil {
_ = bctx.Close()
releaseSlot()
unlock()
return nil, nil, fmt.Errorf("浏览器续期注入 Cookie 快照失败: %w", err)
}
} else if cookieStr != "" {
if err := addCookieStr(bctx, cookieStr); err != nil {
if // err 保存err,供当前处理流程使用
err := addCookieStr(bctx, cookieStr); err != nil {
_ = bctx.Close()
releaseSlot()
unlock()
@@ -525,6 +612,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
}
}
// release 保存release,供当前处理流程使用
release := func() {
_ = bctx.Close()
releaseSlot()
@@ -533,6 +621,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
return bctx, release, nil
}
// quickRenewHeadless 负责quickRenewHeadless相关处理。
func quickRenewHeadless(headless bool) bool {
return resolveHeadlessRequest(headless)
}
@@ -540,10 +629,12 @@ func quickRenewHeadless(headless bool) bool {
// ResolveHeadless returns the browser headless mode from account ShowBrowser plus
// the optional BROWSER_HEADLESS override. All browser-backed login/renewal flows
// use this resolver so headed/headless only changes visibility, not behavior.
// ResolveHeadless 处理Headless。
func ResolveHeadless(showBrowser bool) bool {
return resolveHeadlessRequest(!showBrowser)
}
// resolveHeadlessRequest 负责resolveHeadless请求相关处理。
func resolveHeadlessRequest(headless bool) bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("BROWSER_HEADLESS"))) {
case "true", "1", "yes", "on":
@@ -555,14 +646,18 @@ func resolveHeadlessRequest(headless bool) bool {
}
}
// cookiesRefreshHeadless 负责cookiesRefreshHeadless相关处理。
func cookiesRefreshHeadless(headless bool) bool {
return quickRenewHeadless(headless)
}
// pureUserID 负责pure用户ID相关处理。
func pureUserID(cookieID string) string {
cookieID = sanitize(cookieID)
// parts 保存parts,供当前处理流程使用
parts := strings.Split(cookieID, "_")
if len(parts) >= 2 {
// last 保存last,供当前处理流程使用
last := parts[len(parts)-1]
if len(last) >= 10 && allDigits(last) {
return strings.Join(parts[:len(parts)-1], "_")
@@ -574,10 +669,12 @@ func pureUserID(cookieID string) string {
return cookieID
}
// allDigits 负责allDigits相关处理。
func allDigits(s string) bool {
if s == "" {
return false
}
// r 表示当前遍历过程中的r
for _, r := range s {
if r < '0' || r > '9' {
return false
+22 -3
View File
@@ -6,12 +6,15 @@ import (
"xianyu-go/internal/xianyu/cookierefresh"
)
// TestCredentialCookieSnapshotUsesCurrentFlatCookieAsAuthority 负责TestCredential登录凭证SnapshotUsesCurrentFlat登录凭证AsAuthority相关处理。
func TestCredentialCookieSnapshotUsesCurrentFlatCookieAsAuthority(t *testing.T) {
// existing 保存existing,供当前处理流程使用
existing := []cookierefresh.BrowserCookie{
{Name: "session", Value: "stale", Domain: ".goofish.com", Path: "/", Expires: 123, HTTPOnly: true, Secure: true, SameSite: "Lax"},
{Name: "removed", Value: "old", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "passport", Value: "keep", Domain: ".taobao.com", Path: "/", Secure: true},
}
// got 保存got,供当前处理流程使用
got := credentialCookieSnapshot(existing, map[string]string{
"session": "fresh",
"new": "value",
@@ -19,36 +22,47 @@ func TestCredentialCookieSnapshotUsesCurrentFlatCookieAsAuthority(t *testing.T)
if len(got) != 3 {
t.Fatalf("snapshot len=%d, want 3: %+v", len(got), got)
}
// byName 保存by名称,供当前处理流程使用
byName := make(map[string]cookierefresh.BrowserCookie, len(got))
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range got {
byName[cookie.Name] = cookie
}
// session 保存会话,供当前处理流程使用
session := byName["session"]
if session.Value != "fresh" || session.Expires != 123 || !session.HTTPOnly || session.SameSite != "Lax" {
t.Fatalf("existing attributes or fresh value were lost: %+v", session)
}
if _, exists := byName["removed"]; exists {
if // exists 保存exists,供当前处理流程使用
_, exists := byName["removed"]; exists {
t.Fatalf("cookie absent from current flat value was resurrected: %+v", got)
}
if passport := byName["passport"]; passport.Value != "keep" || passport.Domain != ".taobao.com" {
if // passport 保存passport,供当前处理流程使用
passport := byName["passport"]; passport.Value != "keep" || passport.Domain != ".taobao.com" {
t.Fatalf("out-of-scope cookie was lost: %+v", passport)
}
// added 保存added,供当前处理流程使用
added := byName["new"]
if added.Value != "value" || added.Domain != goofishDot || added.Path != "/" || !added.Secure {
t.Fatalf("new cookie defaults mismatch: %+v", added)
}
}
// TestCredentialCookieSnapshotPreservesAmbiguousSameNameScopes 负责TestCredential登录凭证SnapshotPreservesAmbiguousSame名称Scopes相关处理。
func TestCredentialCookieSnapshotPreservesAmbiguousSameNameScopes(t *testing.T) {
// existing 保存existing,供当前处理流程使用
existing := []cookierefresh.BrowserCookie{
{Name: "token", Value: "old-root", Domain: ".goofish.com", Path: "/"},
{Name: "token", Value: "old-im", Domain: "www.goofish.com", Path: "/im", HTTPOnly: true},
}
// got 保存got,供当前处理流程使用
got := credentialCookieSnapshot(existing, map[string]string{"token": "fresh"})
if len(got) != 2 {
t.Fatalf("same-name scoped cookies collapsed: %+v", got)
}
// values 保存values,供当前处理流程使用
values := map[string]string{}
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range got {
values[cookie.Path] = cookie.Value
}
@@ -57,9 +71,12 @@ func TestCredentialCookieSnapshotPreservesAmbiguousSameNameScopes(t *testing.T)
}
}
// TestReconcileSnapshotWithCurrentCookie 负责TestReconcileSnapshotWithCurrent登录凭证相关处理。
func TestReconcileSnapshotWithCurrentCookie(t *testing.T) {
// snapshot 保存snapshot,供当前处理流程使用
snapshot := []cookierefresh.BrowserCookie{{Name: "session", Value: "old", Domain: ".goofish.com", Path: "/", Expires: 456}}
// got 保存got,供当前处理流程使用
got := reconcileSnapshotWithCurrentCookie(snapshot, "session=new", goofishIMURL)
if len(got) != 1 || got[0].Value != "new" || got[0].Expires != 456 {
t.Fatalf("flat cookie did not update snapshot without losing attributes: %+v", got)
@@ -74,11 +91,13 @@ func TestReconcileSnapshotWithCurrentCookie(t *testing.T) {
if got == nil || len(got) != 0 {
t.Fatalf("authoritative empty snapshot must not fall back to flat cookies: %#v", got)
}
if got := reconcileSnapshotWithCurrentCookie(nil, "session=legacy", goofishIMURL); got != nil {
if // got 保存got,供当前处理流程使用
got := reconcileSnapshotWithCurrentCookie(nil, "session=legacy", goofishIMURL); got != nil {
t.Fatalf("missing snapshot should preserve the legacy flat-cookie fallback: %#v", got)
}
}
// TestSilentHasLoginURLMatcher 负责TestSilentHas登录URLMatcher相关处理。
func TestSilentHasLoginURLMatcher(t *testing.T) {
if !isSilentHasLoginURL("https://passport.goofish.com/newlogin/silentHasLogin.do?appName=xianyu") {
t.Fatal("official silentHasLogin request was not recognized")
+29 -2
View File
@@ -13,10 +13,13 @@ import (
// 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, ";") {
part = strings.TrimSpace(part)
if eq := strings.Index(part, "="); eq >= 0 {
if // eq 保存eq,供当前处理流程使用
eq := strings.Index(part, "="); eq >= 0 {
m[part[:eq]] = part[eq+1:]
}
}
@@ -25,7 +28,9 @@ func parseCookieStr(s string) map[string]string {
// cookieMarshal 把 map 拼成 "k=v; k2=v2"。
func cookieMarshal(m map[string]string) string {
// parts 保存parts,供当前处理流程使用
parts := make([]string, 0, len(m))
// k、v 表示当前遍历过程中的k、v
for k, v := range m {
parts = append(parts, k+"="+v)
}
@@ -39,11 +44,16 @@ func MarshalCookies(m map[string]string) string {
// parseCookieStrToPlaywright 把 cookie 字符串转成 playwright OptionalCookie。
func parseCookieStrToPlaywright(s string) []playwright.OptionalCookie {
// cookies 保存cookies,供当前处理流程使用
var cookies []playwright.OptionalCookie
// part 表示当前遍历过程中的part
for _, part := range strings.Split(s, ";") {
part = strings.TrimSpace(part)
if eq := strings.Index(part, "="); eq >= 0 {
if // eq 保存eq,供当前处理流程使用
eq := strings.Index(part, "="); eq >= 0 {
// name 保存名称,供当前处理流程使用
name := part[:eq]
// value 保存值,供当前处理流程使用
value := part[eq+1:]
if name == "" {
continue
@@ -59,17 +69,23 @@ func parseCookieStrToPlaywright(s string) []playwright.OptionalCookie {
return cookies
}
// snapshotToOptionalCookies 负责snapshotToOptionalCookies相关处理。
func snapshotToOptionalCookies(snapshot []cookierefresh.BrowserCookie) []playwright.OptionalCookie {
// out 保存out,供当前处理流程使用
var out []playwright.OptionalCookie
// c 表示当前遍历过程中的c
for _, c := range cookierefresh.NormalizeSnapshot(snapshot) {
// domain 保存domain,供当前处理流程使用
domain := c.Domain
if domain == "" {
domain = goofishDot
}
// path 保存路径,供当前处理流程使用
path := c.Path
if path == "" {
path = "/"
}
// oc 保存oc,供当前处理流程使用
oc := playwright.OptionalCookie{
Name: c.Name,
Value: c.Value,
@@ -97,9 +113,13 @@ func snapshotToOptionalCookies(snapshot []cookierefresh.BrowserCookie) []playwri
return out
}
// cookieSnapshotFromPlaywright 负责登录凭证SnapshotFromPlaywright相关处理。
func cookieSnapshotFromPlaywright(cs []playwright.Cookie) []cookierefresh.BrowserCookie {
// out 保存out,供当前处理流程使用
out := make([]cookierefresh.BrowserCookie, 0, len(cs))
// c 表示当前遍历过程中的c
for _, c := range cs {
// bc 保存bc,供当前处理流程使用
bc := cookierefresh.BrowserCookie{
Name: c.Name,
Value: c.Value,
@@ -122,7 +142,9 @@ func cookieSnapshotFromPlaywright(cs []playwright.Cookie) []cookierefresh.Browse
// cookiesToMap 把 playwright Cookie 切片转成 map。
func cookiesToMap(cs []playwright.Cookie) map[string]string {
// m 保存m,供当前处理流程使用
m := make(map[string]string, len(cs))
// c 表示当前遍历过程中的c
for _, c := range cs {
m[c.Name] = c.Value
}
@@ -132,19 +154,23 @@ func cookiesToMap(cs []playwright.Cookie) map[string]string {
// rng is used only for human-like pointer timing in interactive captcha
// handling. It must not be used to alter the browser/device fingerprint.
// #nosec G404 -- non-cryptographic interaction jitter only.
// rng 保存rng,供当前处理流程使用
var rng = &lockedRand{value: rand.New(rand.NewSource(time.Now().UnixNano()))}
// lockedRand 保存lockedRand,供当前处理流程使用
type lockedRand struct {
mu sync.Mutex
value *rand.Rand
}
// Intn 负责Intn相关处理。
func (r *lockedRand) Intn(n int) int {
r.mu.Lock()
defer r.mu.Unlock()
return r.value.Intn(n)
}
// Float64 负责Float64相关处理。
func (r *lockedRand) Float64() float64 {
r.mu.Lock()
defer r.mu.Unlock()
@@ -154,6 +180,7 @@ func (r *lockedRand) Float64() float64 {
// stealthScript is intentionally stable. Randomly overriding canvas, WebGL,
// hardware, platform, or timing APIs makes one account present a different
// device fingerprint on every renewal and is itself a strong risk signal.
// stealthScript 负责stealthScript相关处理。
func stealthScript() string {
return stealthTemplate
}
+20 -2
View File
@@ -5,12 +5,16 @@ import (
"testing"
)
// TestParseCookieStrRoundTrip 负责TestParse登录凭证StrRoundTrip相关处理。
func TestParseCookieStrRoundTrip(t *testing.T) {
// in 保存in,供当前处理流程使用
in := "unb=999; _m_h5_tk=abc_1; cookie2=xyz"
// m 保存m,供当前处理流程使用
m := parseCookieStr(in)
if m["unb"] != "999" || m["_m_h5_tk"] != "abc_1" || m["cookie2"] != "xyz" {
t.Fatalf("解析异常: %+v", m)
}
// out 保存out,供当前处理流程使用
out := cookieMarshal(m)
// 顺序不保证,逐项检查。
for _, kv := range []string{"unb=999", "_m_h5_tk=abc_1", "cookie2=xyz"} {
@@ -20,12 +24,16 @@ func TestParseCookieStrRoundTrip(t *testing.T) {
}
}
// TestParseCookieStrToPlaywright 负责TestParse登录凭证StrToPlaywright相关处理。
func TestParseCookieStrToPlaywright(t *testing.T) {
// cookies 保存cookies,供当前处理流程使用
cookies := parseCookieStrToPlaywright("a=1; b=2")
if len(cookies) != 2 {
t.Fatalf("每个 Cookie 只应注入一次,got %d", len(cookies))
}
// domains 保存domains,供当前处理流程使用
domains := make(map[string]bool)
// c 表示当前遍历过程中的c
for _, c := range cookies {
if c.Domain == nil {
t.Fatalf("domain 不能为空: %+v", c.Domain)
@@ -40,26 +48,34 @@ func TestParseCookieStrToPlaywright(t *testing.T) {
}
}
// TestParseCookieStrEmpty 负责TestParse登录凭证StrEmpty相关处理。
func TestParseCookieStrEmpty(t *testing.T) {
if got := parseCookieStr(""); len(got) != 0 {
if // got 保存got,供当前处理流程使用
got := parseCookieStr(""); len(got) != 0 {
t.Fatalf("空串应返回空 map, got %+v", got)
}
if got := parseCookieStrToPlaywright(",,, ;"); len(got) != 0 {
if // got 保存got,供当前处理流程使用
got := parseCookieStrToPlaywright(",,, ;"); len(got) != 0 {
t.Fatalf("无效串应返回空, got %+v", got)
}
}
// TestCookiesToMapAndStr 负责TestCookiesToMapAndStr相关处理。
func TestCookiesToMapAndStr(t *testing.T) {
// 用 cookiesToMap/cookiesToStr 覆盖(构造 Cookie 不导出字段,借 parse 间接)。
m := map[string]string{"unb": "1", "cna": "xx"}
// s 保存s,供当前处理流程使用
s := cookieMarshal(m)
// m2 保存m2,供当前处理流程使用
m2 := parseCookieStr(s)
if m2["unb"] != "1" || m2["cna"] != "xx" {
t.Fatalf("往返异常: %+v", m2)
}
}
// TestStealthScriptKeepsNativeFingerprint 负责TestStealthScriptKeepsNativeFingerprint相关处理。
func TestStealthScriptKeepsNativeFingerprint(t *testing.T) {
// s 保存s,供当前处理流程使用
s := stealthScript()
if strings.Contains(s, "{{") {
t.Fatalf("stealth 脚本仍有未替换占位符: %q", s[:min(200, len(s))])
@@ -67,6 +83,7 @@ func TestStealthScriptKeepsNativeFingerprint(t *testing.T) {
if !strings.Contains(s, "webdriver") {
t.Fatal("stealth 脚本应只规范化 webdriver")
}
// forbidden 表示当前遍历过程中的forbidden
for _, forbidden := range []string{"toDataURL", "WebGL", "hardwareConcurrency", "deviceMemory", "RTCPeerConnection", "Math.random", "navigator.platform"} {
if strings.Contains(s, forbidden) {
t.Fatalf("stealth 脚本不应伪造 %q", forbidden)
@@ -74,6 +91,7 @@ func TestStealthScriptKeepsNativeFingerprint(t *testing.T) {
}
}
// TestStealthScriptStable 负责TestStealthScriptStable相关处理。
func TestStealthScriptStable(t *testing.T) {
if stealthScript() != stealthScript() {
t.Fatal("同一浏览器配置不应产生漂移的指纹脚本")
+26 -3
View File
@@ -13,7 +13,9 @@ import (
// TokenCaptchaCookieSnapshot 在滑块引擎退出并释放持久化 Profile 后,重新打开
// 同一 Profile 读取最终 Cookie Jar。它不访问任何业务页面,只用于把滑块验证
// 已经产生的精确 Domain/Path/HttpOnly/Expires 属性交回 Go 凭证层。
// TokenCaptchaCookieSnapshot 负责令牌Captcha登录凭证Snapshot相关处理。
func (m *Manager) TokenCaptchaCookieSnapshot(ctx context.Context, cookieID string, headless bool) (string, []cookierefresh.BrowserCookie, error) {
// bctx、release、err 保存bctx、release、err,供当前处理流程使用
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, "", nil, quickRenewHeadless(headless), true)
if err != nil {
return "", nil, err
@@ -24,10 +26,13 @@ func (m *Manager) TokenCaptchaCookieSnapshot(ctx context.Context, cookieID strin
// syncCredentialCookies 为 token 滑块上下文同步 Cookie。普通登录、
// 续期、MTOP、Token 和 WebSocket 生产流程不得调用 Chromium。
// syncCredentialCookies 负责syncCredentialCookies相关处理。
func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string, snapshots ...[]cookierefresh.BrowserCookie) error {
if len(snapshots) > 0 && snapshots[0] != nil {
// preserved 保存preserved,供当前处理流程使用
preserved := cookierefresh.NormalizeSnapshot(snapshots[0])
if err := bctx.ClearCookies(); err != nil {
if // err 保存err,供当前处理流程使用
err := bctx.ClearCookies(); err != nil {
return err
}
if len(preserved) == 0 {
@@ -35,35 +40,47 @@ func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string, sna
}
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
}
// incoming 保存incoming,供当前处理流程使用
incoming := parseCookieStr(cookieStr)
if len(incoming) == 0 {
return fmt.Errorf("Cookie为空或格式错误")
}
// existing、err 保存existing、err,供当前处理流程使用
existing, err := bctx.Cookies()
if err != nil {
return err
}
// preserved 保存preserved,供当前处理流程使用
preserved := credentialCookieSnapshotForURL(cookieSnapshotFromPlaywright(existing), incoming, goofishIMURL)
if err := bctx.ClearCookies(); err != nil {
if // err 保存err,供当前处理流程使用
err := bctx.ClearCookies(); err != nil {
return err
}
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
}
// credentialCookieSnapshot 负责credential登录凭证Snapshot相关处理。
func credentialCookieSnapshot(existing []cookierefresh.BrowserCookie, incoming map[string]string) []cookierefresh.BrowserCookie {
return credentialCookieSnapshotForURL(existing, incoming, goofishIMURL)
}
// credentialCookieSnapshotForURL 负责credential登录凭证SnapshotForURL相关处理。
func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, incoming map[string]string, rawURL string) []cookierefresh.BrowserCookie {
// preserved 保存preserved,供当前处理流程使用
preserved := make([]cookierefresh.BrowserCookie, 0, len(existing)+len(incoming))
// matched 保存matched,供当前处理流程使用
matched := make(map[string]bool, len(incoming))
// counts 保存counts,供当前处理流程使用
counts := make(map[string]int, len(existing))
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range cookierefresh.NormalizeSnapshot(existing) {
counts[cookie.Name]++
}
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range existing {
if !cookieScopeMatches(cookie, rawURL) {
if value, ok := incoming[cookie.Name]; ok {
if // value、ok 保存value、ok,供当前处理流程使用
value, ok := incoming[cookie.Name]; ok {
if counts[cookie.Name] == 1 && cookie.PartitionKey == "" {
cookie.Value = value
}
@@ -72,6 +89,7 @@ func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, inco
preserved = append(preserved, cookie)
continue
}
// value、ok 保存value、ok,供当前处理流程使用
value, ok := incoming[cookie.Name]
if !ok {
continue
@@ -82,6 +100,7 @@ func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, inco
preserved = append(preserved, cookie)
matched[cookie.Name] = true
}
// name、value 表示当前遍历过程中的name、value
for name, value := range incoming {
if matched[name] {
continue
@@ -93,12 +112,16 @@ func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, inco
return cookierefresh.NormalizeSnapshot(preserved)
}
// cookieScopeMatches 负责登录凭证ScopeMatches相关处理。
func cookieScopeMatches(cookie cookierefresh.BrowserCookie, rawURL string) bool {
// header 保存header,供当前处理流程使用
header, _ := cookierefresh.ScopedCookieHeaderForRequest([]cookierefresh.BrowserCookie{cookie}, rawURL, "https://goofish.com", time.Unix(0, 0))
return header != ""
}
// currentCookieHeader 负责current登录凭证Header相关处理。
func currentCookieHeader(snapshot []cookierefresh.BrowserCookie, rawURL string) string {
// header 保存header,供当前处理流程使用
header, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, rawURL, "https://goofish.com", time.Now())
return header
}
+87 -16
View File
@@ -23,6 +23,7 @@ import (
)
// 默认 UA、语言、时区与视口。
// defaultW 保存defaultW,供当前处理流程使用
const (
defaultW = 1920
defaultH = 1080
@@ -44,13 +45,16 @@ func chromiumLaunchArgs() []string {
}
}
// chromiumExecutablePath 负责chromiumExecutable路径相关处理。
func chromiumExecutablePath() *string {
if path := strings.TrimSpace(os.Getenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH")); path != "" {
if // path 保存路径,供当前处理流程使用
path := strings.TrimSpace(os.Getenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH")); path != "" {
return playwright.String(path)
}
return nil
}
// skipPlaywrightBrowserDownload 负责skipPlaywright浏览器Download相关处理。
func skipPlaywrightBrowserDownload() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD"))) {
case "1", "true", "yes", "on":
@@ -60,42 +64,54 @@ func skipPlaywrightBrowserDownload() bool {
}
}
// packagedPlaywrightRuntimeReady 负责packagedPlaywrightRuntimeReady相关处理。
func packagedPlaywrightRuntimeReady() bool {
// driverDir 保存driverDir,供当前处理流程使用
driverDir := strings.TrimSpace(os.Getenv("PLAYWRIGHT_DRIVER_PATH"))
if driverDir == "" {
return false
}
// nodeReady 保存nodeReady,供当前处理流程使用
nodeReady := false
if nodePath := strings.TrimSpace(os.Getenv("PLAYWRIGHT_NODEJS_PATH")); nodePath != "" {
if // nodePath 保存node路径,供当前处理流程使用
nodePath := strings.TrimSpace(os.Getenv("PLAYWRIGHT_NODEJS_PATH")); nodePath != "" {
// err 保存err,供当前处理流程使用
_, err := os.Stat(nodePath)
nodeReady = err == nil
} else {
// nodeName 保存node名称,供当前处理流程使用
nodeName := "node"
if runtime.GOOS == "windows" {
nodeName = "node.exe"
}
// err 保存err,供当前处理流程使用
_, err := os.Stat(filepath.Join(driverDir, nodeName))
nodeReady = err == nil
}
if !nodeReady {
return false
}
if _, err := os.Stat(filepath.Join(driverDir, "package", "cli.js")); err != nil {
if // err 保存err,供当前处理流程使用
_, err := os.Stat(filepath.Join(driverDir, "package", "cli.js")); err != nil {
return false
}
if strings.TrimSpace(os.Getenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH")) != "" {
return true
}
// browserDir 保存浏览器Dir,供当前处理流程使用
browserDir := strings.TrimSpace(os.Getenv("PLAYWRIGHT_BROWSERS_PATH"))
if browserDir == "" {
return false
}
// matches、err 保存matches、err,供当前处理流程使用
matches, err := filepath.Glob(filepath.Join(browserDir, "chromium-*"))
if err != nil {
return false
}
// match 表示当前遍历过程中的match
for _, match := range matches {
if info, statErr := os.Stat(match); statErr == nil && info.IsDir() {
if // info、statErr 保存info、statErr,供当前处理流程使用
info, statErr := os.Stat(match); statErr == nil && info.IsDir() {
return true
}
}
@@ -130,6 +146,7 @@ type Manager struct {
tokenCaptchaFallbackFn tokenCaptchaEngineFunc
}
// poolEntry 保存poolEntry,供当前处理流程使用
type poolEntry struct {
cookieID string
browser playwright.Browser
@@ -155,6 +172,7 @@ func NewManager(logger *slog.Logger) *Manager {
if packagedPlaywrightRuntimeReady() {
return nil
}
// opts 保存opts,供当前处理流程使用
opts := &playwright.RunOptions{
Browsers: []string{"chromium"},
Verbose: false,
@@ -170,12 +188,14 @@ func NewManager(logger *slog.Logger) *Manager {
}
}
// accountRenewLock 负责账号Renew锁相关处理。
func (m *Manager) accountRenewLock(cookieID string) *sync.Mutex {
m.renewMu.Lock()
defer m.renewMu.Unlock()
if m.renewLocks == nil {
m.renewLocks = make(map[string]*sync.Mutex)
}
// lock 保存锁,供当前处理流程使用
lock := m.renewLocks[cookieID]
if lock == nil {
lock = &sync.Mutex{}
@@ -184,6 +204,7 @@ func (m *Manager) accountRenewLock(cookieID string) *sync.Mutex {
return lock
}
// acquireRenewSlot 负责acquireRenewSlot相关处理。
func (m *Manager) acquireRenewSlot(ctx context.Context) (func(), error) {
if m.renewSlots == nil {
m.renewSlots = make(chan struct{}, 3)
@@ -199,17 +220,20 @@ func (m *Manager) acquireRenewSlot(ctx context.Context) (func(), error) {
// init 懒加载 playwright(首次调用时下载 driver + chromium)。
func (m *Manager) init() error {
m.once.Do(func() {
if err := m.installFn(); err != nil {
if // err 保存err,供当前处理流程使用
err := m.installFn(); err != nil {
m.initErr = fmt.Errorf("安装 playwright/chromium 失败(缺系统依赖时需手动执行 playwright install --with-deps): %w", err)
return
}
// pw、err 保存pw、err,供当前处理流程使用
pw, err := m.runFn()
if err != nil {
m.initErr = fmt.Errorf("启动 playwright 失败: %w", err)
return
}
m.pw = pw
if err := m.detectBrowserFingerprint(); err != nil {
if // err 保存err,供当前处理流程使用
err := m.detectBrowserFingerprint(); err != nil {
m.initErr = fmt.Errorf("读取 Playwright Chromium 原生指纹失败: %w", err)
_ = pw.Stop()
m.pw = nil
@@ -223,10 +247,14 @@ func (m *Manager) init() error {
// Initialize starts Playwright and publishes the bundled Chromium's native
// browser identity before any non-browser client sends requests.
// Initialize 负责Initialize相关处理。
func (m *Manager) Initialize() error { return m.init() }
// detectBrowserFingerprint 负责detect浏览器Fingerprint相关处理。
func (m *Manager) detectBrowserFingerprint() error {
// observed 保存observed,供当前处理流程使用
observed := make(chan http.Header, 1)
// server 保存server,供当前处理流程使用
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
observed <- r.Header.Clone()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
@@ -234,6 +262,7 @@ func (m *Manager) detectBrowserFingerprint() error {
}))
defer server.Close()
// b、err 保存b、err,供当前处理流程使用
b, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(true),
Args: chromiumLaunchArgs(),
@@ -243,18 +272,22 @@ func (m *Manager) detectBrowserFingerprint() error {
return err
}
defer func() { _ = b.Close() }()
// ctx、err 保存ctx、err,供当前处理流程使用
ctx, err := b.NewContext()
if err != nil {
return err
}
defer func() { _ = ctx.Close() }()
// page、err 保存page、err,供当前处理流程使用
page, err := ctx.NewPage()
if err != nil {
return err
}
if _, err := page.Goto(server.URL, playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil {
if // err 保存err,供当前处理流程使用
_, err := page.Goto(server.URL, playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil {
return err
}
// headers 保存headers,供当前处理流程使用
var headers http.Header
select {
case headers = <-observed:
@@ -277,13 +310,16 @@ func (m *Manager) detectBrowserFingerprint() error {
// Close 释放所有浏览器与 playwright。
func (m *Manager) Close() error {
m.mu.Lock()
// entries 保存entries,供当前处理流程使用
entries := make([]*poolEntry, 0, len(m.pool))
// e 表示当前遍历过程中的e
for _, e := range m.pool {
entries = append(entries, e)
}
m.pool = make(map[string]*poolEntry)
m.mu.Unlock()
// e 表示当前遍历过程中的e
for _, e := range entries {
closeEntry(e, m.logger)
}
@@ -295,14 +331,18 @@ func (m *Manager) Close() error {
// newPage 从池中取(或创建)一个 context,返回新 page + 释放函数。
// 每次请求新建 page,避免并发导航冲突(与 browser_pool.get_browser 一致)。
// newPage 负责new页码相关处理。
func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headless bool) (playwright.Page, func(), error) {
if err := m.init(); err != nil {
if // err 保存err,供当前处理流程使用
err := m.init(); err != nil {
return nil, nil, err
}
// entry、err 保存entry、err,供当前处理流程使用
entry, err := m.acquireEntry(cookieID, cookieStr, headless)
if err != nil {
return nil, nil, err
}
// page、err 保存page、err,供当前处理流程使用
page, err := entry.context.NewPage()
if err != nil {
// context 损坏,丢弃重建一次。
@@ -319,6 +359,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
return nil, nil, fmt.Errorf("新建 page 失败: %w", err)
}
}
// release 保存release,供当前处理流程使用
release := func() {
_ = page.Close()
m.releaseEntry(cookieID, entry)
@@ -326,18 +367,22 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
return page, release, nil
}
// acquireEntry 负责acquireEntry相关处理。
func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
m.mu.Lock()
if e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
if // e、ok 保存e、ok,供当前处理流程使用
e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
m.claimEntryLocked(e)
m.mu.Unlock()
return e, nil
}
m.mu.Unlock()
// created、err 保存created、err,供当前处理流程使用
created, err, _ := m.creates.Do(cookieID, func() (any, error) {
m.mu.Lock()
if e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
if // e、ok 保存e、ok,供当前处理流程使用
e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
m.mu.Unlock()
return e, nil
}
@@ -349,12 +394,14 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
if err != nil {
return nil, err
}
// entry、ok 保存entry、ok,供当前处理流程使用
entry, ok := created.(*poolEntry)
if !ok || entry == nil {
return nil, fmt.Errorf("浏览器池创建返回异常")
}
m.mu.Lock()
if current := m.pool[cookieID]; current == entry {
if // current 保存current,供当前处理流程使用
current := m.pool[cookieID]; current == entry {
m.claimEntryLocked(entry)
m.mu.Unlock()
} else {
@@ -364,6 +411,7 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
return entry, nil
}
// claimEntryLocked 负责claimEntryLocked相关处理。
func (m *Manager) claimEntryLocked(entry *poolEntry) {
entry.lastUsed = time.Now()
if entry.initialLeaseAvailable {
@@ -373,10 +421,12 @@ func (m *Manager) claimEntryLocked(entry *poolEntry) {
entry.active++
}
// releaseEntry 负责releaseEntry相关处理。
func (m *Manager) releaseEntry(cookieID string, entry *poolEntry) {
m.mu.Lock()
defer m.mu.Unlock()
if current := m.pool[cookieID]; current != entry {
if // current 保存current,供当前处理流程使用
current := m.pool[cookieID]; current != entry {
return
}
if entry.active > 0 {
@@ -385,7 +435,9 @@ func (m *Manager) releaseEntry(cookieID string, entry *poolEntry) {
entry.lastUsed = time.Now()
}
// createEntry 负责createEntry相关处理。
func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
// browser、err 保存browser、err,供当前处理流程使用
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
@@ -394,6 +446,7 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
if err != nil {
return nil, fmt.Errorf("启动 chromium 失败: %w", err)
}
// context、err 保存context、err,供当前处理流程使用
context, err := browser.NewContext(playwright.BrowserNewContextOptions{
Viewport: &playwright.Size{Width: defaultW, Height: defaultH},
Locale: playwright.String(defaultLang),
@@ -403,16 +456,19 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
_ = browser.Close()
return nil, fmt.Errorf("创建 context 失败: %w", err)
}
if err := context.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
if // err 保存err,供当前处理流程使用
err := context.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
m.logger.Warn("注入 stealth 脚本失败", "err", err)
}
if cookieStr != "" {
if err := addCookieStr(context, cookieStr); err != nil {
if // err 保存err,供当前处理流程使用
err := addCookieStr(context, cookieStr); err != nil {
_ = context.Close()
_ = browser.Close()
return nil, fmt.Errorf("注入 cookie 失败: %w", err)
}
}
// entry 保存entry,供当前处理流程使用
entry := &poolEntry{
cookieID: cookieID,
browser: browser,
@@ -427,16 +483,20 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
return entry, nil
}
// touch 负责touch相关处理。
func (m *Manager) touch(cookieID string) {
m.mu.Lock()
if e, ok := m.pool[cookieID]; ok {
if // e、ok 保存e、ok,供当前处理流程使用
e, ok := m.pool[cookieID]; ok {
e.lastUsed = time.Now()
}
m.mu.Unlock()
}
// evict 负责evict相关处理。
func (m *Manager) evict(cookieID string) {
m.mu.Lock()
// e、ok 保存e、ok,供当前处理流程使用
e, ok := m.pool[cookieID]
if ok && e.active > 0 {
m.mu.Unlock()
@@ -449,14 +509,18 @@ func (m *Manager) evict(cookieID string) {
}
}
// evictIfNeeded 负责evictIfNeeded相关处理。
func (m *Manager) evictIfNeeded() {
m.mu.Lock()
if len(m.pool) < m.maxSize {
m.mu.Unlock()
return
}
// oldest 保存oldest,供当前处理流程使用
var oldest *poolEntry
// oldestID 保存oldestID,供当前处理流程使用
var oldestID string
// id、e 表示当前遍历过程中的id、e
for id, e := range m.pool {
if e.active > 0 {
continue
@@ -477,9 +541,12 @@ func (m *Manager) evictIfNeeded() {
// CleanupIdle 清理超过 idleTTL 未用的浏览器。
func (m *Manager) CleanupIdle() {
// now 保存now,供当前处理流程使用
now := time.Now()
m.mu.Lock()
// toClose 保存toClose,供当前处理流程使用
var toClose []*poolEntry
// id、e 表示当前遍历过程中的id、e
for id, e := range m.pool {
if e.active == 0 && now.Sub(e.lastUsed) > m.idleTTL {
toClose = append(toClose, e)
@@ -487,11 +554,13 @@ func (m *Manager) CleanupIdle() {
}
}
m.mu.Unlock()
// e 表示当前遍历过程中的e
for _, e := range toClose {
closeEntry(e, m.logger)
}
}
// closeEntry 负责closeEntry相关处理。
func closeEntry(e *poolEntry, logger *slog.Logger) {
if e == nil {
return
@@ -506,11 +575,13 @@ func closeEntry(e *poolEntry, logger *slog.Logger) {
// addCookieStr 把 "k=v; k2=v2" 注入 context(domain .goofish.com)。
func addCookieStr(ctx playwright.BrowserContext, cookieStr string) error {
// cookies 保存cookies,供当前处理流程使用
cookies := parseCookieStrToPlaywright(cookieStr)
if len(cookies) == 0 {
return errors.New("cookie 为空或格式错误")
}
if err := ctx.ClearCookies(); err != nil {
if // err 保存err,供当前处理流程使用
err := ctx.ClearCookies(); err != nil {
return fmt.Errorf("清理浏览器旧 cookie: %w", err)
}
return ctx.AddCookies(cookies)
+64 -16
View File
@@ -12,13 +12,18 @@ import (
// TestChromiumLaunchArgs 验证启动参数含关键安全/反检测项。
func TestChromiumLaunchArgs(t *testing.T) {
// args 保存args,供当前处理流程使用
args := chromiumLaunchArgs()
if len(args) == 0 {
t.Fatal("应返回非空参数列表")
}
// want 保存want,供当前处理流程使用
want := []string{"--no-sandbox", "--disable-dev-shm-usage", "--disable-blink-features=AutomationControlled", "--lang=zh-CN"}
// w 表示当前遍历过程中的w
for _, w := range want {
// found 保存found,供当前处理流程使用
found := false
// a 表示当前遍历过程中的a
for _, a := range args {
if a == w {
found = true
@@ -31,25 +36,34 @@ func TestChromiumLaunchArgs(t *testing.T) {
}
}
// TestPackagedPlaywrightRuntimeReady 负责TestPackagedPlaywrightRuntimeReady相关处理。
func TestPackagedPlaywrightRuntimeReady(t *testing.T) {
// runtimeRoot 保存runtimeRoot,供当前处理流程使用
runtimeRoot := t.TempDir()
// driverDir 保存driverDir,供当前处理流程使用
driverDir := filepath.Join(runtimeRoot, "driver")
// browserDir 保存浏览器Dir,供当前处理流程使用
browserDir := filepath.Join(runtimeRoot, "browsers")
if err := os.MkdirAll(filepath.Join(driverDir, "package"), 0o755); err != nil {
if // err 保存err,供当前处理流程使用
err := os.MkdirAll(filepath.Join(driverDir, "package"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(browserDir, "chromium-1228"), 0o755); err != nil {
if // err 保存err,供当前处理流程使用
err := os.MkdirAll(filepath.Join(browserDir, "chromium-1228"), 0o755); err != nil {
t.Fatal(err)
}
// nodeName 保存node名称,供当前处理流程使用
nodeName := "node"
if runtime.GOOS == "windows" {
nodeName = "node.exe"
}
// path 表示当前遍历过程中的路径
for _, path := range []string{
filepath.Join(driverDir, nodeName),
filepath.Join(driverDir, "package", "cli.js"),
} {
if err := os.WriteFile(path, []byte("runtime"), 0o755); err != nil {
if // err 保存err,供当前处理流程使用
err := os.WriteFile(path, []byte("runtime"), 0o755); err != nil {
t.Fatal(err)
}
}
@@ -61,21 +75,30 @@ func TestPackagedPlaywrightRuntimeReady(t *testing.T) {
}
}
// TestPackagedPlaywrightRuntimeReadyWithExternalNode 负责TestPackagedPlaywrightRuntimeReadyWithExternalNode相关处理。
func TestPackagedPlaywrightRuntimeReadyWithExternalNode(t *testing.T) {
// runtimeRoot 保存runtimeRoot,供当前处理流程使用
runtimeRoot := t.TempDir()
// driverDir 保存driverDir,供当前处理流程使用
driverDir := filepath.Join(runtimeRoot, "driver")
// browserDir 保存浏览器Dir,供当前处理流程使用
browserDir := filepath.Join(runtimeRoot, "browsers")
if err := os.MkdirAll(filepath.Join(driverDir, "package"), 0o755); err != nil {
if // err 保存err,供当前处理流程使用
err := os.MkdirAll(filepath.Join(driverDir, "package"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(browserDir, "chromium-1228"), 0o755); err != nil {
if // err 保存err,供当前处理流程使用
err := os.MkdirAll(filepath.Join(browserDir, "chromium-1228"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(driverDir, "package", "cli.js"), []byte("runtime"), 0o644); err != nil {
if // err 保存err,供当前处理流程使用
err := os.WriteFile(filepath.Join(driverDir, "package", "cli.js"), []byte("runtime"), 0o644); err != nil {
t.Fatal(err)
}
// nodePath 保存node路径,供当前处理流程使用
nodePath := filepath.Join(runtimeRoot, "node")
if err := os.WriteFile(nodePath, []byte("runtime"), 0o755); err != nil {
if // err 保存err,供当前处理流程使用
err := os.WriteFile(nodePath, []byte("runtime"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PLAYWRIGHT_DRIVER_PATH", driverDir)
@@ -99,7 +122,9 @@ func newTestManager(maxSize int) *Manager {
// TestTouchUpdatesLastUsed touch 命中池中条目时更新 lastUsed。
func TestTouchUpdatesLastUsed(t *testing.T) {
// m 保存m,供当前处理流程使用
m := newTestManager(3)
// old 保存old,供当前处理流程使用
old := time.Now().Add(-time.Hour)
m.pool["c1"] = &poolEntry{cookieID: "c1", lastUsed: old}
m.touch("c1")
@@ -112,14 +137,17 @@ func TestTouchUpdatesLastUsed(t *testing.T) {
// TestEvictRemovesEntry evict 删除指定条目(nil browser 时 closeEntry 为 no-op)。
func TestEvictRemovesEntry(t *testing.T) {
// m 保存m,供当前处理流程使用
m := newTestManager(3)
m.pool["c1"] = &poolEntry{cookieID: "c1"}
m.pool["c2"] = &poolEntry{cookieID: "c2"}
m.evict("c1")
if _, ok := m.pool["c1"]; ok {
if // ok 保存ok,供当前处理流程使用
_, ok := m.pool["c1"]; ok {
t.Fatal("evict 应删除 c1")
}
if _, ok := m.pool["c2"]; !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := m.pool["c2"]; !ok {
t.Fatal("c2 应保留")
}
// evict 不存在的条目不 panic。
@@ -128,6 +156,7 @@ func TestEvictRemovesEntry(t *testing.T) {
// TestEvictIfNeededEvictsOldest 池满时驱逐最久未用的条目。
func TestEvictIfNeededEvictsOldest(t *testing.T) {
// m 保存m,供当前处理流程使用
m := newTestManager(2)
m.pool["c1"] = &poolEntry{cookieID: "c1", lastUsed: time.Now().Add(-2 * time.Hour)}
m.pool["c2"] = &poolEntry{cookieID: "c2", lastUsed: time.Now()}
@@ -135,35 +164,44 @@ func TestEvictIfNeededEvictsOldest(t *testing.T) {
if _, ok := m.pool["c1"]; ok {
t.Fatal("应驱逐最旧的 c1")
}
if _, ok := m.pool["c2"]; !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := m.pool["c2"]; !ok {
t.Fatal("c2 应保留")
}
}
// TestEvictIfNeededNoopWhenUnderLimit 池未满时不驱逐。
func TestEvictIfNeededNoopWhenUnderLimit(t *testing.T) {
// m 保存m,供当前处理流程使用
m := newTestManager(5)
m.pool["c1"] = &poolEntry{cookieID: "c1", lastUsed: time.Now()}
m.evictIfNeeded()
if _, ok := m.pool["c1"]; !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := m.pool["c1"]; !ok {
t.Fatal("未满不应驱逐")
}
}
// TestEvictIfNeededSkipsActiveEntries 负责TestEvictIfNeededSkipsActiveEntries相关处理。
func TestEvictIfNeededSkipsActiveEntries(t *testing.T) {
// m 保存m,供当前处理流程使用
m := newTestManager(2)
m.pool["active-old"] = &poolEntry{cookieID: "active-old", lastUsed: time.Now().Add(-2 * time.Hour), active: 1}
m.pool["idle-new"] = &poolEntry{cookieID: "idle-new", lastUsed: time.Now()}
m.evictIfNeeded()
if _, ok := m.pool["active-old"]; !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := m.pool["active-old"]; !ok {
t.Fatal("正在执行 token 请求的条目不得被淘汰")
}
if _, ok := m.pool["idle-new"]; ok {
if // ok 保存ok,供当前处理流程使用
_, ok := m.pool["idle-new"]; ok {
t.Fatal("池满时应优先淘汰空闲条目")
}
}
// TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive 负责TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive相关处理。
func TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive(t *testing.T) {
// m 保存m,供当前处理流程使用
m := newTestManager(2)
m.pool["active-1"] = &poolEntry{cookieID: "active-1", lastUsed: time.Now().Add(-2 * time.Hour), active: 1}
m.pool["active-2"] = &poolEntry{cookieID: "active-2", lastUsed: time.Now().Add(-time.Hour), active: 1}
@@ -173,23 +211,29 @@ func TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive(t *testing.T) {
}
}
// TestCleanupIdleSkipsActiveEntries 负责TestCleanupIdleSkipsActiveEntries相关处理。
func TestCleanupIdleSkipsActiveEntries(t *testing.T) {
// m 保存m,供当前处理流程使用
m := newTestManager(3)
m.idleTTL = time.Minute
// old 保存old,供当前处理流程使用
old := time.Now().Add(-time.Hour)
m.pool["active"] = &poolEntry{cookieID: "active", lastUsed: old, active: 1}
m.pool["idle"] = &poolEntry{cookieID: "idle", lastUsed: old}
m.CleanupIdle()
if _, ok := m.pool["active"]; !ok {
if // ok 保存ok,供当前处理流程使用
_, ok := m.pool["active"]; !ok {
t.Fatal("CleanupIdle 不得关闭仍有租约的条目")
}
if _, ok := m.pool["idle"]; ok {
if // ok 保存ok,供当前处理流程使用
_, ok := m.pool["idle"]; ok {
t.Fatal("CleanupIdle 应清理过期空闲条目")
}
}
// TestMarshalCookies 导出包装器等价 cookieMarshal。
func TestMarshalCookies(t *testing.T) {
// got 保存got,供当前处理流程使用
got := MarshalCookies(map[string]string{"unb": "1", "cna": "xx"})
// map 顺序不保证,逐项检查。
if !contains(got, "unb=1") || !contains(got, "cna=xx") {
@@ -199,10 +243,12 @@ func TestMarshalCookies(t *testing.T) {
// TestCookiesToMap playwright.Cookie 切片转 map。
func TestCookiesToMap(t *testing.T) {
// cs 保存cs,供当前处理流程使用
cs := []playwright.Cookie{
{Name: "unb", Value: "123"},
{Name: "_m_h5_tk", Value: "tok"},
}
// m 保存m,供当前处理流程使用
m := cookiesToMap(cs)
if m["unb"] != "123" || m["_m_h5_tk"] != "tok" || len(m) != 2 {
t.Fatalf("cookiesToMap=%+v", m)
@@ -213,8 +259,10 @@ func TestCookiesToMap(t *testing.T) {
}
}
// contains 负责contains相关处理。
func contains(s, sub string) bool {
for i := 0; i+len(sub) <= len(s); i++ {
for // i 保存i,供当前处理流程使用
i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
+84 -18
View File
@@ -15,6 +15,7 @@ import (
"xianyu-go/internal/xianyu/mtop"
)
// mtopOrderDetailURL 保存mtop订单DetailURL,供当前处理流程使用
const mtopOrderDetailURL = "mtop.idle.web.trade.order.detail"
// OrderDetail 订单详情(对齐 engine.OrderDetail)。
@@ -39,7 +40,9 @@ var orderStatusMap = map[int]string{
// FetchOrderDetail 用浏览器抓取单个订单详情。
// 移植自 utils/order_fetcher_optimized.py fetch_order_complete。
// FetchOrderDetail 负责Fetch订单Detail相关处理。
func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cookieValue string, requireSpec ...bool) (*OrderDetail, error) {
// needsSpec 保存needsSpec,供当前处理流程使用
needsSpec := len(requireSpec) > 0 && requireSpec[0]
// 优先调用稳定的 MTop 详情接口;页面自动化只作为规格字段的兼容兜底。
if direct, directErr := mtop.NewClient().FetchOrderDetail(ctx, cookieValue, orderID); directErr == nil && direct != nil && direct.Amount != "" &&
@@ -54,33 +57,45 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
// A shared Chromium context owns one mutable Cookie Jar. Serialize browser
// fallback refreshes for the account so concurrent batch rows cannot clear
// and re-inject different snapshots underneath each other.
// browserCredentialLock 保存浏览器Credential锁,供当前处理流程使用
browserCredentialLock := m.accountRenewLock("order_credential_" + cookieID)
browserCredentialLock.Lock()
defer browserCredentialLock.Unlock()
if err := m.init(); err != nil {
if // err 保存err,供当前处理流程使用
err := m.init(); err != nil {
return nil, err
}
// page、release、err 保存page、release、err,供当前处理流程使用
page, release, err := m.newPage(ctx, cookieID, cookieValue, true)
if err != nil {
return nil, err
}
defer release()
if session := mtop.CookieSessionFromContext(ctx); session != nil {
if err := syncCredentialCookies(page.Context(), cookieValue, session.Snapshot()); err != nil {
if // session 保存会话,供当前处理流程使用
session := mtop.CookieSessionFromContext(ctx); session != nil {
if // err 保存err,供当前处理流程使用
err := syncCredentialCookies(page.Context(), cookieValue, session.Snapshot()); err != nil {
return nil, fmt.Errorf("订单详情同步完整 Cookie Jar: %w", err)
}
}
// mu 保存mu,供当前处理流程使用
var mu sync.Mutex
// apiBody 保存api请求体,供当前处理流程使用
var apiBody map[string]any
// observedAPIs 保存observedAPIs,供当前处理流程使用
var observedAPIs []string
// 路由拦截:fetch mtop 订单详情 API 响应体。
_ = page.Route("**/*", func(route playwright.Route) {
// requestURL 保存请求URL,供当前处理流程使用
requestURL := route.Request().URL()
if parsed, parseErr := url.Parse(requestURL); parseErr == nil && strings.Contains(parsed.Host, "goofish.com") {
if // parsed、parseErr 保存parsed、parseErr,供当前处理流程使用
parsed, parseErr := url.Parse(requestURL); parseErr == nil && strings.Contains(parsed.Host, "goofish.com") {
// apiName 保存api名称,供当前处理流程使用
apiName := parsed.Query().Get("api")
if apiName == "" && strings.Contains(parsed.Path, "/h5/") {
// parts 保存parts,供当前处理流程使用
parts := strings.Split(parsed.Path, "/")
if len(parts) > 2 {
apiName = parts[2]
@@ -95,10 +110,13 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
}
}
if strings.Contains(requestURL, mtopOrderDetailURL) {
// resp、err 保存resp、err,供当前处理流程使用
resp, err := route.Fetch()
if err == nil {
// body 保存请求体,供当前处理流程使用
var body map[string]any
if err := resp.JSON(&body); err == nil {
if // err 保存err,供当前处理流程使用
err := resp.JSON(&body); err == nil {
mu.Lock()
apiBody = body
mu.Unlock()
@@ -108,8 +126,10 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
_ = route.Continue()
})
// url 保存地址,供当前处理流程使用
url := fmt.Sprintf("https://www.goofish.com/order-detail?orderId=%s&role=seller", orderID)
if _, err := page.Goto(url, playwright.PageGotoOptions{
if // err 保存err,供当前处理流程使用
_, err := page.Goto(url, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateNetworkidle,
Timeout: playwright.Float(30000),
}); err != nil {
@@ -122,19 +142,23 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
time.Sleep(1 * time.Second)
mu.Lock()
// body 保存请求体,供当前处理流程使用
body := apiBody
mu.Unlock()
// od 保存od,供当前处理流程使用
od := &OrderDetail{OrderID: orderID}
if body != nil {
if d, ok := body["data"].(map[string]any); ok {
if // d、ok 保存d、ok,供当前处理流程使用
d, ok := body["data"].(map[string]any); ok {
parseAPIResponse(od, d)
}
}
// DOM 补充(金额 / SKU)。
parseDOMContent(page, od)
// allCookies、cookieErr 保存allCookies、cookieErr,供当前处理流程使用
allCookies, cookieErr := page.Context().Cookies()
if cookieErr != nil {
return nil, fmt.Errorf("读取订单详情浏览器 Cookie Jar: %w", cookieErr)
@@ -145,28 +169,35 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
}
od.CookieSnapshotComplete = true
od.UpdatedCookies = currentCookieHeader(od.CookieSnapshot, goofishIMURL)
if session := mtop.CookieSessionFromContext(ctx); session != nil {
if // session 保存会话,供当前处理流程使用
session := mtop.CookieSessionFromContext(ctx); session != nil {
session.ReplaceSnapshot(od.CookieSnapshot)
}
if od.Amount == "" {
// title 保存标题,供当前处理流程使用
title, _ := page.Title()
m.logger.Warn("订单详情未解析到实付金额", "order_id", orderID, "page_title", title, "page_url", page.URL(), "api_captured", body != nil, "observed_apis", observedAPIs)
}
return od, nil
}
// parseAPIResponse 负责parseAPI响应相关处理。
func parseAPIResponse(od *OrderDetail, data map[string]any) {
// 订单状态。
if ut, ok := data["utArgs"].(map[string]any); ok {
if code, ok := ut["orderStatus"].(float64); ok {
if s, ok := orderStatusMap[int(code)]; ok {
if // code、ok 保存code、ok,供当前处理流程使用
code, ok := ut["orderStatus"].(float64); ok {
if // s、ok 保存s、ok,供当前处理流程使用
s, ok := orderStatusMap[int(code)]; ok {
od.OrderStatus = s
}
}
}
// 组件中找金额和规格。
comps, _ := data["components"].([]any)
// c 表示当前遍历过程中的c
for _, c := range comps {
// cm、ok 保存cm、ok,供当前处理流程使用
cm, ok := c.(map[string]any)
if !ok {
continue
@@ -174,13 +205,16 @@ func parseAPIResponse(od *OrderDetail, data map[string]any) {
if cm["render"] == "orderInfoVO" {
// 当前接口把 priceInfo 放在 component.data 下;兼容旧结构的顶层字段。
componentData, _ := cm["data"].(map[string]any)
// priceInfo 保存priceInfo,供当前处理流程使用
priceInfo, _ := componentData["priceInfo"].(map[string]any)
if priceInfo == nil {
priceInfo, _ = cm["priceInfo"].(map[string]any)
}
if priceInfo != nil {
// amount 保存amount,供当前处理流程使用
amount, _ := priceInfo["amount"].(map[string]any)
if v, ok := amount["value"].(string); ok {
if // v、ok 保存v、ok,供当前处理流程使用
v, ok := amount["value"].(string); ok {
od.Amount = v
}
}
@@ -188,21 +222,29 @@ func parseAPIResponse(od *OrderDetail, data map[string]any) {
}
}
// currencyAmountRE 保存currencyAmountRE,供当前处理流程使用
var currencyAmountRE = regexp.MustCompile(`[¥¥]\s*([0-9]+(?:\.[0-9]{1,2})?)`)
// plainAmountRE 保存plainAmountRE,供当前处理流程使用
var plainAmountRE = regexp.MustCompile(`^\s*([0-9]+(?:\.[0-9]{1,2})?)\s*$`)
// parseDOMContent 负责parseDOM内容相关处理。
func parseDOMContent(page playwright.Page, od *OrderDetail) {
// 金额。
if od.Amount == "" {
if el, err := page.QuerySelector(`.boldNum--JgEOXfA3`); err == nil && el != nil {
if t, err := el.TextContent(); err == nil {
if // el、err 保存el、err,供当前处理流程使用
el, err := page.QuerySelector(`.boldNum--JgEOXfA3`); err == nil && el != nil {
if // t、err 保存t、err,供当前处理流程使用
t, err := el.TextContent(); err == nil {
od.Amount = strings.TrimSpace(t)
}
}
}
if od.Amount == "" {
if raw, err := page.Evaluate(`() => document.body?.innerText || ''`); err == nil {
if pageText, ok := raw.(string); ok {
if // raw、err 保存raw、err,供当前处理流程使用
raw, err := page.Evaluate(`() => document.body?.innerText || ''`); err == nil {
if // pageText、ok 保存页码Text、ok,供当前处理流程使用
pageText, ok := raw.(string); ok {
od.Amount = extractPaidAmountFromText(pageText)
}
}
@@ -210,13 +252,16 @@ func parseDOMContent(page playwright.Page, od *OrderDetail) {
// SKU(规格+数量)。移植自 _parse_dom_content。
if skuEls, err := page.QuerySelectorAll(`.sku--u_ddZval`); err == nil && len(skuEls) >= 1 {
// t 保存t,供当前处理流程使用
t, _ := skuEls[0].TextContent()
// parts 保存parts,供当前处理流程使用
parts := strings.SplitN(t, ":", 2)
if len(parts) == 2 {
od.SpecName = strings.TrimSpace(parts[0])
od.SpecValue = strings.TrimSpace(parts[1])
}
if len(skuEls) >= 2 {
// q 保存q,供当前处理流程使用
q, _ := skuEls[1].TextContent()
od.Quantity = strings.TrimPrefix(strings.TrimSpace(q), "x")
}
@@ -226,17 +271,26 @@ func parseDOMContent(page playwright.Page, od *OrderDetail) {
}
}
// extractPaidAmountFromText 负责extractPaidAmountFrom文本相关处理。
func extractPaidAmountFromText(pageText string) string {
// labels 保存labels,供当前处理流程使用
labels := []string{"实付款", "实付金额", "订单金额", "合计"}
// rawLines 保存原始Lines,供当前处理流程使用
rawLines := strings.Split(pageText, "\n")
// lines 保存lines,供当前处理流程使用
lines := make([]string, 0, len(rawLines))
// line 表示当前遍历过程中的line
for _, line := range rawLines {
if trimmed := strings.TrimSpace(line); trimmed != "" {
if // trimmed 保存trimmed,供当前处理流程使用
trimmed := strings.TrimSpace(line); trimmed != "" {
lines = append(lines, trimmed)
}
}
// i、line 表示当前遍历过程中的i、line
for i, line := range lines {
// matchedLabel 保存matchedLabel,供当前处理流程使用
matchedLabel := false
// label 表示当前遍历过程中的label
for _, label := range labels {
if strings.Contains(line, label) {
matchedLabel = true
@@ -246,16 +300,20 @@ func extractPaidAmountFromText(pageText string) string {
if !matchedLabel {
continue
}
// end 保存结束,供当前处理流程使用
end := i + 3
if end > len(lines) {
end = len(lines)
}
// candidate 表示当前遍历过程中的candidate
for _, candidate := range lines[i:end] {
if match := currencyAmountRE.FindStringSubmatch(candidate); len(match) == 2 {
if // match 保存match,供当前处理流程使用
match := currencyAmountRE.FindStringSubmatch(candidate); len(match) == 2 {
return match[1]
}
if candidate != line {
if match := plainAmountRE.FindStringSubmatch(candidate); len(match) == 2 {
if // match 保存match,供当前处理流程使用
match := plainAmountRE.FindStringSubmatch(candidate); len(match) == 2 {
return match[1]
}
}
@@ -266,27 +324,35 @@ func extractPaidAmountFromText(pageText string) string {
// BatchRefreshOrders 并发抓取多个订单详情(semaphore=5)。
func (m *Manager) BatchRefreshOrders(ctx context.Context, orderIDs []string, cookieID, cookieValue string) (map[string]any, error) {
// sem 保存sem,供当前处理流程使用
sem := make(chan struct{}, 5)
// result 保存结果,供当前处理流程使用
type result struct {
id string
od *OrderDetail
err error
}
// results 保存results,供当前处理流程使用
results := make([]result, len(orderIDs))
// wg 保存wg,供当前处理流程使用
var wg sync.WaitGroup
// i、id 表示当前遍历过程中的i、id
for i, id := range orderIDs {
wg.Add(1)
go func(idx int, oid string) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
// od、err 保存od、err,供当前处理流程使用
od, err := m.FetchOrderDetail(ctx, oid, cookieID, cookieValue)
results[idx] = result{id: oid, od: od, err: err}
}(i, id)
}
wg.Wait()
// orders 保存订单列表,供当前处理流程使用
orders := make([]map[string]any, 0, len(orderIDs))
// r 表示当前遍历过程中的r
for _, r := range results {
if r.err != nil {
orders = append(orders, map[string]any{"order_id": r.id, "success": false, "error": r.err.Error()})
+16 -2
View File
@@ -4,7 +4,9 @@ import (
"testing"
)
// TestOrderStatusMap 负责Test订单状态Map相关处理。
func TestOrderStatusMap(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := []struct {
code int
expect string
@@ -13,15 +15,20 @@ func TestOrderStatusMap(t *testing.T) {
{4, "completed"}, {7, "refunding"}, {8, "cancelled"},
{9, "refunding"}, {10, "cancelled"}, {11, "completed"}, {12, "cancelled"},
}
// c 表示当前遍历过程中的c
for _, c := range cases {
if s, ok := orderStatusMap[c.code]; !ok || s != c.expect {
if // s、ok 保存s、ok,供当前处理流程使用
s, ok := orderStatusMap[c.code]; !ok || s != c.expect {
t.Errorf("orderStatusMap[%d] = %q, want %q", c.code, s, c.expect)
}
}
}
// TestParseAPIResponseStatusCode 负责TestParseAPI响应状态Code相关处理。
func TestParseAPIResponseStatusCode(t *testing.T) {
// od 保存od,供当前处理流程使用
od := &OrderDetail{}
// data 保存数据,供当前处理流程使用
data := map[string]any{
"utArgs": map[string]any{"orderStatus": float64(2)},
}
@@ -31,8 +38,11 @@ func TestParseAPIResponseStatusCode(t *testing.T) {
}
}
// TestParseAPIResponseAmountFromComponentData 负责TestParseAPI响应AmountFromComponent数据相关处理。
func TestParseAPIResponseAmountFromComponentData(t *testing.T) {
// od 保存od,供当前处理流程使用
od := &OrderDetail{}
// data 保存数据,供当前处理流程使用
data := map[string]any{
"components": []any{
map[string]any{
@@ -51,15 +61,19 @@ func TestParseAPIResponseAmountFromComponentData(t *testing.T) {
}
}
// TestExtractPaidAmountFromText 负责TestExtractPaidAmountFrom文本相关处理。
func TestExtractPaidAmountFromText(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]string{
"商品标价\n¥99.00\n实付款 ¥0.88\n交易成功": "0.88",
"订单信息\n实付金额\n¥12.50\n订单编号": "12.50",
"合计\n6.00\n其他信息": "6.00",
"商品价格\n¥19.90\n没有付款标签": "",
}
// input、want 表示当前遍历过程中的input、want
for input, want := range cases {
if got := extractPaidAmountFromText(input); got != want {
if // got 保存got,供当前处理流程使用
got := extractPaidAmountFromText(input); got != want {
t.Errorf("extractPaidAmountFromText(%q)=%q want %q", input, got, want)
}
}
+97 -19
View File
@@ -17,16 +17,23 @@ var loginIDSelectors = []string{
`input[placeholder*="手机号"]`, `input[placeholder*="邮箱"]`,
".fm-login-id",
}
// loginPwdSelectors 保存登录PwdSelectors,供当前处理流程使用
var loginPwdSelectors = []string{
"#fm-login-password", `input[type="password"]`,
}
// loginBtnSelectors 保存登录BtnSelectors,供当前处理流程使用
var loginBtnSelectors = []string{
"button.password-login", `button[type="submit"]`,
}
// loginSuccessSelectors 保存登录SuccessSelectors,供当前处理流程使用
var loginSuccessSelectors = []string{
".rc-virtual-list-holder-inner", // IM 页面侧边栏有子元素则已登录
}
// passwordVerificationWaitInterval 保存密码VerificationWaitInterval,供当前处理流程使用
const (
passwordVerificationWaitInterval = 10 * time.Second
passwordVerificationMaxWait = 5 * time.Minute
@@ -39,6 +46,7 @@ const (
// PasswordLogin 用账号密码通过浏览器登录闲鱼,返回完整 cookie map。
// 移植自 xianyu_slider_stealth.login_with_password_playwright。
// userDataDir:空字符串使用按账号划分的默认持久化目录。
// PasswordLogin 负责密码登录相关处理。
func (m *Manager) PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error) {
return m.passwordLogin(ctx, account, password, cookieID, userDataDir, headless, nil)
}
@@ -48,6 +56,7 @@ func (m *Manager) PasswordLoginWithEvents(ctx context.Context, account, password
return m.passwordLogin(ctx, account, password, cookieID, userDataDir, headless, onEvent)
}
// passwordLogin 负责密码登录相关处理。
func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent PasswordLoginEventHandler) (map[string]string, error) {
if strings.TrimSpace(account) == "" || strings.TrimSpace(password) == "" {
return nil, fmt.Errorf("账号或密码不能为空")
@@ -58,18 +67,21 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
}
headless = quickRenewHeadless(headless)
// bctx、release、err 保存bctx、release、err,供当前处理流程使用
bctx, release, err := m.newPersistentPasswordContext(ctx, cookieID, userDataDir, headless)
if err != nil {
return nil, err
}
defer release()
// page、err 保存page、err,供当前处理流程使用
page, err := bctx.NewPage()
if err != nil {
return nil, fmt.Errorf("新建 page 失败: %w", err)
}
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
if // err 保存err,供当前处理流程使用
_, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(30000),
}); err != nil {
@@ -80,13 +92,15 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
if clickQuickEnter(page) {
m.logger.Info("密码登录:已点击[快速进入],等待页面刷新", "cookieID", cookieID)
time.Sleep(quickRenewAfterClick)
// cookies、err 保存cookies、err,供当前处理流程使用
cookies, err := extractPageCookies(page)
if err == nil && quickEnterCookiesUsable(cookies) {
m.logger.Info("密码登录:快速进入成功,跳过账号密码输入", "cookieID", cookieID)
return cookies, nil
}
m.logger.Info("密码登录:快速进入未获取到有效 Cookie,继续账号密码登录", "cookieID", cookieID)
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
if // err 保存err,供当前处理流程使用
_, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(30000),
}); err != nil {
@@ -103,7 +117,8 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
idEl, pwdEl, submitEl := findLoginForm(page)
if idEl == nil {
time.Sleep(2 * time.Second)
if handled := detectAndHandlePasswordSlider(page, m.logger); handled {
if // handled 保存handled,供当前处理流程使用
handled := detectAndHandlePasswordSlider(page, m.logger); handled {
m.logger.Info("密码登录:未找到表单时已处理滑块", "cookieID", cookieID)
}
time.Sleep(3 * time.Second)
@@ -123,8 +138,10 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
time.Sleep(secondsDuration(randomFloat(0.5, 1.0)))
// 同意协议复选框(若存在)。
if cb := findPasswordElement(page, []string{"#fm-agreement-checkbox"}); cb != nil {
// checked 保存checked,供当前处理流程使用
checked, _ := cb.Evaluate(`el => Boolean(el.checked)`)
if isChecked, _ := checked.(bool); !isChecked {
if // isChecked 保存isChecked,供当前处理流程使用
isChecked, _ := checked.(bool); !isChecked {
_ = cb.Click()
time.Sleep(300 * time.Millisecond)
}
@@ -154,34 +171,44 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
return extractPageCookies(page)
}
// findPasswordElement 负责find密码Element相关处理。
func findPasswordElement(page playwright.Page, selectors []string) playwright.ElementHandle {
// frames 保存frames,供当前处理流程使用
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
// frame 表示当前遍历过程中的frame
for _, frame := range frames {
if el := queryFirst(frame, selectors); el != nil {
if // el 保存el,供当前处理流程使用
el := queryFirst(frame, selectors); el != nil {
return el
}
}
return nil
}
// clickPasswordLoginTab 负责click密码登录Tab相关处理。
func clickPasswordLoginTab(page playwright.Page) bool {
// el 保存el,供当前处理流程使用
el := findPasswordElement(page, []string{"a.password-login-tab-item"})
return el != nil && el.Click() == nil
}
// detectAndHandlePasswordSlider 负责detectAndHandle密码Slider相关处理。
func detectAndHandlePasswordSlider(page playwright.Page, logger sliderLogger) bool {
// content 保存内容,供当前处理流程使用
content, _ := page.Content()
if !strings.Contains(content, "nc-container") && !strings.Contains(content, "scratch-captcha") {
// 参考实现把“未发现滑块”也视为检测流程成功;调用方据此保持相同的等待节奏。
return true
}
if err := solveSlider(page, isScratchCaptcha(content), logger); err != nil {
if // err 保存err,供当前处理流程使用
err := solveSlider(page, isScratchCaptcha(content), logger); err != nil {
logger.Warn("密码登录滑块处理失败", "err", err)
return false
}
return true
}
// quickEnterCookiesUsable 负责quickEnterCookiesUsable相关处理。
func quickEnterCookiesUsable(cookies map[string]string) bool {
if len(cookies) == 0 {
return false
@@ -189,23 +216,28 @@ func quickEnterCookiesUsable(cookies map[string]string) bool {
return strings.TrimSpace(cookies["unb"]) != ""
}
// handlePasswordLoginPending 负责handle密码登录Pending相关处理。
func (m *Manager) handlePasswordLoginPending(ctx context.Context, page playwright.Page, onEvent PasswordLoginEventHandler) (map[string]string, error) {
if msg := passwordLoginErrorFromPage(page); msg != "" {
if // msg 保存msg,供当前处理流程使用
msg := passwordLoginErrorFromPage(page); msg != "" {
if onEvent != nil {
onEvent(PasswordLoginEventFromMessage(msg))
}
return nil, fmt.Errorf("密码登录失败: %s", msg)
}
if event, ok := passwordBaxiaEventFromPage(page); ok {
if // event、ok 保存event、ok,供当前处理流程使用
event, ok := passwordBaxiaEventFromPage(page); ok {
if onEvent != nil {
onEvent(event)
}
return nil, fmt.Errorf("密码登录失败: %s", event.Message)
}
if event, ok := passwordVerificationEventFromPage(page); ok {
if // event、ok 保存event、ok,供当前处理流程使用
event, ok := passwordVerificationEventFromPage(page); ok {
if onEvent != nil {
onEvent(event)
}
// cookies、err 保存cookies、err,供当前处理流程使用
cookies, err := waitPasswordVerification(ctx, page, onEvent)
if err == nil {
m.logger.Info("密码登录人工验证完成")
@@ -213,6 +245,7 @@ func (m *Manager) handlePasswordLoginPending(ctx context.Context, page playwrigh
}
return nil, err
}
// errMsg 保存errMsg,供当前处理流程使用
errMsg := "登录失败"
if onEvent != nil {
onEvent(PasswordLoginEventFromMessage(errMsg))
@@ -220,9 +253,12 @@ func (m *Manager) handlePasswordLoginPending(ctx context.Context, page playwrigh
return nil, fmt.Errorf("密码登录失败: %s", errMsg)
}
// waitPasswordVerification 负责wait密码Verification相关处理。
func waitPasswordVerification(ctx context.Context, page playwright.Page, onEvent PasswordLoginEventHandler) (map[string]string, error) {
// ticker 保存ticker,供当前处理流程使用
ticker := time.NewTicker(passwordVerificationWaitInterval)
defer ticker.Stop()
// timer 保存定时器,供当前处理流程使用
timer := time.NewTimer(passwordVerificationMaxWait)
defer timer.Stop()
for {
@@ -236,48 +272,63 @@ func waitPasswordVerification(ctx context.Context, page playwright.Page, onEvent
if checkLoginSuccess(page) {
return extractPageCookies(page)
}
if msg := passwordLoginErrorFromPage(page); msg != "" {
if // msg 保存msg,供当前处理流程使用
msg := passwordLoginErrorFromPage(page); msg != "" {
return nil, fmt.Errorf("密码登录失败: %s", msg)
}
if event, ok := passwordBaxiaEventFromPage(page); ok {
if // event、ok 保存event、ok,供当前处理流程使用
event, ok := passwordBaxiaEventFromPage(page); ok {
return nil, fmt.Errorf("密码登录失败: %s", event.Message)
}
if event, ok := passwordVerificationEventFromPage(page); ok && onEvent != nil {
if // event、ok 保存event、ok,供当前处理流程使用
event, ok := passwordVerificationEventFromPage(page); ok && onEvent != nil {
onEvent(event)
}
}
}
// passwordLoginErrorFromPage 负责密码登录错误From页码相关处理。
func passwordLoginErrorFromPage(page playwright.Page) string {
if el, err := page.QuerySelector(".login-error-msg"); err == nil && el != nil {
if msg, _ := el.TextContent(); strings.TrimSpace(msg) != "" {
if // el、err 保存el、err,供当前处理流程使用
el, err := page.QuerySelector(".login-error-msg"); err == nil && el != nil {
if // msg 保存msg,供当前处理流程使用
msg, _ := el.TextContent(); strings.TrimSpace(msg) != "" {
return strings.TrimSpace(msg)
}
}
// htmlText 表示当前遍历过程中的html文本
for _, htmlText := range passwordLoginHTMLs(page) {
if msg := detectPasswordLoginErrorHTML(htmlText); msg != "" {
if // msg 保存msg,供当前处理流程使用
msg := detectPasswordLoginErrorHTML(htmlText); msg != "" {
return msg
}
}
return ""
}
// passwordBaxiaEventFromPage 负责密码BaxiaEventFrom页码相关处理。
func passwordBaxiaEventFromPage(page playwright.Page) (PasswordLoginEvent, bool) {
// htmlText 表示当前遍历过程中的html文本
for _, htmlText := range passwordLoginHTMLs(page) {
if event, ok := detectPasswordBaxiaPunishHTML(htmlText); ok {
if // event、ok 保存event、ok,供当前处理流程使用
event, ok := detectPasswordBaxiaPunishHTML(htmlText); ok {
return event, true
}
}
return PasswordLoginEvent{}, false
}
// passwordVerificationEventFromPage 负责密码VerificationEventFrom页码相关处理。
func passwordVerificationEventFromPage(page playwright.Page) (PasswordLoginEvent, bool) {
if event, ok := passwordVerificationEventFromContent(pageContent(page), page.URL()); ok {
if // event、ok 保存event、ok,供当前处理流程使用
event, ok := passwordVerificationEventFromContent(pageContent(page), page.URL()); ok {
event.ScreenshotPath = firstNonEmptyString(event.ScreenshotPath, passwordVerificationScreenshot(page))
return event, true
}
// frame 表示当前遍历过程中的frame
for _, frame := range page.Frames() {
if event, ok := passwordVerificationEventFromContent(frameContent(frame), frame.URL()); ok {
if // event、ok 保存event、ok,供当前处理流程使用
event, ok := passwordVerificationEventFromContent(frameContent(frame), frame.URL()); ok {
event.ScreenshotPath = firstNonEmptyString(event.ScreenshotPath, passwordVerificationScreenshot(page))
return event, true
}
@@ -285,7 +336,9 @@ func passwordVerificationEventFromPage(page playwright.Page) (PasswordLoginEvent
return PasswordLoginEvent{}, false
}
// passwordVerificationEventFromContent 负责密码VerificationEventFrom内容相关处理。
func passwordVerificationEventFromContent(htmlText, frameURL string) (PasswordLoginEvent, bool) {
// event、ok 保存event、ok,供当前处理流程使用
event, ok := detectPasswordVerificationHTML(htmlText)
if !ok {
return PasswordLoginEvent{}, false
@@ -296,25 +349,34 @@ func passwordVerificationEventFromContent(htmlText, frameURL string) (PasswordLo
return event, true
}
// passwordLoginHTMLs 负责密码登录HTMLs相关处理。
func passwordLoginHTMLs(page playwright.Page) []string {
// htmls 保存htmls,供当前处理流程使用
htmls := []string{pageContent(page)}
// frame 表示当前遍历过程中的frame
for _, frame := range page.Frames() {
htmls = append(htmls, frameContent(frame))
}
return htmls
}
// pageContent 负责页码内容相关处理。
func pageContent(page playwright.Page) string {
// content 保存内容,供当前处理流程使用
content, _ := page.Content()
return content
}
// frameContent 负责frame内容相关处理。
func frameContent(frame playwright.Frame) string {
// content 保存内容,供当前处理流程使用
content, _ := frame.Content()
return content
}
// passwordVerificationScreenshot 负责密码VerificationScreenshot相关处理。
func passwordVerificationScreenshot(page playwright.Page) string {
// raw、err 保存raw、err,供当前处理流程使用
raw, err := page.Screenshot(playwright.PageScreenshotOptions{
FullPage: playwright.Bool(true),
Timeout: playwright.Float(5000),
@@ -325,12 +387,16 @@ func passwordVerificationScreenshot(page playwright.Page) string {
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(raw)
}
// looksLikeVerificationURL 负责looksLikeVerificationURL相关处理。
func looksLikeVerificationURL(raw string) bool {
// lower 保存lower,供当前处理流程使用
lower := strings.ToLower(raw)
return containsAny(lower, "passport", "verify", "photo", "iv/", "identity", "login", "qrcode")
}
// firstNonEmptyString 负责firstNonEmptyString相关处理。
func firstNonEmptyString(values ...string) string {
// value 表示当前遍历过程中的值
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
@@ -339,8 +405,11 @@ func firstNonEmptyString(values ...string) string {
return ""
}
// checkLoginSuccess 负责check登录Success相关处理。
func checkLoginSuccess(page playwright.Page) bool {
// sel 表示当前遍历过程中的sel
for _, sel := range loginSuccessSelectors {
// el、err 保存el、err,供当前处理流程使用
el, err := page.QuerySelector(sel)
if err != nil || el == nil {
continue
@@ -351,7 +420,8 @@ func checkLoginSuccess(page playwright.Page) bool {
return el ? el.children.length : 0;
}`, sel)
if err == nil {
if n, ok := count.(float64); ok && n > 0 {
if // n、ok 保存n、ok,供当前处理流程使用
n, ok := count.(float64); ok && n > 0 {
return true
}
}
@@ -359,21 +429,29 @@ func checkLoginSuccess(page playwright.Page) bool {
return false
}
// findLoginForm 负责find登录表单相关处理。
func findLoginForm(page playwright.Page) (idEl, pwdEl, submitEl playwright.ElementHandle) {
// frames 保存frames,供当前处理流程使用
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
// f 表示当前遍历过程中的f
for _, f := range frames {
// id 保存标识,供当前处理流程使用
id := queryFirst(f, loginIDSelectors)
if id == nil {
continue
}
// pwd 保存pwd,供当前处理流程使用
pwd := queryFirst(f, loginPwdSelectors)
// submit 保存submit,供当前处理流程使用
submit := queryFirst(f, loginBtnSelectors)
return id, pwd, submit
}
return nil, nil, nil
}
// sanitize 负责sanitize相关处理。
func sanitize(s string) string {
// r 保存r,供当前处理流程使用
r := strings.NewReplacer("/", "_", "\\", "_", ":", "_", " ", "_")
return r.Replace(s)
}
+25 -1
View File
@@ -6,6 +6,7 @@ import (
"strings"
)
// htmlTagPattern 保存htmlTagPattern,供当前处理流程使用
var (
htmlTagPattern = regexp.MustCompile(`(?is)<[^>]+>`)
scriptStylePattern = regexp.MustCompile(`(?is)<script[^>]*>.*?</script>|<style[^>]*>.*?</style>`)
@@ -14,10 +15,12 @@ var (
escapedSlashPattern = strings.NewReplacer(`\/`, `/`, `\u0026`, `&`)
)
// detectPasswordBaxiaPunishHTML 负责detect密码BaxiaPunishHTML相关处理。
func detectPasswordBaxiaPunishHTML(htmlText string) (PasswordLoginEvent, bool) {
if !IsBaxiaPunishMessage(htmlText) {
return PasswordLoginEvent{}, false
}
// msg 保存msg,供当前处理流程使用
msg := "触发闲鱼风控图形验证(baxia-punish),账号正常但暂时无法自动登录"
return PasswordLoginEvent{
Status: PasswordLoginStatusFailed,
@@ -28,8 +31,11 @@ func detectPasswordBaxiaPunishHTML(htmlText string) (PasswordLoginEvent, bool) {
}, true
}
// detectPasswordLoginErrorHTML 负责detect密码登录错误HTML相关处理。
func detectPasswordLoginErrorHTML(htmlText string) string {
// text 保存文本,供当前处理流程使用
text := normalizeHTMLText(htmlText)
// keyword 表示当前遍历过程中的关键词
for _, keyword := range []string{
"账密错误", "账号密码错误", "用户名或密码错误", "账号或密码错误", "密码错误",
"账号不存在", "账号已被冻结", "账号被冻结", "账户被冻结", "账号已锁定", "账户已锁定",
@@ -42,8 +48,11 @@ func detectPasswordLoginErrorHTML(htmlText string) string {
return ""
}
// detectPasswordVerificationHTML 负责detect密码VerificationHTML相关处理。
func detectPasswordVerificationHTML(htmlText string) (PasswordLoginEvent, bool) {
// normalized 保存normalized,供当前处理流程使用
normalized := normalizeHTMLText(htmlText)
// lower 保存lower,供当前处理流程使用
lower := strings.ToLower(htmlText)
if !containsAny(normalized,
"人脸验证", "人脸识别", "身份验证", "安全验证", "扫码验证", "验证二维码",
@@ -54,7 +63,9 @@ func detectPasswordVerificationHTML(htmlText string) (PasswordLoginEvent, bool)
) {
return PasswordLoginEvent{}, false
}
// msg 保存msg,供当前处理流程使用
msg := "密码登录需要人工验证,请在浏览器中完成验证后等待自动继续"
// event 保存event,供当前处理流程使用
event := PasswordLoginEvent{
Status: PasswordLoginStatusVerificationRequired,
Message: msg,
@@ -65,11 +76,17 @@ func detectPasswordVerificationHTML(htmlText string) (PasswordLoginEvent, bool)
return event, true
}
// extractPasswordVerificationURL 负责extract密码VerificationURL相关处理。
func extractPasswordVerificationURL(htmlText string) string {
// cleaned 保存cleaned,供当前处理流程使用
cleaned := escapedSlashPattern.Replace(html.UnescapeString(htmlText))
// matches 保存matches,供当前处理流程使用
matches := verificationURLRe.FindAllString(cleaned, -1)
// raw 表示当前遍历过程中的原始
for _, raw := range matches {
// url 保存地址,供当前处理流程使用
url := strings.TrimRight(raw, ".,);]")
// lower 保存lower,供当前处理流程使用
lower := strings.ToLower(url)
if containsAny(lower, "passport", "verify", "photo", "iv/", "identity", "login", "qrcode") {
return url
@@ -78,22 +95,29 @@ func extractPasswordVerificationURL(htmlText string) string {
return ""
}
// extractPasswordQRURL 负责extract密码QRURL相关处理。
func extractPasswordQRURL(htmlText string) string {
// cleaned 保存cleaned,供当前处理流程使用
cleaned := escapedSlashPattern.Replace(html.UnescapeString(htmlText))
if match := dataImageURLRe.FindString(cleaned); match != "" {
if // match 保存match,供当前处理流程使用
match := dataImageURLRe.FindString(cleaned); match != "" {
return match
}
return ""
}
// normalizeHTMLText 负责normalizeHTML文本相关处理。
func normalizeHTMLText(htmlText string) string {
// cleaned 保存cleaned,供当前处理流程使用
cleaned := scriptStylePattern.ReplaceAllString(htmlText, " ")
cleaned = htmlTagPattern.ReplaceAllString(cleaned, " ")
cleaned = escapedSlashPattern.Replace(html.UnescapeString(cleaned))
return strings.Join(strings.Fields(cleaned), " ")
}
// containsAny 负责containsAny相关处理。
func containsAny(s string, keywords ...string) bool {
// keyword 表示当前遍历过程中的关键词
for _, keyword := range keywords {
if strings.Contains(s, keyword) {
return true
@@ -7,8 +7,11 @@ import (
"time"
)
// TestDetectPasswordBaxiaPunishHTML 负责TestDetect密码BaxiaPunishHTML相关处理。
func TestDetectPasswordBaxiaPunishHTML(t *testing.T) {
// html 保存html,供当前处理流程使用
html := `<div id="baxia-punish"><div class="captcha-question">请找两个松鼠</div></div>`
// event、ok 保存event、ok,供当前处理流程使用
event, ok := detectPasswordBaxiaPunishHTML(html)
if !ok {
t.Fatal("应识别 baxia 图形验证")
@@ -18,7 +21,9 @@ func TestDetectPasswordBaxiaPunishHTML(t *testing.T) {
}
}
// TestPasswordEventFromMessageDoesNotTreatFaceRiskAsBaxia 负责Test密码EventFrom消息DoesNotTreatFaceRiskAsBaxia相关处理。
func TestPasswordEventFromMessageDoesNotTreatFaceRiskAsBaxia(t *testing.T) {
// event 保存event,供当前处理流程使用
event := PasswordLoginEventFromMessage("账号触发风控,需要人脸验证")
if event.Reason == "baxia_punish_captcha" {
t.Fatalf("普通人脸验证不应按 baxia 冷却: %+v", event)
@@ -28,7 +33,9 @@ func TestPasswordEventFromMessageDoesNotTreatFaceRiskAsBaxia(t *testing.T) {
}
}
// TestDetectPasswordLoginErrorHTML 负责TestDetect密码登录错误HTML相关处理。
func TestDetectPasswordLoginErrorHTML(t *testing.T) {
// msg 保存msg,供当前处理流程使用
msg := detectPasswordLoginErrorHTML(`<div class="login-error-msg">账号或密码错误</div>`)
if msg != "账号或密码错误" {
t.Fatalf("登录错误识别=%q", msg)
@@ -39,8 +46,11 @@ func TestDetectPasswordLoginErrorHTML(t *testing.T) {
}
}
// TestDetectPasswordVerificationHTML 负责TestDetect密码VerificationHTML相关处理。
func TestDetectPasswordVerificationHTML(t *testing.T) {
// html 保存html,供当前处理流程使用
html := `<iframe id="alibaba-login-box" src="https:\/\/passport.goofish.com\/iv\/photoVerify\/index.htm?token=abc"></iframe><div>需要人脸验证,请使用手机扫码</div>`
// event、ok 保存event、ok,供当前处理流程使用
event, ok := detectPasswordVerificationHTML(html)
if !ok {
t.Fatal("应识别人脸验证")
@@ -53,6 +63,7 @@ func TestDetectPasswordVerificationHTML(t *testing.T) {
}
}
// TestQuickEnterCookiesUsableRequiresUNB 负责TestQuickEnterCookiesUsableRequiresUNB相关处理。
func TestQuickEnterCookiesUsableRequiresUNB(t *testing.T) {
if quickEnterCookiesUsable(map[string]string{"_m_h5_tk": "tk"}) {
t.Fatal("快速进入未拿到 unb 不应视为成功")
@@ -65,6 +76,7 @@ func TestQuickEnterCookiesUsableRequiresUNB(t *testing.T) {
}
}
// TestPasswordLoginReferenceProfileAndTiming 负责Test密码登录ReferenceProfileAndTiming相关处理。
func TestPasswordLoginReferenceProfileAndTiming(t *testing.T) {
if passwordLoginPageLoadWait != 2*time.Second || passwordLoginTabWait != 1500*time.Millisecond ||
passwordLoginAfterSubmitWait != 3*time.Second || passwordLoginCompletionWait != 5*time.Second {
@@ -77,8 +89,10 @@ func TestPasswordLoginReferenceProfileAndTiming(t *testing.T) {
}
}
// TestPasswordPersistentContextOptionsMatchReference 负责Test密码Persistent上下文OptionsMatchReference相关处理。
func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) {
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "/opt/chromium")
// opts 保存opts,供当前处理流程使用
opts := passwordPersistentContextOptions(true)
if opts.Headless == nil || !*opts.Headless {
t.Fatal("密码登录应按调用参数使用无头模式")
@@ -106,8 +120,11 @@ func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) {
}
}
// TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit 负责Test密码登录RejectsBlankCredentialsBefore浏览器Init相关处理。
func TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit(t *testing.T) {
// m 保存m,供当前处理流程使用
m := &Manager{}
// tc 表示当前遍历过程中的tc
for _, tc := range []struct {
account string
password string
@@ -116,6 +133,7 @@ func TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit(t *testing.T) {
{account: "account", password: ""},
{account: " ", password: "secret"},
} {
// err 保存err,供当前处理流程使用
_, err := m.PasswordLogin(context.Background(), tc.account, tc.password, "cookie-id", "", true)
if err == nil || !strings.Contains(err.Error(), "账号或密码不能为空") {
t.Fatalf("account=%q password=%q: err=%v", tc.account, tc.password, err)
+8
View File
@@ -2,6 +2,7 @@ package browser
import "strings"
// PasswordLoginStatusProcessing 保存密码登录状态Processing,供当前处理流程使用
const (
PasswordLoginStatusProcessing = "processing"
PasswordLoginStatusVerificationRequired = "verification_required"
@@ -20,8 +21,10 @@ type PasswordLoginEvent struct {
CooldownHours int
}
// PasswordLoginEventHandler 保存密码登录EventHandler,供当前处理流程使用
type PasswordLoginEventHandler func(PasswordLoginEvent)
// PasswordLoginEventFromError 负责密码登录EventFrom错误相关处理。
func PasswordLoginEventFromError(err error) PasswordLoginEvent {
if err == nil {
return PasswordLoginEvent{}
@@ -29,8 +32,11 @@ func PasswordLoginEventFromError(err error) PasswordLoginEvent {
return PasswordLoginEventFromMessage(err.Error())
}
// PasswordLoginEventFromMessage 负责密码登录EventFrom消息相关处理。
func PasswordLoginEventFromMessage(msg string) PasswordLoginEvent {
// lower 保存lower,供当前处理流程使用
lower := strings.ToLower(msg)
// event 保存event,供当前处理流程使用
event := PasswordLoginEvent{Status: PasswordLoginStatusFailed, Message: msg, Error: msg}
switch {
case IsBaxiaPunishMessage(msg) || (strings.Contains(msg, "风控") && strings.Contains(msg, "图形验证")):
@@ -42,7 +48,9 @@ func PasswordLoginEventFromMessage(msg string) PasswordLoginEvent {
return event
}
// IsBaxiaPunishMessage 负责IsBaxiaPunish消息相关处理。
func IsBaxiaPunishMessage(msg string) bool {
// lower 保存lower,供当前处理流程使用
lower := strings.ToLower(msg)
return strings.Contains(lower, "baxia") ||
strings.Contains(lower, "punish") ||
@@ -5,21 +5,27 @@ import (
"testing"
)
// TestPasswordLoginEventFromErrorVerification 负责Test密码登录EventFrom错误Verification相关处理。
func TestPasswordLoginEventFromErrorVerification(t *testing.T) {
// event 保存event,供当前处理流程使用
event := PasswordLoginEventFromError(errors.New("需要人脸验证"))
if event.Status != PasswordLoginStatusVerificationRequired {
t.Fatalf("status=%q want verification_required", event.Status)
}
}
// TestPasswordLoginEventFromErrorBaxia 负责Test密码登录EventFrom错误Baxia相关处理。
func TestPasswordLoginEventFromErrorBaxia(t *testing.T) {
// event 保存event,供当前处理流程使用
event := PasswordLoginEventFromError(errors.New("baxia-punish verification 风控图形验证"))
if event.Status != PasswordLoginStatusFailed || event.Reason != "baxia_punish_captcha" || event.CooldownHours != 5 {
t.Fatalf("event=%+v", event)
}
}
// TestIsBaxiaPunishMessage 负责TestIsBaxiaPunish消息相关处理。
func TestIsBaxiaPunishMessage(t *testing.T) {
// msg 表示当前遍历过程中的msg
for _, msg := range []string{"baxia-punish", "scratch-captcha-container", "找两个松鼠"} {
if !IsBaxiaPunishMessage(msg) {
t.Fatalf("%q should be recognized as baxia punish", msg)
+15 -2
View File
@@ -4,20 +4,25 @@ import "testing"
// TestSanitize 特殊字符替换为下划线(用于 userDataDir 命名)。
func TestSanitize(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]string{
"acc_1": "acc_1",
"acc/1:2 3": "acc_1_2_3",
`a\b:c d`: "a_b_c_d",
"": "",
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if got := sanitize(in); got != want {
if // got 保存got,供当前处理流程使用
got := sanitize(in); got != want {
t.Errorf("sanitize(%q)=%q want %q", in, got, want)
}
}
}
// TestPureUserIDMatchesReferenceRule 负责TestPure用户IDMatchesReference规则相关处理。
func TestPureUserIDMatchesReferenceRule(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]string{
"foo_1234567890": "foo",
"foo_bar_1234567890": "foo_bar",
@@ -26,13 +31,16 @@ func TestPureUserIDMatchesReferenceRule(t *testing.T) {
"": "unknown",
"foo/bar_1234567890": "foo_bar",
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if got := pureUserID(in); got != want {
if // got 保存got,供当前处理流程使用
got := pureUserID(in); got != want {
t.Fatalf("pureUserID(%q)=%q want %q", in, got, want)
}
}
}
// TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides 负责TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides相关处理。
func TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides(t *testing.T) {
t.Setenv("BROWSER_HEADLESS", "")
if !quickRenewHeadless(true) {
@@ -51,6 +59,7 @@ func TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides(t *testing.T) {
}
}
// TestResolveHeadlessUsesShowBrowserConsistently 负责TestResolveHeadlessUsesShow浏览器Consistently相关处理。
func TestResolveHeadlessUsesShowBrowserConsistently(t *testing.T) {
t.Setenv("BROWSER_HEADLESS", "")
if !ResolveHeadless(false) {
@@ -69,6 +78,7 @@ func TestResolveHeadlessUsesShowBrowserConsistently(t *testing.T) {
}
}
// TestCookiesRefreshHeadlessUsesAccountPreference 负责TestCookiesRefreshHeadlessUses账号Preference相关处理。
func TestCookiesRefreshHeadlessUsesAccountPreference(t *testing.T) {
t.Setenv("BROWSER_HEADLESS", "")
if !cookiesRefreshHeadless(true) {
@@ -83,18 +93,21 @@ func TestCookiesRefreshHeadlessUsesAccountPreference(t *testing.T) {
}
}
// TestChromiumExecutablePathFromEnv 负责TestChromiumExecutable路径FromEnv相关处理。
func TestChromiumExecutablePathFromEnv(t *testing.T) {
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "")
if chromiumExecutablePath() != nil {
t.Fatal("未设置 PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH 时应返回 nil")
}
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", " /usr/bin/chromium ")
// got 保存got,供当前处理流程使用
got := chromiumExecutablePath()
if got == nil || *got != "/usr/bin/chromium" {
t.Fatalf("chromiumExecutablePath=%v", got)
}
}
// TestSkipPlaywrightBrowserDownloadFromEnv 负责TestSkipPlaywright浏览器DownloadFromEnv相关处理。
func TestSkipPlaywrightBrowserDownloadFromEnv(t *testing.T) {
t.Setenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "")
if skipPlaywrightBrowserDownload() {
+25 -8
View File
@@ -14,11 +14,13 @@ import (
// QRCookieRefresh 用扫码临时 cookie + 风控验证 URL,通过浏览器换取真实 cookie(含 unb)。
// verificationURL 为空时跳过验证步骤(无风控场景)。
// QRCookieRefresh 负责QR登录凭证Refresh相关处理。
func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (realCookies string, unb string, err error) {
if tmpCookies == "" {
return "", "", fmt.Errorf("扫码临时 cookie 为空")
}
if err := m.init(); err != nil {
if // err 保存err,供当前处理流程使用
err := m.init(); err != nil {
return "", "", err
}
@@ -35,6 +37,7 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
}
defer func() { _ = browser.Close() }()
// bctx、err 保存bctx、err,供当前处理流程使用
bctx, err := browser.NewContext(playwright.BrowserNewContextOptions{
Viewport: &playwright.Size{Width: 1100, Height: 760},
Locale: playwright.String(defaultLang),
@@ -45,13 +48,16 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
}
defer func() { _ = bctx.Close() }()
if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
if // err 保存err,供当前处理流程使用
err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
m.logger.Warn("注入 stealth 脚本失败", "err", err)
}
if err := addCookieStr(bctx, tmpCookies); err != nil {
if // err 保存err,供当前处理流程使用
err := addCookieStr(bctx, tmpCookies); err != nil {
return "", "", fmt.Errorf("注入临时 cookie 失败: %w", err)
}
// page、err 保存page、err,供当前处理流程使用
page, err := bctx.NewPage()
if err != nil {
return "", "", fmt.Errorf("新建 page 失败: %w", err)
@@ -62,7 +68,8 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
// 用户在手机完成验证后,mini_login_check.htm 会自动 redirect 到 ivCheckLogin.htm。
// Chromium 跟随这个 redirect,服务端会在此 session 里写入认证态。
m.logger.Info("Chromium 打开验证等待页", "verification_url", logsafe.URL(verificationURL))
if _, err := page.Goto(verificationURL, playwright.PageGotoOptions{
if // err 保存err,供当前处理流程使用
_, err := page.Goto(verificationURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(15000),
}); err != nil {
@@ -72,8 +79,10 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
// 等待用户完成手机验证,页面会 redirect 到 ivCheckLogin.htm(最多3分钟)。
// 每2秒截图一次并通过 onScreenshot 回调发给前端,用户可直接看到验证页面。
m.logger.Info("等待验证完成(监测页面 redirect + 截图推送)...")
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(3 * time.Minute)
for time.Now().Before(deadline) {
// u 保存u,供当前处理流程使用
u := page.URL()
if strings.Contains(u, "ivCheckLogin") {
m.logger.Info("验证通过,页面已跳转", "url", logsafe.URL(u))
@@ -81,7 +90,8 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
}
// 截图并回调给前端。
if onScreenshot != nil {
if img, err2 := page.Screenshot(); err2 == nil {
if // img、err2 保存img、err2,供当前处理流程使用
img, err2 := page.Screenshot(); err2 == nil {
onScreenshot("data:image/png;base64," + base64.StdEncoding.EncodeToString(img))
}
}
@@ -96,7 +106,8 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
// A single normal home-page load runs goofish-auto-login and loginuser.get.
// Do not reload repeatedly: the browser client does not do that and the
// duplicate burst is an avoidable risk signal.
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
if // err 保存err,供当前处理流程使用
_, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(20000),
}); err != nil {
@@ -107,12 +118,15 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
// 轮询直到 unb 出现或超时(最长15秒)。
var all []playwright.Cookie
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
// err2 保存err2,供当前处理流程使用
var err2 error
all, err2 = bctx.Cookies()
if err2 == nil {
if m2 := cookiesToMap(all); m2["unb"] != "" {
if // m2 保存m2,供当前处理流程使用
m2 := cookiesToMap(all); m2["unb"] != "" {
m.logger.Info("轮询拿到 unb")
break
}
@@ -126,13 +140,16 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
return "", "", fmt.Errorf("提取 cookie 失败: %w", err)
}
}
// cookieMap 保存登录凭证Map,供当前处理流程使用
cookieMap := cookiesToMap(all)
// cookieStr 保存登录凭证Str,供当前处理流程使用
cookieStr := cookieMarshal(cookieMap)
unb = cookieMap["unb"]
// 关键字段日志,便于排查。
for _, k := range []string{"unb", "_m_h5_tk", "_m_h5_tk_enc", "cookie2", "t", "sgcookie", "cna"} {
if v, ok := cookieMap[k]; ok {
if // v、ok 保存v、ok,供当前处理流程使用
v, ok := cookieMap[k]; ok {
m.logger.Info("cookie字段", "name", k, "len", len(v))
} else {
m.logger.Info("cookie字段缺失", "name", k)
+1
View File
@@ -3,6 +3,7 @@ package browser
// Keep Chromium's native fingerprint intact. The launch arguments already
// disable AutomationControlled; this only removes well-known automation
// globals and never patches input events or hardware properties.
// stealthTemplate 保存stealthTemplate,供当前处理流程使用
const stealthTemplate = `
(() => {
try {
+10 -2
View File
@@ -6,27 +6,35 @@ import (
"xianyu-go/internal/xianyu/cookierefresh"
)
// TestCredentialCookieSnapshotPreservesChromiumAttributes 负责TestCredential登录凭证SnapshotPreservesChromiumAttributes相关处理。
func TestCredentialCookieSnapshotPreservesChromiumAttributes(t *testing.T) {
// existing 保存existing,供当前处理流程使用
existing := []cookierefresh.BrowserCookie{
{Name: "cookie2", Value: "old", Domain: ".taobao.com", Path: "/", Expires: 12345, HTTPOnly: true, Secure: true, SameSite: "None"},
{Name: "stale", Value: "remove", Domain: ".goofish.com", Path: "/"},
}
// got 保存got,供当前处理流程使用
got := credentialCookieSnapshot(existing, map[string]string{"cookie2": "new", "unb": "1"})
if len(got) != 2 {
t.Fatalf("snapshot length=%d want=2: %+v", len(got), got)
}
// byName 保存by名称,供当前处理流程使用
byName := map[string]cookierefresh.BrowserCookie{}
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range got {
byName[cookie.Name] = cookie
}
// cookie2 保存cookie2,供当前处理流程使用
cookie2 := byName["cookie2"]
if cookie2.Value != "new" || cookie2.Domain != ".taobao.com" || cookie2.Expires != 12345 || !cookie2.HTTPOnly || !cookie2.Secure || cookie2.SameSite != "None" {
t.Fatalf("preserved cookie=%+v", cookie2)
}
if unb := byName["unb"]; unb.Domain != goofishDot || unb.Path != "/" {
if // unb 保存unb,供当前处理流程使用
unb := byName["unb"]; unb.Domain != goofishDot || unb.Path != "/" {
t.Fatalf("new cookie defaults=%+v", unb)
}
if _, ok := byName["stale"]; ok {
if // ok 保存ok,供当前处理流程使用
_, ok := byName["stale"]; ok {
t.Fatal("cookie absent from current snapshot must be removed")
}
}
+4 -1
View File
@@ -9,12 +9,14 @@ import (
// resolvePersistentUserDataDir prepares the profile directory required by
// Playwright's LaunchPersistentContext. playwright-go rejects relative paths.
// resolvePersistentUserDataDir 负责resolvePersistent用户数据Dir相关处理。
func resolvePersistentUserDataDir(path string) (string, error) {
path = strings.TrimSpace(path)
if path == "" {
return "", fmt.Errorf("持久化浏览器用户数据目录不能为空")
}
// absPath、err 保存absPath、err,供当前处理流程使用
absPath, err := filepath.Abs(path)
if err != nil {
return "", fmt.Errorf("解析持久化浏览器用户数据目录失败: %w", err)
@@ -23,7 +25,8 @@ func resolvePersistentUserDataDir(path string) (string, error) {
if !filepath.IsAbs(absPath) {
return "", fmt.Errorf("持久化浏览器用户数据目录不是绝对路径: %s", absPath)
}
if err := os.MkdirAll(absPath, 0o700); err != nil {
if // err 保存err,供当前处理流程使用
err := os.MkdirAll(absPath, 0o700); err != nil {
return "", fmt.Errorf("创建持久化浏览器用户数据目录失败: %w", err)
}
return absPath, nil
+16 -1
View File
@@ -7,17 +7,22 @@ import (
"testing"
)
// TestResolvePersistentUserDataDirConvertsRelativePathAndCreatesDirectory 负责TestResolvePersistent用户数据DirConvertsRelative路径AndCreatesDirectory相关处理。
func TestResolvePersistentUserDataDirConvertsRelativePathAndCreatesDirectory(t *testing.T) {
// cwd、err 保存cwd、err,供当前处理流程使用
cwd, err := os.Getwd()
if err != nil {
t.Fatalf("Getwd: %v", err)
}
// target 保存target,供当前处理流程使用
target := filepath.Join(t.TempDir(), "nested", "profile")
// relative、err 保存relative、err,供当前处理流程使用
relative, err := filepath.Rel(cwd, target)
if err != nil {
t.Fatalf("Rel: %v", err)
}
// got、err 保存got、err,供当前处理流程使用
got, err := resolvePersistentUserDataDir(relative)
if err != nil {
t.Fatalf("resolvePersistentUserDataDir: %v", err)
@@ -28,6 +33,7 @@ func TestResolvePersistentUserDataDirConvertsRelativePathAndCreatesDirectory(t *
if got != filepath.Clean(target) {
t.Fatalf("got %q, want %q", got, filepath.Clean(target))
}
// info、err 保存info、err,供当前处理流程使用
info, err := os.Stat(got)
if err != nil {
t.Fatalf("Stat: %v", err)
@@ -37,8 +43,11 @@ func TestResolvePersistentUserDataDirConvertsRelativePathAndCreatesDirectory(t *
}
}
// TestResolvePersistentUserDataDirPreservesAbsolutePath 负责TestResolvePersistent用户数据DirPreservesAbsolute路径相关处理。
func TestResolvePersistentUserDataDirPreservesAbsolutePath(t *testing.T) {
// target 保存target,供当前处理流程使用
target := filepath.Join(t.TempDir(), "profile")
// got、err 保存got、err,供当前处理流程使用
got, err := resolvePersistentUserDataDir(" " + target + " ")
if err != nil {
t.Fatalf("resolvePersistentUserDataDir: %v", err)
@@ -48,18 +57,24 @@ func TestResolvePersistentUserDataDirPreservesAbsolutePath(t *testing.T) {
}
}
// TestResolvePersistentUserDataDirRejectsEmptyPath 负责TestResolvePersistent用户数据DirRejectsEmpty路径相关处理。
func TestResolvePersistentUserDataDirRejectsEmptyPath(t *testing.T) {
// err 保存err,供当前处理流程使用
_, err := resolvePersistentUserDataDir(" ")
if err == nil || !strings.Contains(err.Error(), "不能为空") {
t.Fatalf("空路径应返回明确错误,got %v", err)
}
}
// TestResolvePersistentUserDataDirReportsCreateFailure 负责TestResolvePersistent用户数据DirReportsCreateFailure相关处理。
func TestResolvePersistentUserDataDirReportsCreateFailure(t *testing.T) {
// parentFile 保存parent文件,供当前处理流程使用
parentFile := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(parentFile, []byte("not a directory"), 0o600); err != nil {
if // err 保存err,供当前处理流程使用
err := os.WriteFile(parentFile, []byte("not a directory"), 0o600); err != nil {
t.Fatalf("WriteFile: %v", err)
}
// err 保存err,供当前处理流程使用
_, err := resolvePersistentUserDataDir(filepath.Join(parentFile, "profile"))
if err == nil || !strings.Contains(err.Error(), "创建") {
t.Fatalf("目录创建失败应返回明确错误,got %v", err)