重构:完成架构一致性整改与生命周期收口
This commit is contained in:
1 parent
55904cc409
commit
9eb6be2875
344 files changed
+15961
-13926
No files matched your search
@@ -16,7 +16,7 @@ import (
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
// quickRenewPageLoadWait 保存quickRenew页码LoadWait,供当前处理流程使用
|
||||
// quickRenewPageLoadWait 用于本次流程后续判断的quickRenew页码LoadWait
|
||||
const (
|
||||
quickRenewPageLoadWait = 3 * time.Second
|
||||
quickRenewAfterClick = 5 * time.Second
|
||||
@@ -26,7 +26,7 @@ const (
|
||||
officialReloadWait = 5 * time.Second
|
||||
)
|
||||
|
||||
// ErrInteractiveLoginRequired 保存ErrInteractive登录Required,供当前处理流程使用
|
||||
// ErrInteractiveLoginRequired 用于本次流程后续判断的ErrInteractive登录Required
|
||||
var (
|
||||
ErrInteractiveLoginRequired = errors.New("浏览器会话已退出登录,需要交互式登录")
|
||||
ErrSecurityVerification = errors.New("闲鱼要求安全验证,需要人工处理")
|
||||
@@ -36,9 +36,9 @@ var (
|
||||
//
|
||||
// 这个方法位于密码登录之前:如果 Cookie 仍保留可续期的浏览器会话,页面通常会给出
|
||||
// 免输密码的快速进入入口。成功点击后提取完整 Cookie,可避免更重的账号密码登录。
|
||||
// CookieRenew 负责登录凭证Renew相关处理。
|
||||
// CookieRenew 封装登录凭证Renew业务协调。
|
||||
func (m *Manager) CookieRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (map[string]string, error) {
|
||||
// newCookies、err 保存newCookies、err,供当前处理流程使用
|
||||
// newCookies、err 用于本次流程后续判断的newCookies、err
|
||||
newCookies, err := m.BrowserQuickRenew(ctx, cookieID, cookieStr, headless)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -46,7 +46,7 @@ func (m *Manager) CookieRenew(ctx context.Context, cookieID, cookieStr string, h
|
||||
return cookierefresh.ParseCookieString(newCookies), nil
|
||||
}
|
||||
|
||||
// newPersistentPasswordContext 负责newPersistent密码上下文相关处理。
|
||||
// newPersistentPasswordContext 封装newPersistent密码上下文业务协调。
|
||||
func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, userDataDir string, headless bool) (playwright.BrowserContext, func(), error) {
|
||||
// err 表示管理器拒绝新建持久化上下文的原因,并用于下面的短路返回。
|
||||
if err := m.beginOperation(ctx); err != nil {
|
||||
@@ -58,20 +58,20 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us
|
||||
finishOperation := func() {
|
||||
operationOnce.Do(m.endOperation)
|
||||
}
|
||||
// lock 保存锁,供当前处理流程使用
|
||||
// lock 用于本次流程后续判断的锁
|
||||
lock := m.accountRenewLock(cookieID)
|
||||
lock.Lock()
|
||||
// unlock 保存unlock,供当前处理流程使用
|
||||
// unlock 用于本次流程后续判断的unlock
|
||||
unlock := func() { lock.Unlock() }
|
||||
|
||||
// releaseSlot、err 保存releaseSlot、err,供当前处理流程使用
|
||||
// releaseSlot、err 用于本次流程后续判断的releaseSlot、err
|
||||
releaseSlot, err := m.acquireRenewSlot(ctx)
|
||||
if err != nil {
|
||||
unlock()
|
||||
finishOperation()
|
||||
return nil, nil, err
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.init(); err != nil {
|
||||
releaseSlot()
|
||||
unlock()
|
||||
@@ -86,9 +86,9 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us
|
||||
return nil, nil, err
|
||||
}
|
||||
cleanSingletonFiles(userDataDir)
|
||||
// bctx 保存bctx,供当前处理流程使用
|
||||
// bctx 用于本次流程后续判断的bctx
|
||||
var bctx playwright.BrowserContext
|
||||
// lastErr 保存lastErr,供当前处理流程使用
|
||||
// lastErr 用于本次流程后续判断的lastErr
|
||||
var lastErr error
|
||||
// attempt 表示当前持久化 Chromium 的重试序号;启动失败时会先清理 profile 锁文件再重试一次。
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
@@ -106,7 +106,7 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us
|
||||
finishOperation()
|
||||
return nil, nil, fmt.Errorf("启动持久化浏览器失败: %w", lastErr)
|
||||
}
|
||||
// release 保存release,供当前处理流程使用
|
||||
// release 用于本次流程后续判断的release
|
||||
release := func() {
|
||||
_ = bctx.Close()
|
||||
releaseSlot()
|
||||
@@ -141,7 +141,7 @@ func passwordPersistentContextOptions(headless bool, headlessUserAgent ...*strin
|
||||
|
||||
// BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。
|
||||
func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error) {
|
||||
// newCookies、err 保存newCookies、err,供当前处理流程使用
|
||||
// newCookies、err 用于本次流程后续判断的newCookies、err
|
||||
newCookies, _, err := m.BrowserQuickRenewSnapshot(ctx, cookieID, cookieStr, nil, headless)
|
||||
return newCookies, err
|
||||
}
|
||||
@@ -149,14 +149,14 @@ 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相关处理。
|
||||
// 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 用于本次流程后续判断的effectiveSnapshot
|
||||
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
|
||||
|
||||
// headless 是经环境覆盖后的本次续期浏览器可见性,并决定是否必须应用运行时指纹。
|
||||
@@ -175,7 +175,7 @@ func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cooki
|
||||
}
|
||||
defer func() { _ = page.Close() }()
|
||||
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(quickRenewTimeoutMS),
|
||||
@@ -184,11 +184,11 @@ func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cooki
|
||||
}
|
||||
time.Sleep(quickRenewPageLoadWait)
|
||||
|
||||
// hasQuickEnter 保存hasQuickEnter,供当前处理流程使用
|
||||
// hasQuickEnter 用于本次流程后续判断的hasQuickEnter
|
||||
hasQuickEnter := false
|
||||
// renewErr 保存renewErr,供当前处理流程使用
|
||||
// renewErr 用于本次流程后续判断的renewErr
|
||||
var renewErr error
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := verifyHomeLoginState(page); err != nil {
|
||||
if errors.Is(err, ErrSecurityVerification) {
|
||||
renewErr = err
|
||||
@@ -203,7 +203,7 @@ func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cooki
|
||||
}
|
||||
}
|
||||
|
||||
// newCookies、newSnapshot、err 保存newCookies、newSnapshot、err,供当前处理流程使用
|
||||
// newCookies、newSnapshot、err 用于本次流程后续判断的newCookies、newSnapshot、err
|
||||
newCookies, newSnapshot, err := readAuthoritativeCookieJar(bctx, goofishIMURL)
|
||||
if err != nil {
|
||||
return "", nil, errors.Join(renewErr, err)
|
||||
@@ -222,12 +222,12 @@ 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相关处理。
|
||||
// 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 用于本次流程后续判断的effectiveSnapshot
|
||||
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
|
||||
// headless 是经环境覆盖后的定时续期浏览器可见性,并决定页面级指纹覆盖。
|
||||
headless = cookiesRefreshHeadless(headless)
|
||||
@@ -245,13 +245,13 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt
|
||||
}
|
||||
defer func() { _ = page.Close() }()
|
||||
|
||||
// reloaded、renewErr 保存reloaded、renewErr,供当前处理流程使用
|
||||
// reloaded、renewErr 用于本次流程后续判断的reloaded、renewErr
|
||||
reloaded, renewErr := navigateOfficialRenewPage(ctx, page)
|
||||
if renewErr == nil {
|
||||
renewErr = verifyHomeLoginState(page)
|
||||
}
|
||||
|
||||
// newCookies、newSnapshot、err 保存newCookies、newSnapshot、err,供当前处理流程使用
|
||||
// newCookies、newSnapshot、err 用于本次流程后续判断的newCookies、newSnapshot、err
|
||||
newCookies, newSnapshot, err := readAuthoritativeCookieJar(bctx, goofishIMURL)
|
||||
if err != nil {
|
||||
return "", nil, reloaded, errors.Join(renewErr, err)
|
||||
@@ -266,15 +266,15 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt
|
||||
return newCookies, newSnapshot, reloaded, nil
|
||||
}
|
||||
|
||||
// navigateOfficialRenewPage 负责navigateOfficialRenew页码相关处理。
|
||||
// navigateOfficialRenewPage 封装navigateOfficialRenew页码业务协调。
|
||||
func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool, error) {
|
||||
// silentStarted 保存silentStarted,供当前处理流程使用
|
||||
// silentStarted 用于本次流程后续判断的silentStarted
|
||||
silentStarted := make(chan struct{}, 1)
|
||||
// silentSettled 保存silentSettled,供当前处理流程使用
|
||||
// silentSettled 用于本次流程后续判断的silentSettled
|
||||
silentSettled := make(chan bool, 1)
|
||||
// reloadCommitted 保存reloadCommitted,供当前处理流程使用
|
||||
// reloadCommitted 用于本次流程后续判断的reloadCommitted
|
||||
reloadCommitted := make(chan struct{}, 1)
|
||||
// navigationArmed 保存navigationArmed,供当前处理流程使用
|
||||
// navigationArmed 用于本次流程后续判断的navigationArmed
|
||||
var navigationArmed atomic.Bool
|
||||
page.OnRequest(func(request playwright.Request) {
|
||||
if isSilentHasLoginURL(request.URL()) {
|
||||
@@ -309,7 +309,7 @@ func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool,
|
||||
}
|
||||
})
|
||||
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(60000),
|
||||
@@ -321,9 +321,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 用于本次流程后续判断的observe定时器
|
||||
observeTimer := time.NewTimer(officialAutoLoginWait)
|
||||
// requestStarted 保存请求Started,供当前处理流程使用
|
||||
// requestStarted 用于本次流程后续判断的请求Started
|
||||
requestStarted := false
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -338,9 +338,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 用于本次流程后续判断的drain定时器
|
||||
drainTimer := time.NewTimer(officialFetchDrainWait)
|
||||
// requestFinished 保存请求Finished,供当前处理流程使用
|
||||
// requestFinished 用于本次流程后续判断的请求Finished
|
||||
requestFinished := false
|
||||
select {
|
||||
case requestFinished = <-silentSettled:
|
||||
@@ -351,12 +351,12 @@ func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool,
|
||||
case <-drainTimer.C:
|
||||
}
|
||||
if requestFinished {
|
||||
// reloadTimer 保存reload定时器,供当前处理流程使用
|
||||
// reloadTimer 用于本次流程后续判断的reload定时器
|
||||
reloadTimer := time.NewTimer(officialReloadWait)
|
||||
select {
|
||||
case <-reloadCommitted:
|
||||
reloadTimer.Stop()
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := page.WaitForLoadState(playwright.PageWaitForLoadStateOptions{
|
||||
State: playwright.LoadStateDomcontentloaded, Timeout: playwright.Float(10000),
|
||||
}); err != nil {
|
||||
@@ -375,14 +375,14 @@ func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool,
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// readAuthoritativeCookieJar 负责readAuthoritative登录凭证Jar相关处理。
|
||||
// readAuthoritativeCookieJar 封装readAuthoritative登录凭证Jar业务协调。
|
||||
func readAuthoritativeCookieJar(bctx playwright.BrowserContext, rawURL string) (string, []cookierefresh.BrowserCookie, error) {
|
||||
// all、err 保存all、err,供当前处理流程使用
|
||||
// all、err 用于本次流程后续判断的all、err
|
||||
all, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("提取浏览器 Cookie Jar: %w", err)
|
||||
}
|
||||
// snapshot 保存snapshot,供当前处理流程使用
|
||||
// snapshot 用于本次流程后续判断的snapshot
|
||||
snapshot := cookieSnapshotFromPlaywright(all)
|
||||
if snapshot == nil {
|
||||
snapshot = []cookierefresh.BrowserCookie{}
|
||||
@@ -390,12 +390,12 @@ func readAuthoritativeCookieJar(bctx playwright.BrowserContext, rawURL string) (
|
||||
return currentCookieHeader(snapshot, rawURL), snapshot, nil
|
||||
}
|
||||
|
||||
// isSilentHasLoginURL 负责isSilentHas登录URL相关处理。
|
||||
// isSilentHasLoginURL 封装isSilentHas登录URL业务协调。
|
||||
func isSilentHasLoginURL(rawURL string) bool {
|
||||
return strings.Contains(rawURL, "/newlogin/silentHasLogin.do")
|
||||
}
|
||||
|
||||
// reconcileSnapshotWithCurrentCookie 负责reconcileSnapshotWithCurrent登录凭证相关处理。
|
||||
// reconcileSnapshotWithCurrentCookie 封装reconcileSnapshotWithCurrent登录凭证业务协调。
|
||||
func reconcileSnapshotWithCurrentCookie(snapshot []cookierefresh.BrowserCookie, cookieStr, rawURL string) []cookierefresh.BrowserCookie {
|
||||
if snapshot == nil {
|
||||
return nil
|
||||
@@ -411,36 +411,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 用于本次流程后续判断的cookies、refreshed、err
|
||||
cookies, refreshed, _, err := m.CookiesRefreshSnapshot(ctx, cookieID, cookieStr, snapshot, headless)
|
||||
return cookies, refreshed, err
|
||||
}
|
||||
|
||||
// clickQuickEnter 负责clickQuickEnter相关处理。
|
||||
// clickQuickEnter 封装clickQuickEnter业务协调。
|
||||
func clickQuickEnter(page playwright.Page) bool {
|
||||
// frames 保存frames,供当前处理流程使用
|
||||
// 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 用于本次流程后续判断的el、err
|
||||
el, err := f.QuerySelector(sel)
|
||||
if err == nil && el != nil && elementVisible(el) {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := el.Click(); err == nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
// buttons、err 保存buttons、err,供当前处理流程使用
|
||||
// buttons、err 用于本次流程后续判断的buttons、err
|
||||
buttons, err := f.QuerySelectorAll("button")
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
// btn 表示当前遍历过程中的btn
|
||||
for _, btn := range buttons {
|
||||
// text 保存文本,供当前处理流程使用
|
||||
// text 用于本次流程后续判断的文本
|
||||
text, _ := btn.TextContent()
|
||||
if strings.Contains(strings.TrimSpace(text), "快速进入") && elementVisible(btn) {
|
||||
_ = btn.Click()
|
||||
@@ -451,7 +451,7 @@ func clickQuickEnter(page playwright.Page) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// quickEnterSelectors 保存quickEnterSelectors,供当前处理流程使用
|
||||
// quickEnterSelectors 用于本次流程后续判断的quickEnterSelectors
|
||||
var quickEnterSelectors = []string{
|
||||
`button:has-text("快速进入")`,
|
||||
`button[type="submit"]:has-text("快速进入")`,
|
||||
@@ -459,12 +459,12 @@ var quickEnterSelectors = []string{
|
||||
`.fn-button:has-text("快速进入")`,
|
||||
}
|
||||
|
||||
// verifyHomeLoginState 负责verifyHome登录状态相关处理。
|
||||
// verifyHomeLoginState 封装verifyHome登录状态业务协调。
|
||||
func verifyHomeLoginState(page playwright.Page) error {
|
||||
if pageHasSecurityVerification(page) {
|
||||
return ErrSecurityVerification
|
||||
}
|
||||
// result、err 保存result、err,供当前处理流程使用
|
||||
// result、err 用于本次流程后续判断的result、err
|
||||
result, err := page.Evaluate(`() => {
|
||||
const visible = (el) => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
@@ -485,14 +485,14 @@ func verifyHomeLoginState(page playwright.Page) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取浏览器登录状态失败: %w", err)
|
||||
}
|
||||
// signals、ok 保存signals、ok,供当前处理流程使用
|
||||
// signals、ok 用于本次流程后续判断的signals、ok
|
||||
signals, ok := result.(map[string]any)
|
||||
if !ok {
|
||||
return fmt.Errorf("浏览器登录状态返回格式异常")
|
||||
}
|
||||
// personal 保存personal,供当前处理流程使用
|
||||
// personal 用于本次流程后续判断的personal
|
||||
personal, _ := signals["personal"].(bool)
|
||||
// login 保存登录,供当前处理流程使用
|
||||
// login 用于本次流程后续判断的登录
|
||||
login, _ := signals["login"].(bool)
|
||||
if personal && !login {
|
||||
return nil
|
||||
@@ -503,11 +503,11 @@ func verifyHomeLoginState(page playwright.Page) error {
|
||||
return fmt.Errorf("%w: 页面未出现个人主页入口", ErrInteractiveLoginRequired)
|
||||
}
|
||||
|
||||
// pageHasSecurityVerification 负责页码HasSecurityVerification相关处理。
|
||||
// pageHasSecurityVerification 封装页码HasSecurityVerification业务协调。
|
||||
func pageHasSecurityVerification(page playwright.Page) bool {
|
||||
// frame 表示当前遍历过程中的frame
|
||||
for _, frame := range page.Frames() {
|
||||
// lowerURL 保存lowerURL,供当前处理流程使用
|
||||
// lowerURL 用于本次流程后续判断的lowerURL
|
||||
lowerURL := strings.ToLower(frame.URL())
|
||||
// marker 表示当前遍历过程中的marker
|
||||
for _, marker := range []string{"photoverify", "normal_validate", "identity_verify", "baxia-punish", "/punish"} {
|
||||
@@ -515,7 +515,7 @@ func pageHasSecurityVerification(page playwright.Page) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// content、err 保存content、err,供当前处理流程使用
|
||||
// content、err 用于本次流程后续判断的content、err
|
||||
content, err := frame.Content()
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -530,14 +530,14 @@ func pageHasSecurityVerification(page playwright.Page) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// elementVisible 负责elementVisible相关处理。
|
||||
// elementVisible 封装elementVisible业务协调。
|
||||
func elementVisible(el playwright.ElementHandle) bool {
|
||||
// visible、err 保存visible、err,供当前处理流程使用
|
||||
// visible、err 用于本次流程后续判断的visible、err
|
||||
visible, err := el.IsVisible()
|
||||
return err == nil && visible
|
||||
}
|
||||
|
||||
// cleanSingletonFiles 负责cleanSingleton文件列表相关处理。
|
||||
// cleanSingletonFiles 封装cleanSingleton文件列表业务协调。
|
||||
func cleanSingletonFiles(userDataDir string) {
|
||||
// name 表示当前遍历过程中的名称
|
||||
for _, name := range []string{"SingletonLock", "SingletonSocket", "SingletonCookie"} {
|
||||
@@ -545,7 +545,7 @@ func cleanSingletonFiles(userDataDir string) {
|
||||
}
|
||||
}
|
||||
|
||||
// newPersistentRenewContext 负责newPersistentRenew上下文相关处理。
|
||||
// newPersistentRenewContext 封装newPersistentRenew上下文业务协调。
|
||||
func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool, captchaProfile ...bool) (playwright.BrowserContext, func(), error) {
|
||||
// err 表示管理器拒绝新建续期上下文的原因,并用于下面的短路返回。
|
||||
if err := m.beginOperation(ctx); err != nil {
|
||||
@@ -557,13 +557,13 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
finishOperation := func() {
|
||||
operationOnce.Do(m.endOperation)
|
||||
}
|
||||
// lock 保存锁,供当前处理流程使用
|
||||
// lock 用于本次流程后续判断的锁
|
||||
lock := m.accountRenewLock(cookieID)
|
||||
lock.Lock()
|
||||
// unlock 保存unlock,供当前处理流程使用
|
||||
// unlock 用于本次流程后续判断的unlock
|
||||
unlock := func() { lock.Unlock() }
|
||||
|
||||
// releaseSlot、err 保存releaseSlot、err,供当前处理流程使用
|
||||
// releaseSlot、err 用于本次流程后续判断的releaseSlot、err
|
||||
releaseSlot, err := m.acquireRenewSlot(ctx)
|
||||
if err != nil {
|
||||
unlock()
|
||||
@@ -571,7 +571,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.init(); err != nil {
|
||||
releaseSlot()
|
||||
unlock()
|
||||
@@ -579,7 +579,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// userDataDir、err 保存用户数据Dir、err,供当前处理流程使用
|
||||
// userDataDir、err 用于本次流程后续判断的用户数据Dir、err
|
||||
userDataDir, err := resolvePersistentUserDataDir(filepath.Join("browser_data", "user_"+pureUserID(cookieID)))
|
||||
if err != nil {
|
||||
releaseSlot()
|
||||
@@ -588,14 +588,14 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
return nil, nil, err
|
||||
}
|
||||
cleanSingletonFiles(userDataDir)
|
||||
// viewport 保存viewport,供当前处理流程使用
|
||||
// viewport 用于本次流程后续判断的viewport
|
||||
viewport := &playwright.Size{Width: 1280, Height: 720}
|
||||
if len(captchaProfile) > 0 && captchaProfile[0] {
|
||||
viewport = &playwright.Size{Width: 1980, Height: 1024}
|
||||
}
|
||||
// bctx 保存bctx,供当前处理流程使用
|
||||
// bctx 用于本次流程后续判断的bctx
|
||||
var bctx playwright.BrowserContext
|
||||
// lastErr 保存lastErr,供当前处理流程使用
|
||||
// lastErr 用于本次流程后续判断的lastErr
|
||||
var lastErr error
|
||||
// attempt 表示当前持久化 profile 的启动序号;失败后只进行一次清理后的重试。
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
@@ -627,12 +627,12 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
return nil, nil, fmt.Errorf("启动持久化浏览器失败: %w", lastErr)
|
||||
}
|
||||
|
||||
if // err 保存err,供当前处理流程使用
|
||||
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 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := bctx.ClearCookies(); err != nil {
|
||||
_ = bctx.Close()
|
||||
releaseSlot()
|
||||
@@ -640,7 +640,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
finishOperation()
|
||||
return nil, nil, fmt.Errorf("浏览器续期清理旧 Cookie 失败: %w", err)
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := bctx.AddCookies(snapshotToOptionalCookies(snapshot)); err != nil {
|
||||
_ = bctx.Close()
|
||||
releaseSlot()
|
||||
@@ -649,7 +649,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
return nil, nil, fmt.Errorf("浏览器续期注入 Cookie 快照失败: %w", err)
|
||||
}
|
||||
} else if cookieStr != "" {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := addCookieStr(bctx, cookieStr); err != nil {
|
||||
_ = bctx.Close()
|
||||
releaseSlot()
|
||||
@@ -659,7 +659,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
}
|
||||
}
|
||||
|
||||
// release 保存release,供当前处理流程使用
|
||||
// release 用于本次流程后续判断的release
|
||||
release := func() {
|
||||
_ = bctx.Close()
|
||||
releaseSlot()
|
||||
@@ -669,7 +669,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
return bctx, release, nil
|
||||
}
|
||||
|
||||
// quickRenewHeadless 负责quickRenewHeadless相关处理。
|
||||
// quickRenewHeadless 封装quickRenewHeadless业务协调。
|
||||
func quickRenewHeadless(headless bool) bool {
|
||||
return resolveHeadlessRequest(headless)
|
||||
}
|
||||
@@ -682,7 +682,7 @@ func ResolveHeadless(showBrowser bool) bool {
|
||||
return resolveHeadlessRequest(!showBrowser)
|
||||
}
|
||||
|
||||
// resolveHeadlessRequest 负责resolveHeadless请求相关处理。
|
||||
// resolveHeadlessRequest 封装resolveHeadless请求业务协调。
|
||||
func resolveHeadlessRequest(headless bool) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv("BROWSER_HEADLESS"))) {
|
||||
case "true", "1", "yes", "on":
|
||||
@@ -694,18 +694,18 @@ func resolveHeadlessRequest(headless bool) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// cookiesRefreshHeadless 负责cookiesRefreshHeadless相关处理。
|
||||
// cookiesRefreshHeadless 封装cookiesRefreshHeadless业务协调。
|
||||
func cookiesRefreshHeadless(headless bool) bool {
|
||||
return quickRenewHeadless(headless)
|
||||
}
|
||||
|
||||
// pureUserID 负责pure用户ID相关处理。
|
||||
// pureUserID 封装pure用户ID业务协调。
|
||||
func pureUserID(cookieID string) string {
|
||||
cookieID = sanitize(cookieID)
|
||||
// parts 保存parts,供当前处理流程使用
|
||||
// parts 用于本次流程后续判断的parts
|
||||
parts := strings.Split(cookieID, "_")
|
||||
if len(parts) >= 2 {
|
||||
// last 保存last,供当前处理流程使用
|
||||
// last 用于本次流程后续判断的last
|
||||
last := parts[len(parts)-1]
|
||||
if len(last) >= 10 && allDigits(last) {
|
||||
return strings.Join(parts[:len(parts)-1], "_")
|
||||
@@ -717,7 +717,7 @@ func pureUserID(cookieID string) string {
|
||||
return cookieID
|
||||
}
|
||||
|
||||
// allDigits 负责allDigits相关处理。
|
||||
// allDigits 封装allDigits业务协调。
|
||||
func allDigits(s string) bool {
|
||||
if s == "" {
|
||||
return false
|
||||
|
||||
@@ -6,15 +6,15 @@ import (
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
// TestCredentialCookieSnapshotUsesCurrentFlatCookieAsAuthority 负责TestCredential登录凭证SnapshotUsesCurrentFlat登录凭证AsAuthority相关处理。
|
||||
// TestCredentialCookieSnapshotUsesCurrentFlatCookieAsAuthority 封装TestCredential登录凭证SnapshotUsesCurrentFlat登录凭证AsAuthority业务协调。
|
||||
func TestCredentialCookieSnapshotUsesCurrentFlatCookieAsAuthority(t *testing.T) {
|
||||
// existing 保存existing,供当前处理流程使用
|
||||
// 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 用于本次流程后续判断的got
|
||||
got := credentialCookieSnapshot(existing, map[string]string{
|
||||
"session": "fresh",
|
||||
"new": "value",
|
||||
@@ -22,45 +22,45 @@ func TestCredentialCookieSnapshotUsesCurrentFlatCookieAsAuthority(t *testing.T)
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("snapshot len=%d, want 3: %+v", len(got), got)
|
||||
}
|
||||
// byName 保存by名称,供当前处理流程使用
|
||||
// byName 用于本次流程后续判断的by名称
|
||||
byName := make(map[string]cookierefresh.BrowserCookie, len(got))
|
||||
// cookie 表示当前遍历过程中的登录凭证
|
||||
for _, cookie := range got {
|
||||
byName[cookie.Name] = cookie
|
||||
}
|
||||
// session 保存会话,供当前处理流程使用
|
||||
// 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 保存exists,供当前处理流程使用
|
||||
if // exists 用于本次流程后续判断的exists
|
||||
_, exists := byName["removed"]; exists {
|
||||
t.Fatalf("cookie absent from current flat value was resurrected: %+v", got)
|
||||
}
|
||||
if // passport 保存passport,供当前处理流程使用
|
||||
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 用于本次流程后续判断的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相关处理。
|
||||
// TestCredentialCookieSnapshotPreservesAmbiguousSameNameScopes 封装TestCredential登录凭证SnapshotPreservesAmbiguousSame名称Scopes业务协调。
|
||||
func TestCredentialCookieSnapshotPreservesAmbiguousSameNameScopes(t *testing.T) {
|
||||
// existing 保存existing,供当前处理流程使用
|
||||
// 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 用于本次流程后续判断的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 用于本次流程后续判断的values
|
||||
values := map[string]string{}
|
||||
// cookie 表示当前遍历过程中的登录凭证
|
||||
for _, cookie := range got {
|
||||
@@ -71,12 +71,12 @@ func TestCredentialCookieSnapshotPreservesAmbiguousSameNameScopes(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileSnapshotWithCurrentCookie 负责TestReconcileSnapshotWithCurrent登录凭证相关处理。
|
||||
// TestReconcileSnapshotWithCurrentCookie 封装TestReconcileSnapshotWithCurrent登录凭证业务协调。
|
||||
func TestReconcileSnapshotWithCurrentCookie(t *testing.T) {
|
||||
// snapshot 保存snapshot,供当前处理流程使用
|
||||
// snapshot 用于本次流程后续判断的snapshot
|
||||
snapshot := []cookierefresh.BrowserCookie{{Name: "session", Value: "old", Domain: ".goofish.com", Path: "/", Expires: 456}}
|
||||
|
||||
// got 保存got,供当前处理流程使用
|
||||
// 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)
|
||||
@@ -91,13 +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 保存got,供当前处理流程使用
|
||||
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相关处理。
|
||||
// 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")
|
||||
|
||||
+21
-21
@@ -13,12 +13,12 @@ import (
|
||||
|
||||
// parseCookieStr 把 "k=v; k2=v2" 解析为 map。
|
||||
func parseCookieStr(s string) map[string]string {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 用于本次流程后续判断的m
|
||||
m := make(map[string]string)
|
||||
// part 表示当前遍历过程中的part
|
||||
for _, part := range strings.Split(s, ";") {
|
||||
part = strings.TrimSpace(part)
|
||||
if // eq 保存eq,供当前处理流程使用
|
||||
if // eq 用于本次流程后续判断的eq
|
||||
eq := strings.Index(part, "="); eq >= 0 {
|
||||
m[part[:eq]] = part[eq+1:]
|
||||
}
|
||||
@@ -28,7 +28,7 @@ func parseCookieStr(s string) map[string]string {
|
||||
|
||||
// cookieMarshal 把 map 拼成 "k=v; k2=v2"。
|
||||
func cookieMarshal(m map[string]string) string {
|
||||
// parts 保存parts,供当前处理流程使用
|
||||
// parts 用于本次流程后续判断的parts
|
||||
parts := make([]string, 0, len(m))
|
||||
// k、v 表示当前遍历过程中的k、v
|
||||
for k, v := range m {
|
||||
@@ -44,16 +44,16 @@ func MarshalCookies(m map[string]string) string {
|
||||
|
||||
// parseCookieStrToPlaywright 把 cookie 字符串转成 playwright OptionalCookie。
|
||||
func parseCookieStrToPlaywright(s string) []playwright.OptionalCookie {
|
||||
// cookies 保存cookies,供当前处理流程使用
|
||||
// cookies 用于本次流程后续判断的cookies
|
||||
var cookies []playwright.OptionalCookie
|
||||
// part 表示当前遍历过程中的part
|
||||
for _, part := range strings.Split(s, ";") {
|
||||
part = strings.TrimSpace(part)
|
||||
if // eq 保存eq,供当前处理流程使用
|
||||
if // eq 用于本次流程后续判断的eq
|
||||
eq := strings.Index(part, "="); eq >= 0 {
|
||||
// name 保存名称,供当前处理流程使用
|
||||
// name 用于本次流程后续判断的名称
|
||||
name := part[:eq]
|
||||
// value 保存值,供当前处理流程使用
|
||||
// value 用于本次流程后续判断的值
|
||||
value := part[eq+1:]
|
||||
if name == "" {
|
||||
continue
|
||||
@@ -69,23 +69,23 @@ func parseCookieStrToPlaywright(s string) []playwright.OptionalCookie {
|
||||
return cookies
|
||||
}
|
||||
|
||||
// snapshotToOptionalCookies 负责snapshotToOptionalCookies相关处理。
|
||||
// snapshotToOptionalCookies 封装snapshotToOptionalCookies业务协调。
|
||||
func snapshotToOptionalCookies(snapshot []cookierefresh.BrowserCookie) []playwright.OptionalCookie {
|
||||
// out 保存out,供当前处理流程使用
|
||||
// out 用于本次流程后续判断的out
|
||||
var out []playwright.OptionalCookie
|
||||
// c 表示当前遍历过程中的c
|
||||
for _, c := range cookierefresh.NormalizeSnapshot(snapshot) {
|
||||
// domain 保存domain,供当前处理流程使用
|
||||
// domain 用于本次流程后续判断的domain
|
||||
domain := c.Domain
|
||||
if domain == "" {
|
||||
domain = goofishDot
|
||||
}
|
||||
// path 保存路径,供当前处理流程使用
|
||||
// path 用于本次流程后续判断的路径
|
||||
path := c.Path
|
||||
if path == "" {
|
||||
path = "/"
|
||||
}
|
||||
// oc 保存oc,供当前处理流程使用
|
||||
// oc 用于本次流程后续判断的oc
|
||||
oc := playwright.OptionalCookie{
|
||||
Name: c.Name,
|
||||
Value: c.Value,
|
||||
@@ -113,13 +113,13 @@ func snapshotToOptionalCookies(snapshot []cookierefresh.BrowserCookie) []playwri
|
||||
return out
|
||||
}
|
||||
|
||||
// cookieSnapshotFromPlaywright 负责登录凭证SnapshotFromPlaywright相关处理。
|
||||
// cookieSnapshotFromPlaywright 封装登录凭证SnapshotFromPlaywright业务协调。
|
||||
func cookieSnapshotFromPlaywright(cs []playwright.Cookie) []cookierefresh.BrowserCookie {
|
||||
// out 保存out,供当前处理流程使用
|
||||
// out 用于本次流程后续判断的out
|
||||
out := make([]cookierefresh.BrowserCookie, 0, len(cs))
|
||||
// c 表示当前遍历过程中的c
|
||||
for _, c := range cs {
|
||||
// bc 保存bc,供当前处理流程使用
|
||||
// bc 用于本次流程后续判断的bc
|
||||
bc := cookierefresh.BrowserCookie{
|
||||
Name: c.Name,
|
||||
Value: c.Value,
|
||||
@@ -142,7 +142,7 @@ func cookieSnapshotFromPlaywright(cs []playwright.Cookie) []cookierefresh.Browse
|
||||
|
||||
// cookiesToMap 把 playwright Cookie 切片转成 map。
|
||||
func cookiesToMap(cs []playwright.Cookie) map[string]string {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 用于本次流程后续判断的m
|
||||
m := make(map[string]string, len(cs))
|
||||
// c 表示当前遍历过程中的c
|
||||
for _, c := range cs {
|
||||
@@ -154,23 +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,供当前处理流程使用
|
||||
// rng 用于本次流程后续判断的rng
|
||||
var rng = &lockedRand{value: rand.New(rand.NewSource(time.Now().UnixNano()))}
|
||||
|
||||
// lockedRand 保存lockedRand,供当前处理流程使用
|
||||
// lockedRand 用于本次流程后续判断的lockedRand
|
||||
type lockedRand struct {
|
||||
mu sync.Mutex
|
||||
value *rand.Rand
|
||||
}
|
||||
|
||||
// Intn 负责Intn相关处理。
|
||||
// Intn 封装Intn业务协调。
|
||||
func (r *lockedRand) Intn(n int) int {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.value.Intn(n)
|
||||
}
|
||||
|
||||
// Float64 负责Float64相关处理。
|
||||
// Float64 封装Float64业务协调。
|
||||
func (r *lockedRand) Float64() float64 {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
@@ -180,7 +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相关处理。
|
||||
// stealthScript 封装stealthScript业务协调。
|
||||
func stealthScript() string {
|
||||
return stealthTemplate
|
||||
}
|
||||
@@ -5,16 +5,16 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestParseCookieStrRoundTrip 负责TestParse登录凭证StrRoundTrip相关处理。
|
||||
// TestParseCookieStrRoundTrip 封装TestParse登录凭证StrRoundTrip业务协调。
|
||||
func TestParseCookieStrRoundTrip(t *testing.T) {
|
||||
// in 保存in,供当前处理流程使用
|
||||
// in 用于本次流程后续判断的in
|
||||
in := "unb=999; _m_h5_tk=abc_1; cookie2=xyz"
|
||||
// m 保存m,供当前处理流程使用
|
||||
// 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 用于本次流程后续判断的out
|
||||
out := cookieMarshal(m)
|
||||
// 顺序不保证,逐项检查。
|
||||
for _, kv := range []string{"unb=999", "_m_h5_tk=abc_1", "cookie2=xyz"} {
|
||||
@@ -24,14 +24,14 @@ func TestParseCookieStrRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseCookieStrToPlaywright 负责TestParse登录凭证StrToPlaywright相关处理。
|
||||
// TestParseCookieStrToPlaywright 封装TestParse登录凭证StrToPlaywright业务协调。
|
||||
func TestParseCookieStrToPlaywright(t *testing.T) {
|
||||
// cookies 保存cookies,供当前处理流程使用
|
||||
// cookies 用于本次流程后续判断的cookies
|
||||
cookies := parseCookieStrToPlaywright("a=1; b=2")
|
||||
if len(cookies) != 2 {
|
||||
t.Fatalf("每个 Cookie 只应注入一次,got %d", len(cookies))
|
||||
}
|
||||
// domains 保存domains,供当前处理流程使用
|
||||
// domains 用于本次流程后续判断的domains
|
||||
domains := make(map[string]bool)
|
||||
// c 表示当前遍历过程中的c
|
||||
for _, c := range cookies {
|
||||
@@ -48,34 +48,34 @@ func TestParseCookieStrToPlaywright(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseCookieStrEmpty 负责TestParse登录凭证StrEmpty相关处理。
|
||||
// TestParseCookieStrEmpty 封装TestParse登录凭证StrEmpty业务协调。
|
||||
func TestParseCookieStrEmpty(t *testing.T) {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := parseCookieStr(""); len(got) != 0 {
|
||||
t.Fatalf("空串应返回空 map, got %+v", got)
|
||||
}
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := parseCookieStrToPlaywright(",,, ;"); len(got) != 0 {
|
||||
t.Fatalf("无效串应返回空, got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCookiesToMapAndStr 负责TestCookiesToMapAndStr相关处理。
|
||||
// TestCookiesToMapAndStr 封装TestCookiesToMapAndStr业务协调。
|
||||
func TestCookiesToMapAndStr(t *testing.T) {
|
||||
// 用 cookiesToMap/cookiesToStr 覆盖(构造 Cookie 不导出字段,借 parse 间接)。
|
||||
m := map[string]string{"unb": "1", "cna": "xx"}
|
||||
// s 保存s,供当前处理流程使用
|
||||
// s 用于本次流程后续判断的s
|
||||
s := cookieMarshal(m)
|
||||
// m2 保存m2,供当前处理流程使用
|
||||
// m2 用于本次流程后续判断的m2
|
||||
m2 := parseCookieStr(s)
|
||||
if m2["unb"] != "1" || m2["cna"] != "xx" {
|
||||
t.Fatalf("往返异常: %+v", m2)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStealthScriptKeepsNativeFingerprint 负责TestStealthScriptKeepsNativeFingerprint相关处理。
|
||||
// TestStealthScriptKeepsNativeFingerprint 封装TestStealthScriptKeepsNativeFingerprint业务协调。
|
||||
func TestStealthScriptKeepsNativeFingerprint(t *testing.T) {
|
||||
// s 保存s,供当前处理流程使用
|
||||
// s 用于本次流程后续判断的s
|
||||
s := stealthScript()
|
||||
if strings.Contains(s, "{{") {
|
||||
t.Fatalf("stealth 脚本仍有未替换占位符: %q", s[:min(200, len(s))])
|
||||
@@ -91,7 +91,7 @@ func TestStealthScriptKeepsNativeFingerprint(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestStealthScriptStable 负责TestStealthScriptStable相关处理。
|
||||
// TestStealthScriptStable 封装TestStealthScriptStable业务协调。
|
||||
func TestStealthScriptStable(t *testing.T) {
|
||||
if stealthScript() != stealthScript() {
|
||||
t.Fatal("同一浏览器配置不应产生漂移的指纹脚本")
|
||||
|
||||
@@ -15,9 +15,9 @@ import (
|
||||
|
||||
// TestSnapshotToOptionalCookiesPreservesBrowserAttributes 验证完整 Cookie 快照到 Playwright 参数的属性映射。
|
||||
func TestSnapshotToOptionalCookiesPreservesBrowserAttributes(t *testing.T) {
|
||||
// expires 保存过期时间,供当前处理流程使用。
|
||||
// expires 用于本次流程后续判断的过期时间。
|
||||
expires := float64(1700000000)
|
||||
// partitionKey 保存分区键,供当前处理流程使用。
|
||||
// partitionKey 用于本次流程后续判断的分区键。
|
||||
partitionKey := "https://shop.example"
|
||||
// snapshot 保存待转换的浏览器 Cookie 快照。
|
||||
snapshot := []cookierefresh.BrowserCookie{
|
||||
@@ -53,9 +53,9 @@ func TestSnapshotToOptionalCookiesPreservesBrowserAttributes(t *testing.T) {
|
||||
|
||||
// TestCookieSnapshotFromPlaywrightNormalizesFields 验证 Playwright Cookie 可逆转换并补齐默认路径。
|
||||
func TestCookieSnapshotFromPlaywrightNormalizesFields(t *testing.T) {
|
||||
// sameSite 保存 SameSite 属性,供当前处理流程使用。
|
||||
// sameSite 用于本次流程后续判断的 SameSite 属性。
|
||||
sameSite := playwright.SameSiteAttributeLax
|
||||
// partitionKey 保存分区键,供当前处理流程使用。
|
||||
// partitionKey 用于本次流程后续判断的分区键。
|
||||
partitionKey := "https://top.example"
|
||||
// cookies 保存 Playwright 返回的 Cookie 列表。
|
||||
cookies := []playwright.Cookie{
|
||||
|
||||
@@ -13,9 +13,9 @@ import (
|
||||
// TokenCaptchaCookieSnapshot 在滑块引擎退出并释放持久化 Profile 后,重新打开
|
||||
// 同一 Profile 读取最终 Cookie Jar。它不访问任何业务页面,只用于把滑块验证
|
||||
// 已经产生的精确 Domain/Path/HttpOnly/Expires 属性交回 Go 凭证层。
|
||||
// TokenCaptchaCookieSnapshot 负责令牌Captcha登录凭证Snapshot相关处理。
|
||||
// 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 用于本次流程后续判断的bctx、release、err
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, "", nil, quickRenewHeadless(headless), true)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
@@ -26,12 +26,12 @@ func (m *Manager) TokenCaptchaCookieSnapshot(ctx context.Context, cookieID strin
|
||||
|
||||
// syncCredentialCookies 为 token 滑块上下文同步 Cookie。普通登录、
|
||||
// 续期、MTOP、Token 和 WebSocket 生产流程不得调用 Chromium。
|
||||
// syncCredentialCookies 负责syncCredentialCookies相关处理。
|
||||
// syncCredentialCookies 封装syncCredentialCookies业务协调。
|
||||
func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string, snapshots ...[]cookierefresh.BrowserCookie) error {
|
||||
if len(snapshots) > 0 && snapshots[0] != nil {
|
||||
// preserved 保存preserved,供当前处理流程使用
|
||||
// preserved 用于本次流程后续判断的preserved
|
||||
preserved := cookierefresh.NormalizeSnapshot(snapshots[0])
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := bctx.ClearCookies(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -40,37 +40,37 @@ func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string, sna
|
||||
}
|
||||
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
|
||||
}
|
||||
// incoming 保存incoming,供当前处理流程使用
|
||||
// incoming 用于本次流程后续判断的incoming
|
||||
incoming := parseCookieStr(cookieStr)
|
||||
if len(incoming) == 0 {
|
||||
return fmt.Errorf("Cookie为空或格式错误")
|
||||
}
|
||||
// existing、err 保存existing、err,供当前处理流程使用
|
||||
// existing、err 用于本次流程后续判断的existing、err
|
||||
existing, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// preserved 保存preserved,供当前处理流程使用
|
||||
// preserved 用于本次流程后续判断的preserved
|
||||
preserved := credentialCookieSnapshotForURL(cookieSnapshotFromPlaywright(existing), incoming, goofishIMURL)
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := bctx.ClearCookies(); err != nil {
|
||||
return err
|
||||
}
|
||||
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
|
||||
}
|
||||
|
||||
// credentialCookieSnapshot 负责credential登录凭证Snapshot相关处理。
|
||||
// credentialCookieSnapshot 封装credential登录凭证Snapshot业务协调。
|
||||
func credentialCookieSnapshot(existing []cookierefresh.BrowserCookie, incoming map[string]string) []cookierefresh.BrowserCookie {
|
||||
return credentialCookieSnapshotForURL(existing, incoming, goofishIMURL)
|
||||
}
|
||||
|
||||
// credentialCookieSnapshotForURL 负责credential登录凭证SnapshotForURL相关处理。
|
||||
// credentialCookieSnapshotForURL 封装credential登录凭证SnapshotForURL业务协调。
|
||||
func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, incoming map[string]string, rawURL string) []cookierefresh.BrowserCookie {
|
||||
// preserved 保存preserved,供当前处理流程使用
|
||||
// preserved 用于本次流程后续判断的preserved
|
||||
preserved := make([]cookierefresh.BrowserCookie, 0, len(existing)+len(incoming))
|
||||
// matched 保存matched,供当前处理流程使用
|
||||
// matched 用于本次流程后续判断的matched
|
||||
matched := make(map[string]bool, len(incoming))
|
||||
// counts 保存counts,供当前处理流程使用
|
||||
// counts 用于本次流程后续判断的counts
|
||||
counts := make(map[string]int, len(existing))
|
||||
// cookie 表示当前遍历过程中的登录凭证
|
||||
for _, cookie := range cookierefresh.NormalizeSnapshot(existing) {
|
||||
@@ -79,7 +79,7 @@ func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, inco
|
||||
// cookie 表示当前遍历过程中的登录凭证
|
||||
for _, cookie := range existing {
|
||||
if !cookieScopeMatches(cookie, rawURL) {
|
||||
if // value、ok 保存value、ok,供当前处理流程使用
|
||||
if // value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := incoming[cookie.Name]; ok {
|
||||
if counts[cookie.Name] == 1 && cookie.PartitionKey == "" {
|
||||
cookie.Value = value
|
||||
@@ -89,7 +89,7 @@ func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, inco
|
||||
preserved = append(preserved, cookie)
|
||||
continue
|
||||
}
|
||||
// value、ok 保存value、ok,供当前处理流程使用
|
||||
// value、ok 用于本次流程后续判断的value、ok
|
||||
value, ok := incoming[cookie.Name]
|
||||
if !ok {
|
||||
continue
|
||||
@@ -112,16 +112,16 @@ func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, inco
|
||||
return cookierefresh.NormalizeSnapshot(preserved)
|
||||
}
|
||||
|
||||
// cookieScopeMatches 负责登录凭证ScopeMatches相关处理。
|
||||
// cookieScopeMatches 封装登录凭证ScopeMatches业务协调。
|
||||
func cookieScopeMatches(cookie cookierefresh.BrowserCookie, rawURL string) bool {
|
||||
// header 保存header,供当前处理流程使用
|
||||
// header 用于本次流程后续判断的header
|
||||
header, _ := cookierefresh.ScopedCookieHeaderForRequest([]cookierefresh.BrowserCookie{cookie}, rawURL, "https://goofish.com", time.Unix(0, 0))
|
||||
return header != ""
|
||||
}
|
||||
|
||||
// currentCookieHeader 负责current登录凭证Header相关处理。
|
||||
// currentCookieHeader 封装current登录凭证Header业务协调。
|
||||
func currentCookieHeader(snapshot []cookierefresh.BrowserCookie, rawURL string) string {
|
||||
// header 保存header,供当前处理流程使用
|
||||
// header 用于本次流程后续判断的header
|
||||
header, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, rawURL, "https://goofish.com", time.Now())
|
||||
return header
|
||||
}
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
)
|
||||
|
||||
// 默认 UA、语言、时区与视口。
|
||||
// defaultW 保存defaultW,供当前处理流程使用
|
||||
// defaultW 用于本次流程后续判断的defaultW
|
||||
const (
|
||||
defaultW = 1920
|
||||
defaultH = 1080
|
||||
@@ -90,16 +90,16 @@ func captchaBrowserProxy() string {
|
||||
}
|
||||
}
|
||||
|
||||
// chromiumExecutablePath 负责chromiumExecutable路径相关处理。
|
||||
// chromiumExecutablePath 封装chromiumExecutable路径业务协调。
|
||||
func chromiumExecutablePath() *string {
|
||||
if // path 保存路径,供当前处理流程使用
|
||||
if // path 用于本次流程后续判断的路径
|
||||
path := strings.TrimSpace(os.Getenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH")); path != "" {
|
||||
return playwright.String(path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// skipPlaywrightBrowserDownload 负责skipPlaywright浏览器Download相关处理。
|
||||
// skipPlaywrightBrowserDownload 封装skipPlaywright浏览器Download业务协调。
|
||||
func skipPlaywrightBrowserDownload() bool {
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD"))) {
|
||||
case "1", "true", "yes", "on":
|
||||
@@ -109,53 +109,53 @@ func skipPlaywrightBrowserDownload() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// packagedPlaywrightRuntimeReady 负责packagedPlaywrightRuntimeReady相关处理。
|
||||
// packagedPlaywrightRuntimeReady 封装packagedPlaywrightRuntimeReady业务协调。
|
||||
func packagedPlaywrightRuntimeReady() bool {
|
||||
// driverDir 保存driverDir,供当前处理流程使用
|
||||
// driverDir 用于本次流程后续判断的driverDir
|
||||
driverDir := strings.TrimSpace(os.Getenv("PLAYWRIGHT_DRIVER_PATH"))
|
||||
if driverDir == "" {
|
||||
return false
|
||||
}
|
||||
// nodeReady 保存nodeReady,供当前处理流程使用
|
||||
// nodeReady 用于本次流程后续判断的nodeReady
|
||||
nodeReady := false
|
||||
if // nodePath 保存node路径,供当前处理流程使用
|
||||
if // nodePath 用于本次流程后续判断的node路径
|
||||
nodePath := strings.TrimSpace(os.Getenv("PLAYWRIGHT_NODEJS_PATH")); nodePath != "" {
|
||||
// err 保存err,供当前处理流程使用
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := os.Stat(nodePath)
|
||||
nodeReady = err == nil
|
||||
} else {
|
||||
// nodeName 保存node名称,供当前处理流程使用
|
||||
// nodeName 用于本次流程后续判断的node名称
|
||||
nodeName := "node"
|
||||
if runtime.GOOS == "windows" {
|
||||
nodeName = "node.exe"
|
||||
}
|
||||
// err 保存err,供当前处理流程使用
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := os.Stat(filepath.Join(driverDir, nodeName))
|
||||
nodeReady = err == nil
|
||||
}
|
||||
if !nodeReady {
|
||||
return false
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
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 用于本次流程后续判断的浏览器Dir
|
||||
browserDir := strings.TrimSpace(os.Getenv("PLAYWRIGHT_BROWSERS_PATH"))
|
||||
if browserDir == "" {
|
||||
return false
|
||||
}
|
||||
// matches、err 保存matches、err,供当前处理流程使用
|
||||
// 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 保存info、statErr,供当前处理流程使用
|
||||
if // info、statErr 用于本次流程后续判断的info、statErr
|
||||
info, statErr := os.Stat(match); statErr == nil && info.IsDir() {
|
||||
return true
|
||||
}
|
||||
@@ -214,7 +214,7 @@ type Manager struct {
|
||||
tokenCaptchaFallbackFn tokenCaptchaEngineFunc
|
||||
}
|
||||
|
||||
// poolEntry 保存poolEntry,供当前处理流程使用
|
||||
// poolEntry 用于本次流程后续判断的poolEntry
|
||||
type poolEntry struct {
|
||||
cookieID string
|
||||
browser playwright.Browser
|
||||
@@ -241,7 +241,7 @@ func NewManager(logger *slog.Logger) *Manager {
|
||||
if packagedPlaywrightRuntimeReady() {
|
||||
return nil
|
||||
}
|
||||
// opts 保存opts,供当前处理流程使用
|
||||
// opts 用于本次流程后续判断的opts
|
||||
opts := &playwright.RunOptions{
|
||||
Browsers: []string{"chromium"},
|
||||
Verbose: false,
|
||||
@@ -299,14 +299,14 @@ func (m *Manager) ensureLifecycleCond() {
|
||||
m.lifecycleMu.Unlock()
|
||||
}
|
||||
|
||||
// accountRenewLock 负责账号Renew锁相关处理。
|
||||
// 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 用于本次流程后续判断的锁
|
||||
lock := m.renewLocks[cookieID]
|
||||
if lock == nil {
|
||||
lock = &sync.Mutex{}
|
||||
@@ -315,7 +315,7 @@ func (m *Manager) accountRenewLock(cookieID string) *sync.Mutex {
|
||||
return lock
|
||||
}
|
||||
|
||||
// acquireRenewSlot 负责acquireRenewSlot相关处理。
|
||||
// acquireRenewSlot 封装acquireRenewSlot业务协调。
|
||||
func (m *Manager) acquireRenewSlot(ctx context.Context) (func(), error) {
|
||||
if m.renewSlots == nil {
|
||||
m.renewSlots = make(chan struct{}, 3)
|
||||
@@ -331,19 +331,19 @@ func (m *Manager) acquireRenewSlot(ctx context.Context) (func(), error) {
|
||||
// init 懒加载 playwright(首次调用时下载 driver + chromium)。
|
||||
func (m *Manager) init() error {
|
||||
m.once.Do(func() {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
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 用于本次流程后续判断的pw、err
|
||||
pw, err := m.runFn()
|
||||
if err != nil {
|
||||
m.initErr = fmt.Errorf("启动 playwright 失败: %w", err)
|
||||
return
|
||||
}
|
||||
m.pw = pw
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.detectBrowserFingerprint(); err != nil {
|
||||
m.initErr = fmt.Errorf("读取 Playwright Chromium 原生指纹失败: %w", err)
|
||||
_ = pw.Stop()
|
||||
@@ -358,7 +358,7 @@ 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相关处理。
|
||||
// Initialize 封装Initialize业务协调。
|
||||
func (m *Manager) Initialize() error {
|
||||
// err 表示管理器已进入关闭流程,不能继续初始化 Playwright。
|
||||
if err := m.beginOperation(context.Background()); err != nil {
|
||||
@@ -368,11 +368,11 @@ func (m *Manager) Initialize() error {
|
||||
return m.init()
|
||||
}
|
||||
|
||||
// detectBrowserFingerprint 负责detect浏览器Fingerprint相关处理。
|
||||
// detectBrowserFingerprint 封装detect浏览器Fingerprint业务协调。
|
||||
func (m *Manager) detectBrowserFingerprint() error {
|
||||
// observed 保存observed,供当前处理流程使用
|
||||
// observed 用于本次流程后续判断的observed
|
||||
observed := make(chan http.Header, 1)
|
||||
// server 保存server,供当前处理流程使用
|
||||
// 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")
|
||||
@@ -380,7 +380,7 @@ func (m *Manager) detectBrowserFingerprint() error {
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
// b、err 保存b、err,供当前处理流程使用
|
||||
// b、err 用于本次流程后续判断的b、err
|
||||
b, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(true),
|
||||
Args: chromiumLaunchArgs(),
|
||||
@@ -390,22 +390,22 @@ func (m *Manager) detectBrowserFingerprint() error {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = b.Close() }()
|
||||
// ctx、err 保存ctx、err,供当前处理流程使用
|
||||
// ctx、err 用于本次流程后续判断的ctx、err
|
||||
ctx, err := b.NewContext()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = ctx.Close() }()
|
||||
// page、err 保存page、err,供当前处理流程使用
|
||||
// page、err 用于本次流程后续判断的page、err
|
||||
page, err := ctx.NewPage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := page.Goto(server.URL, playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil {
|
||||
return err
|
||||
}
|
||||
// headers 保存headers,供当前处理流程使用
|
||||
// headers 用于本次流程后续判断的headers
|
||||
var headers http.Header
|
||||
select {
|
||||
case headers = <-observed:
|
||||
@@ -680,7 +680,7 @@ func (m *Manager) CloseContext(ctx context.Context) error {
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
// entries 保存entries,供当前处理流程使用
|
||||
// entries 用于本次流程后续判断的entries
|
||||
entries := make([]*poolEntry, 0, len(m.pool))
|
||||
// e 表示当前遍历过程中的e
|
||||
for _, e := range m.pool {
|
||||
@@ -706,7 +706,7 @@ func (m *Manager) CloseContext(ctx context.Context) error {
|
||||
|
||||
// newPage 从池中取(或创建)一个 context,返回新 page + 释放函数。
|
||||
// 每次请求新建 page,避免并发导航冲突(与 browser_pool.get_browser 一致)。
|
||||
// newPage 负责new页码相关处理。
|
||||
// newPage 封装new页码业务协调。
|
||||
func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headless bool) (playwright.Page, func(), error) {
|
||||
// err 表示管理器已关闭或调用方已取消,不能继续申请浏览器页。
|
||||
if err := m.beginOperation(ctx); err != nil {
|
||||
@@ -718,12 +718,12 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
|
||||
finishOperation := func() {
|
||||
operationOnce.Do(m.endOperation)
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.init(); err != nil {
|
||||
finishOperation()
|
||||
return nil, nil, err
|
||||
}
|
||||
// entry、err 保存entry、err,供当前处理流程使用
|
||||
// entry、err 用于本次流程后续判断的entry、err
|
||||
entry, err := m.acquireEntry(cookieID, cookieStr, headless)
|
||||
if err != nil {
|
||||
finishOperation()
|
||||
@@ -748,7 +748,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
|
||||
return nil, nil, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
}
|
||||
// release 保存release,供当前处理流程使用
|
||||
// release 用于本次流程后续判断的release
|
||||
release := func() {
|
||||
_ = page.Close()
|
||||
m.releaseEntry(cookieID, entry)
|
||||
@@ -757,10 +757,10 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
|
||||
return page, release, nil
|
||||
}
|
||||
|
||||
// acquireEntry 负责acquireEntry相关处理。
|
||||
// acquireEntry 封装acquireEntry业务协调。
|
||||
func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
|
||||
m.mu.Lock()
|
||||
if // e、ok 保存e、ok,供当前处理流程使用
|
||||
if // e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
|
||||
m.claimEntryLocked(e)
|
||||
m.mu.Unlock()
|
||||
@@ -768,10 +768,10 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
// created、err 保存created、err,供当前处理流程使用
|
||||
// created、err 用于本次流程后续判断的created、err
|
||||
created, err, _ := m.creates.Do(cookieID, func() (any, error) {
|
||||
m.mu.Lock()
|
||||
if // e、ok 保存e、ok,供当前处理流程使用
|
||||
if // e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
|
||||
m.mu.Unlock()
|
||||
return e, nil
|
||||
@@ -784,13 +784,13 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// entry、ok 保存entry、ok,供当前处理流程使用
|
||||
// entry、ok 用于本次流程后续判断的entry、ok
|
||||
entry, ok := created.(*poolEntry)
|
||||
if !ok || entry == nil {
|
||||
return nil, fmt.Errorf("浏览器池创建返回异常")
|
||||
}
|
||||
m.mu.Lock()
|
||||
if // current 保存current,供当前处理流程使用
|
||||
if // current 用于本次流程后续判断的current
|
||||
current := m.pool[cookieID]; current == entry {
|
||||
m.claimEntryLocked(entry)
|
||||
m.mu.Unlock()
|
||||
@@ -801,7 +801,7 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// claimEntryLocked 负责claimEntryLocked相关处理。
|
||||
// claimEntryLocked 封装claimEntryLocked业务协调。
|
||||
func (m *Manager) claimEntryLocked(entry *poolEntry) {
|
||||
entry.lastUsed = time.Now()
|
||||
if entry.initialLeaseAvailable {
|
||||
@@ -811,11 +811,11 @@ func (m *Manager) claimEntryLocked(entry *poolEntry) {
|
||||
entry.active++
|
||||
}
|
||||
|
||||
// releaseEntry 负责releaseEntry相关处理。
|
||||
// releaseEntry 封装releaseEntry业务协调。
|
||||
func (m *Manager) releaseEntry(cookieID string, entry *poolEntry) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if // current 保存current,供当前处理流程使用
|
||||
if // current 用于本次流程后续判断的current
|
||||
current := m.pool[cookieID]; current != entry {
|
||||
return
|
||||
}
|
||||
@@ -825,9 +825,9 @@ func (m *Manager) releaseEntry(cookieID string, entry *poolEntry) {
|
||||
entry.lastUsed = time.Now()
|
||||
}
|
||||
|
||||
// createEntry 负责createEntry相关处理。
|
||||
// createEntry 封装createEntry业务协调。
|
||||
func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
|
||||
// browser、err 保存browser、err,供当前处理流程使用
|
||||
// browser、err 用于本次流程后续判断的browser、err
|
||||
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(headless),
|
||||
Args: chromiumLaunchArgs(),
|
||||
@@ -851,19 +851,19 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
|
||||
_ = browser.Close()
|
||||
return nil, fmt.Errorf("创建 context 失败: %w", err)
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := context.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
|
||||
m.logger.Warn("注入 stealth 脚本失败", "err", err)
|
||||
}
|
||||
if cookieStr != "" {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := addCookieStr(context, cookieStr); err != nil {
|
||||
_ = context.Close()
|
||||
_ = browser.Close()
|
||||
return nil, fmt.Errorf("注入 cookie 失败: %w", err)
|
||||
}
|
||||
}
|
||||
// entry 保存entry,供当前处理流程使用
|
||||
// entry 用于本次流程后续判断的entry
|
||||
entry := &poolEntry{
|
||||
cookieID: cookieID,
|
||||
browser: browser,
|
||||
@@ -878,20 +878,20 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// touch 负责touch相关处理。
|
||||
// touch 封装touch业务协调。
|
||||
func (m *Manager) touch(cookieID string) {
|
||||
m.mu.Lock()
|
||||
if // e、ok 保存e、ok,供当前处理流程使用
|
||||
if // e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]; ok {
|
||||
e.lastUsed = time.Now()
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// evict 负责evict相关处理。
|
||||
// evict 封装evict业务协调。
|
||||
func (m *Manager) evict(cookieID string) {
|
||||
m.mu.Lock()
|
||||
// e、ok 保存e、ok,供当前处理流程使用
|
||||
// e、ok 用于本次流程后续判断的e、ok
|
||||
e, ok := m.pool[cookieID]
|
||||
if ok && e.active > 0 {
|
||||
m.mu.Unlock()
|
||||
@@ -904,16 +904,16 @@ func (m *Manager) evict(cookieID string) {
|
||||
}
|
||||
}
|
||||
|
||||
// evictIfNeeded 负责evictIfNeeded相关处理。
|
||||
// evictIfNeeded 封装evictIfNeeded业务协调。
|
||||
func (m *Manager) evictIfNeeded() {
|
||||
m.mu.Lock()
|
||||
if len(m.pool) < m.maxSize {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
// oldest 保存oldest,供当前处理流程使用
|
||||
// oldest 用于本次流程后续判断的oldest
|
||||
var oldest *poolEntry
|
||||
// oldestID 保存oldestID,供当前处理流程使用
|
||||
// oldestID 用于本次流程后续判断的oldestID
|
||||
var oldestID string
|
||||
// id、e 表示当前遍历过程中的id、e
|
||||
for id, e := range m.pool {
|
||||
@@ -936,10 +936,10 @@ func (m *Manager) evictIfNeeded() {
|
||||
|
||||
// CleanupIdle 清理超过 idleTTL 未用的浏览器。
|
||||
func (m *Manager) CleanupIdle() {
|
||||
// now 保存now,供当前处理流程使用
|
||||
// now 用于本次流程后续判断的now
|
||||
now := time.Now()
|
||||
m.mu.Lock()
|
||||
// toClose 保存toClose,供当前处理流程使用
|
||||
// toClose 用于本次流程后续判断的toClose
|
||||
var toClose []*poolEntry
|
||||
// id、e 表示当前遍历过程中的id、e
|
||||
for id, e := range m.pool {
|
||||
@@ -955,7 +955,7 @@ func (m *Manager) CleanupIdle() {
|
||||
}
|
||||
}
|
||||
|
||||
// closeEntry 负责closeEntry相关处理。
|
||||
// closeEntry 封装closeEntry业务协调。
|
||||
func closeEntry(e *poolEntry, logger *slog.Logger) {
|
||||
if e == nil {
|
||||
return
|
||||
@@ -970,12 +970,12 @@ 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 用于本次流程后续判断的cookies
|
||||
cookies := parseCookieStrToPlaywright(cookieStr)
|
||||
if len(cookies) == 0 {
|
||||
return errors.New("cookie 为空或格式错误")
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := ctx.ClearCookies(); err != nil {
|
||||
return fmt.Errorf("清理浏览器旧 cookie: %w", err)
|
||||
}
|
||||
|
||||
@@ -93,16 +93,16 @@ func TestManagerCloseContextWithoutOperations(t *testing.T) {
|
||||
|
||||
// TestChromiumLaunchArgs 验证启动参数含关键安全/反检测项。
|
||||
func TestChromiumLaunchArgs(t *testing.T) {
|
||||
// args 保存args,供当前处理流程使用
|
||||
// args 用于本次流程后续判断的args
|
||||
args := chromiumLaunchArgs()
|
||||
if len(args) == 0 {
|
||||
t.Fatal("应返回非空参数列表")
|
||||
}
|
||||
// want 保存want,供当前处理流程使用
|
||||
// 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 用于本次流程后续判断的found
|
||||
found := false
|
||||
// a 表示当前遍历过程中的a
|
||||
for _, a := range args {
|
||||
@@ -117,23 +117,23 @@ func TestChromiumLaunchArgs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPackagedPlaywrightRuntimeReady 负责TestPackagedPlaywrightRuntimeReady相关处理。
|
||||
// TestPackagedPlaywrightRuntimeReady 封装TestPackagedPlaywrightRuntimeReady业务协调。
|
||||
func TestPackagedPlaywrightRuntimeReady(t *testing.T) {
|
||||
// runtimeRoot 保存runtimeRoot,供当前处理流程使用
|
||||
// runtimeRoot 用于本次流程后续判断的runtimeRoot
|
||||
runtimeRoot := t.TempDir()
|
||||
// driverDir 保存driverDir,供当前处理流程使用
|
||||
// driverDir 用于本次流程后续判断的driverDir
|
||||
driverDir := filepath.Join(runtimeRoot, "driver")
|
||||
// browserDir 保存浏览器Dir,供当前处理流程使用
|
||||
// browserDir 用于本次流程后续判断的浏览器Dir
|
||||
browserDir := filepath.Join(runtimeRoot, "browsers")
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := os.MkdirAll(filepath.Join(driverDir, "package"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := os.MkdirAll(filepath.Join(browserDir, "chromium-1228"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// nodeName 保存node名称,供当前处理流程使用
|
||||
// nodeName 用于本次流程后续判断的node名称
|
||||
nodeName := "node"
|
||||
if runtime.GOOS == "windows" {
|
||||
nodeName = "node.exe"
|
||||
@@ -143,7 +143,7 @@ func TestPackagedPlaywrightRuntimeReady(t *testing.T) {
|
||||
filepath.Join(driverDir, nodeName),
|
||||
filepath.Join(driverDir, "package", "cli.js"),
|
||||
} {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := os.WriteFile(path, []byte("runtime"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -156,29 +156,29 @@ func TestPackagedPlaywrightRuntimeReady(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPackagedPlaywrightRuntimeReadyWithExternalNode 负责TestPackagedPlaywrightRuntimeReadyWithExternalNode相关处理。
|
||||
// TestPackagedPlaywrightRuntimeReadyWithExternalNode 封装TestPackagedPlaywrightRuntimeReadyWithExternalNode业务协调。
|
||||
func TestPackagedPlaywrightRuntimeReadyWithExternalNode(t *testing.T) {
|
||||
// runtimeRoot 保存runtimeRoot,供当前处理流程使用
|
||||
// runtimeRoot 用于本次流程后续判断的runtimeRoot
|
||||
runtimeRoot := t.TempDir()
|
||||
// driverDir 保存driverDir,供当前处理流程使用
|
||||
// driverDir 用于本次流程后续判断的driverDir
|
||||
driverDir := filepath.Join(runtimeRoot, "driver")
|
||||
// browserDir 保存浏览器Dir,供当前处理流程使用
|
||||
// browserDir 用于本次流程后续判断的浏览器Dir
|
||||
browserDir := filepath.Join(runtimeRoot, "browsers")
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := os.MkdirAll(filepath.Join(driverDir, "package"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := os.MkdirAll(filepath.Join(browserDir, "chromium-1228"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := os.WriteFile(filepath.Join(driverDir, "package", "cli.js"), []byte("runtime"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// nodePath 保存node路径,供当前处理流程使用
|
||||
// nodePath 用于本次流程后续判断的node路径
|
||||
nodePath := filepath.Join(runtimeRoot, "node")
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := os.WriteFile(nodePath, []byte("runtime"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -203,9 +203,9 @@ func newTestManager(maxSize int) *Manager {
|
||||
|
||||
// TestTouchUpdatesLastUsed touch 命中池中条目时更新 lastUsed。
|
||||
func TestTouchUpdatesLastUsed(t *testing.T) {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 用于本次流程后续判断的m
|
||||
m := newTestManager(3)
|
||||
// old 保存old,供当前处理流程使用
|
||||
// old 用于本次流程后续判断的old
|
||||
old := time.Now().Add(-time.Hour)
|
||||
m.pool["c1"] = &poolEntry{cookieID: "c1", lastUsed: old}
|
||||
m.touch("c1")
|
||||
@@ -218,16 +218,16 @@ func TestTouchUpdatesLastUsed(t *testing.T) {
|
||||
|
||||
// TestEvictRemovesEntry evict 删除指定条目(nil browser 时 closeEntry 为 no-op)。
|
||||
func TestEvictRemovesEntry(t *testing.T) {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 用于本次流程后续判断的m
|
||||
m := newTestManager(3)
|
||||
m.pool["c1"] = &poolEntry{cookieID: "c1"}
|
||||
m.pool["c2"] = &poolEntry{cookieID: "c2"}
|
||||
m.evict("c1")
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
_, ok := m.pool["c1"]; ok {
|
||||
t.Fatal("evict 应删除 c1")
|
||||
}
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
_, ok := m.pool["c2"]; !ok {
|
||||
t.Fatal("c2 应保留")
|
||||
}
|
||||
@@ -237,7 +237,7 @@ func TestEvictRemovesEntry(t *testing.T) {
|
||||
|
||||
// TestEvictIfNeededEvictsOldest 池满时驱逐最久未用的条目。
|
||||
func TestEvictIfNeededEvictsOldest(t *testing.T) {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// 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()}
|
||||
@@ -245,7 +245,7 @@ func TestEvictIfNeededEvictsOldest(t *testing.T) {
|
||||
if _, ok := m.pool["c1"]; ok {
|
||||
t.Fatal("应驱逐最旧的 c1")
|
||||
}
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
_, ok := m.pool["c2"]; !ok {
|
||||
t.Fatal("c2 应保留")
|
||||
}
|
||||
@@ -253,36 +253,36 @@ func TestEvictIfNeededEvictsOldest(t *testing.T) {
|
||||
|
||||
// TestEvictIfNeededNoopWhenUnderLimit 池未满时不驱逐。
|
||||
func TestEvictIfNeededNoopWhenUnderLimit(t *testing.T) {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 用于本次流程后续判断的m
|
||||
m := newTestManager(5)
|
||||
m.pool["c1"] = &poolEntry{cookieID: "c1", lastUsed: time.Now()}
|
||||
m.evictIfNeeded()
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
_, ok := m.pool["c1"]; !ok {
|
||||
t.Fatal("未满不应驱逐")
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvictIfNeededSkipsActiveEntries 负责TestEvictIfNeededSkipsActiveEntries相关处理。
|
||||
// TestEvictIfNeededSkipsActiveEntries 封装TestEvictIfNeededSkipsActiveEntries业务协调。
|
||||
func TestEvictIfNeededSkipsActiveEntries(t *testing.T) {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// 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 保存ok,供当前处理流程使用
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
_, ok := m.pool["active-old"]; !ok {
|
||||
t.Fatal("正在执行 token 请求的条目不得被淘汰")
|
||||
}
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
_, ok := m.pool["idle-new"]; ok {
|
||||
t.Fatal("池满时应优先淘汰空闲条目")
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive 负责TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive相关处理。
|
||||
// TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive 封装TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive业务协调。
|
||||
func TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive(t *testing.T) {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// 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}
|
||||
@@ -292,21 +292,21 @@ func TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCleanupIdleSkipsActiveEntries 负责TestCleanupIdleSkipsActiveEntries相关处理。
|
||||
// TestCleanupIdleSkipsActiveEntries 封装TestCleanupIdleSkipsActiveEntries业务协调。
|
||||
func TestCleanupIdleSkipsActiveEntries(t *testing.T) {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 用于本次流程后续判断的m
|
||||
m := newTestManager(3)
|
||||
m.idleTTL = time.Minute
|
||||
// old 保存old,供当前处理流程使用
|
||||
// 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 保存ok,供当前处理流程使用
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
_, ok := m.pool["active"]; !ok {
|
||||
t.Fatal("CleanupIdle 不得关闭仍有租约的条目")
|
||||
}
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
_, ok := m.pool["idle"]; ok {
|
||||
t.Fatal("CleanupIdle 应清理过期空闲条目")
|
||||
}
|
||||
@@ -314,7 +314,7 @@ func TestCleanupIdleSkipsActiveEntries(t *testing.T) {
|
||||
|
||||
// TestMarshalCookies 导出包装器等价 cookieMarshal。
|
||||
func TestMarshalCookies(t *testing.T) {
|
||||
// got 保存got,供当前处理流程使用
|
||||
// got 用于本次流程后续判断的got
|
||||
got := MarshalCookies(map[string]string{"unb": "1", "cna": "xx"})
|
||||
// map 顺序不保证,逐项检查。
|
||||
if !contains(got, "unb=1") || !contains(got, "cna=xx") {
|
||||
@@ -324,12 +324,12 @@ func TestMarshalCookies(t *testing.T) {
|
||||
|
||||
// TestCookiesToMap playwright.Cookie 切片转 map。
|
||||
func TestCookiesToMap(t *testing.T) {
|
||||
// cs 保存cs,供当前处理流程使用
|
||||
// cs 用于本次流程后续判断的cs
|
||||
cs := []playwright.Cookie{
|
||||
{Name: "unb", Value: "123"},
|
||||
{Name: "_m_h5_tk", Value: "tok"},
|
||||
}
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 用于本次流程后续判断的m
|
||||
m := cookiesToMap(cs)
|
||||
if m["unb"] != "123" || m["_m_h5_tk"] != "tok" || len(m) != 2 {
|
||||
t.Fatalf("cookiesToMap=%+v", m)
|
||||
@@ -340,9 +340,9 @@ func TestCookiesToMap(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// contains 负责contains相关处理。
|
||||
// contains 封装contains业务协调。
|
||||
func contains(s, sub string) bool {
|
||||
for // i 保存i,供当前处理流程使用
|
||||
for // i 用于本次流程后续判断的i
|
||||
i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
|
||||
+58
-58
@@ -16,7 +16,7 @@ import (
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// mtopOrderDetailURL 保存mtop订单DetailURL,供当前处理流程使用
|
||||
// mtopOrderDetailURL 用于本次流程后续判断的mtop订单DetailURL
|
||||
const mtopOrderDetailURL = "mtop.idle.web.trade.order.detail"
|
||||
|
||||
// OrderDetail 订单详情(对齐 engine.OrderDetail)。
|
||||
@@ -41,9 +41,9 @@ var orderStatusMap = map[int]string{
|
||||
|
||||
// FetchOrderDetail 用浏览器抓取单个订单详情。
|
||||
// 移植自 utils/order_fetcher_optimized.py fetch_order_complete。
|
||||
// FetchOrderDetail 负责Fetch订单Detail相关处理。
|
||||
// FetchOrderDetail 封装Fetch订单Detail业务协调。
|
||||
func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cookieValue string, requireSpec ...bool) (*OrderDetail, error) {
|
||||
// needsSpec 保存needsSpec,供当前处理流程使用
|
||||
// needsSpec 用于本次流程后续判断的needsSpec
|
||||
needsSpec := len(requireSpec) > 0 && requireSpec[0]
|
||||
// 优先调用稳定的 MTop 详情接口;页面自动化只作为规格字段的兼容兜底。
|
||||
if direct, directErr := mtop.NewClient().FetchOrderDetail(ctx, cookieValue, orderID); directErr == nil && direct != nil && direct.Amount != "" &&
|
||||
@@ -58,45 +58,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 用于本次流程后续判断的浏览器Credential锁
|
||||
browserCredentialLock := m.accountRenewLock("order_credential_" + cookieID)
|
||||
browserCredentialLock.Lock()
|
||||
defer browserCredentialLock.Unlock()
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.init(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// page、release、err 保存page、release、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 保存会话,供当前处理流程使用
|
||||
if // session 用于本次流程后续判断的会话
|
||||
session := mtop.CookieSessionFromContext(ctx); session != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := syncCredentialCookies(page.Context(), cookieValue, session.Snapshot()); err != nil {
|
||||
return nil, fmt.Errorf("订单详情同步完整 Cookie Jar: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// mu 保存mu,供当前处理流程使用
|
||||
// mu 用于本次流程后续判断的mu
|
||||
var mu sync.Mutex
|
||||
// apiBody 保存api请求体,供当前处理流程使用
|
||||
// apiBody 用于本次流程后续判断的api请求体
|
||||
var apiBody map[string]any
|
||||
// observedAPIs 保存observedAPIs,供当前处理流程使用
|
||||
// observedAPIs 用于本次流程后续判断的observedAPIs
|
||||
var observedAPIs []string
|
||||
|
||||
// 路由拦截:fetch mtop 订单详情 API 响应体。
|
||||
_ = page.Route("**/*", func(route playwright.Route) {
|
||||
// requestURL 保存请求URL,供当前处理流程使用
|
||||
// requestURL 用于本次流程后续判断的请求URL
|
||||
requestURL := route.Request().URL()
|
||||
if // parsed、parseErr 保存parsed、parseErr,供当前处理流程使用
|
||||
if // parsed、parseErr 用于本次流程后续判断的parsed、parseErr
|
||||
parsed, parseErr := url.Parse(requestURL); parseErr == nil && strings.Contains(parsed.Host, "goofish.com") {
|
||||
// apiName 保存api名称,供当前处理流程使用
|
||||
// apiName 用于本次流程后续判断的api名称
|
||||
apiName := parsed.Query().Get("api")
|
||||
if apiName == "" && strings.Contains(parsed.Path, "/h5/") {
|
||||
// parts 保存parts,供当前处理流程使用
|
||||
// parts 用于本次流程后续判断的parts
|
||||
parts := strings.Split(parsed.Path, "/")
|
||||
if len(parts) > 2 {
|
||||
apiName = parts[2]
|
||||
@@ -111,12 +111,12 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
|
||||
}
|
||||
}
|
||||
if strings.Contains(requestURL, mtopOrderDetailURL) {
|
||||
// resp、err 保存resp、err,供当前处理流程使用
|
||||
// resp、err 用于本次流程后续判断的resp、err
|
||||
resp, err := route.Fetch()
|
||||
if err == nil {
|
||||
// body 保存请求体,供当前处理流程使用
|
||||
// body 用于本次流程后续判断的请求体
|
||||
var body map[string]any
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := resp.JSON(&body); err == nil {
|
||||
mu.Lock()
|
||||
apiBody = body
|
||||
@@ -127,9 +127,9 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
|
||||
_ = route.Continue()
|
||||
})
|
||||
|
||||
// url 保存地址,供当前处理流程使用
|
||||
// url 用于本次流程后续判断的地址
|
||||
url := fmt.Sprintf("https://www.goofish.com/order-detail?orderId=%s&role=seller", orderID)
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := page.Goto(url, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateNetworkidle,
|
||||
Timeout: playwright.Float(30000),
|
||||
@@ -143,15 +143,15 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
mu.Lock()
|
||||
// body 保存请求体,供当前处理流程使用
|
||||
// body 用于本次流程后续判断的请求体
|
||||
body := apiBody
|
||||
mu.Unlock()
|
||||
|
||||
// od 保存od,供当前处理流程使用
|
||||
// od 用于本次流程后续判断的od
|
||||
od := &OrderDetail{OrderID: orderID}
|
||||
|
||||
if body != nil {
|
||||
if // d、ok 保存d、ok,供当前处理流程使用
|
||||
if // d、ok 用于本次流程后续判断的d、ok
|
||||
d, ok := body["data"].(map[string]any); ok {
|
||||
parseAPIResponse(od, d)
|
||||
}
|
||||
@@ -159,7 +159,7 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
|
||||
|
||||
// DOM 补充(金额 / SKU)。
|
||||
parseDOMContent(page, od)
|
||||
// allCookies、cookieErr 保存allCookies、cookieErr,供当前处理流程使用
|
||||
// allCookies、cookieErr 用于本次流程后续判断的allCookies、cookieErr
|
||||
allCookies, cookieErr := page.Context().Cookies()
|
||||
if cookieErr != nil {
|
||||
return nil, fmt.Errorf("读取订单详情浏览器 Cookie Jar: %w", cookieErr)
|
||||
@@ -170,25 +170,25 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
|
||||
}
|
||||
od.CookieSnapshotComplete = true
|
||||
od.UpdatedCookies = currentCookieHeader(od.CookieSnapshot, goofishIMURL)
|
||||
if // session 保存会话,供当前处理流程使用
|
||||
if // session 用于本次流程后续判断的会话
|
||||
session := mtop.CookieSessionFromContext(ctx); session != nil {
|
||||
session.ReplaceSnapshot(od.CookieSnapshot)
|
||||
}
|
||||
if od.Amount == "" {
|
||||
// title 保存标题,供当前处理流程使用
|
||||
// title 用于本次流程后续判断的标题
|
||||
title, _ := page.Title()
|
||||
m.logger.Warn("订单详情未解析到实付金额", "order_id", orderID, "page_title", title, "page_url", logsafe.URL(page.URL()), "api_captured", body != nil, "observed_apis", observedAPIs)
|
||||
}
|
||||
return od, nil
|
||||
}
|
||||
|
||||
// parseAPIResponse 负责parseAPI响应相关处理。
|
||||
// parseAPIResponse 封装parseAPI响应业务协调。
|
||||
func parseAPIResponse(od *OrderDetail, data map[string]any) {
|
||||
// 订单状态。
|
||||
if ut, ok := data["utArgs"].(map[string]any); ok {
|
||||
if // code、ok 保存code、ok,供当前处理流程使用
|
||||
if // code、ok 用于本次流程后续判断的code、ok
|
||||
code, ok := ut["orderStatus"].(float64); ok {
|
||||
if // s、ok 保存s、ok,供当前处理流程使用
|
||||
if // s、ok 用于本次流程后续判断的s、ok
|
||||
s, ok := orderStatusMap[int(code)]; ok {
|
||||
od.OrderStatus = s
|
||||
}
|
||||
@@ -198,7 +198,7 @@ func parseAPIResponse(od *OrderDetail, data map[string]any) {
|
||||
comps, _ := data["components"].([]any)
|
||||
// c 表示当前遍历过程中的c
|
||||
for _, c := range comps {
|
||||
// cm、ok 保存cm、ok,供当前处理流程使用
|
||||
// cm、ok 用于本次流程后续判断的cm、ok
|
||||
cm, ok := c.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
@@ -206,15 +206,15 @@ func parseAPIResponse(od *OrderDetail, data map[string]any) {
|
||||
if cm["render"] == "orderInfoVO" {
|
||||
// 当前接口把 priceInfo 放在 component.data 下;兼容旧结构的顶层字段。
|
||||
componentData, _ := cm["data"].(map[string]any)
|
||||
// priceInfo 保存priceInfo,供当前处理流程使用
|
||||
// priceInfo 用于本次流程后续判断的priceInfo
|
||||
priceInfo, _ := componentData["priceInfo"].(map[string]any)
|
||||
if priceInfo == nil {
|
||||
priceInfo, _ = cm["priceInfo"].(map[string]any)
|
||||
}
|
||||
if priceInfo != nil {
|
||||
// amount 保存amount,供当前处理流程使用
|
||||
// amount 用于本次流程后续判断的amount
|
||||
amount, _ := priceInfo["amount"].(map[string]any)
|
||||
if // v、ok 保存v、ok,供当前处理流程使用
|
||||
if // v、ok 用于本次流程后续判断的v、ok
|
||||
v, ok := amount["value"].(string); ok {
|
||||
od.Amount = v
|
||||
}
|
||||
@@ -223,28 +223,28 @@ func parseAPIResponse(od *OrderDetail, data map[string]any) {
|
||||
}
|
||||
}
|
||||
|
||||
// currencyAmountRE 保存currencyAmountRE,供当前处理流程使用
|
||||
// currencyAmountRE 用于本次流程后续判断的currencyAmountRE
|
||||
var currencyAmountRE = regexp.MustCompile(`[¥¥]\s*([0-9]+(?:\.[0-9]{1,2})?)`)
|
||||
|
||||
// plainAmountRE 保存plainAmountRE,供当前处理流程使用
|
||||
// plainAmountRE 用于本次流程后续判断的plainAmountRE
|
||||
var plainAmountRE = regexp.MustCompile(`^\s*([0-9]+(?:\.[0-9]{1,2})?)\s*$`)
|
||||
|
||||
// parseDOMContent 负责parseDOM内容相关处理。
|
||||
// parseDOMContent 封装parseDOM内容业务协调。
|
||||
func parseDOMContent(page playwright.Page, od *OrderDetail) {
|
||||
// 金额。
|
||||
if od.Amount == "" {
|
||||
if // el、err 保存el、err,供当前处理流程使用
|
||||
if // el、err 用于本次流程后续判断的el、err
|
||||
el, err := page.QuerySelector(`.boldNum--JgEOXfA3`); err == nil && el != nil {
|
||||
if // t、err 保存t、err,供当前处理流程使用
|
||||
if // t、err 用于本次流程后续判断的t、err
|
||||
t, err := el.TextContent(); err == nil {
|
||||
od.Amount = strings.TrimSpace(t)
|
||||
}
|
||||
}
|
||||
}
|
||||
if od.Amount == "" {
|
||||
if // raw、err 保存raw、err,供当前处理流程使用
|
||||
if // raw、err 用于本次流程后续判断的raw、err
|
||||
raw, err := page.Evaluate(`() => document.body?.innerText || ''`); err == nil {
|
||||
if // pageText、ok 保存页码Text、ok,供当前处理流程使用
|
||||
if // pageText、ok 用于本次流程后续判断的页码Text、ok
|
||||
pageText, ok := raw.(string); ok {
|
||||
od.Amount = extractPaidAmountFromText(pageText)
|
||||
}
|
||||
@@ -253,16 +253,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 用于本次流程后续判断的t
|
||||
t, _ := skuEls[0].TextContent()
|
||||
// parts 保存parts,供当前处理流程使用
|
||||
// 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 用于本次流程后续判断的q
|
||||
q, _ := skuEls[1].TextContent()
|
||||
od.Quantity = strings.TrimPrefix(strings.TrimSpace(q), "x")
|
||||
}
|
||||
@@ -272,24 +272,24 @@ func parseDOMContent(page playwright.Page, od *OrderDetail) {
|
||||
}
|
||||
}
|
||||
|
||||
// extractPaidAmountFromText 负责extractPaidAmountFrom文本相关处理。
|
||||
// extractPaidAmountFromText 封装extractPaidAmountFrom文本业务协调。
|
||||
func extractPaidAmountFromText(pageText string) string {
|
||||
// labels 保存labels,供当前处理流程使用
|
||||
// labels 用于本次流程后续判断的labels
|
||||
labels := []string{"实付款", "实付金额", "订单金额", "合计"}
|
||||
// rawLines 保存原始Lines,供当前处理流程使用
|
||||
// rawLines 用于本次流程后续判断的原始Lines
|
||||
rawLines := strings.Split(pageText, "\n")
|
||||
// lines 保存lines,供当前处理流程使用
|
||||
// lines 用于本次流程后续判断的lines
|
||||
lines := make([]string, 0, len(rawLines))
|
||||
// line 表示当前遍历过程中的line
|
||||
for _, line := range rawLines {
|
||||
if // trimmed 保存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 用于本次流程后续判断的matchedLabel
|
||||
matchedLabel := false
|
||||
// label 表示当前遍历过程中的label
|
||||
for _, label := range labels {
|
||||
@@ -301,19 +301,19 @@ func extractPaidAmountFromText(pageText string) string {
|
||||
if !matchedLabel {
|
||||
continue
|
||||
}
|
||||
// end 保存结束,供当前处理流程使用
|
||||
// end 用于本次流程后续判断的结束
|
||||
end := i + 3
|
||||
if end > len(lines) {
|
||||
end = len(lines)
|
||||
}
|
||||
// candidate 表示当前遍历过程中的candidate
|
||||
for _, candidate := range lines[i:end] {
|
||||
if // match 保存match,供当前处理流程使用
|
||||
if // match 用于本次流程后续判断的match
|
||||
match := currencyAmountRE.FindStringSubmatch(candidate); len(match) == 2 {
|
||||
return match[1]
|
||||
}
|
||||
if candidate != line {
|
||||
if // match 保存match,供当前处理流程使用
|
||||
if // match 用于本次流程后续判断的match
|
||||
match := plainAmountRE.FindStringSubmatch(candidate); len(match) == 2 {
|
||||
return match[1]
|
||||
}
|
||||
@@ -325,17 +325,17 @@ 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 用于本次流程后续判断的sem
|
||||
sem := make(chan struct{}, 5)
|
||||
// result 保存结果,供当前处理流程使用
|
||||
// result 用于本次流程后续判断的结果
|
||||
type result struct {
|
||||
id string
|
||||
od *OrderDetail
|
||||
err error
|
||||
}
|
||||
// results 保存results,供当前处理流程使用
|
||||
// results 用于本次流程后续判断的results
|
||||
results := make([]result, len(orderIDs))
|
||||
// wg 保存wg,供当前处理流程使用
|
||||
// wg 用于本次流程后续判断的wg
|
||||
var wg sync.WaitGroup
|
||||
// i、id 表示当前遍历过程中的i、id
|
||||
for i, id := range orderIDs {
|
||||
@@ -344,14 +344,14 @@ func (m *Manager) BatchRefreshOrders(ctx context.Context, orderIDs []string, coo
|
||||
defer wg.Done()
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
// od、err 保存od、err,供当前处理流程使用
|
||||
// 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 用于本次流程后续判断的订单列表
|
||||
orders := make([]map[string]any, 0, len(orderIDs))
|
||||
// r 表示当前遍历过程中的r
|
||||
for _, r := range results {
|
||||
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestOrderStatusMap 负责Test订单状态Map相关处理。
|
||||
// TestOrderStatusMap 封装Test订单状态Map业务协调。
|
||||
func TestOrderStatusMap(t *testing.T) {
|
||||
// cases 保存cases,供当前处理流程使用
|
||||
// cases 用于本次流程后续判断的cases
|
||||
cases := []struct {
|
||||
code int
|
||||
expect string
|
||||
@@ -17,18 +17,18 @@ func TestOrderStatusMap(t *testing.T) {
|
||||
}
|
||||
// c 表示当前遍历过程中的c
|
||||
for _, c := range cases {
|
||||
if // s、ok 保存s、ok,供当前处理流程使用
|
||||
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相关处理。
|
||||
// TestParseAPIResponseStatusCode 封装TestParseAPI响应状态Code业务协调。
|
||||
func TestParseAPIResponseStatusCode(t *testing.T) {
|
||||
// od 保存od,供当前处理流程使用
|
||||
// od 用于本次流程后续判断的od
|
||||
od := &OrderDetail{}
|
||||
// data 保存数据,供当前处理流程使用
|
||||
// data 用于本次流程后续判断的数据
|
||||
data := map[string]any{
|
||||
"utArgs": map[string]any{"orderStatus": float64(2)},
|
||||
}
|
||||
@@ -38,11 +38,11 @@ func TestParseAPIResponseStatusCode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseAPIResponseAmountFromComponentData 负责TestParseAPI响应AmountFromComponent数据相关处理。
|
||||
// TestParseAPIResponseAmountFromComponentData 封装TestParseAPI响应AmountFromComponent数据业务协调。
|
||||
func TestParseAPIResponseAmountFromComponentData(t *testing.T) {
|
||||
// od 保存od,供当前处理流程使用
|
||||
// od 用于本次流程后续判断的od
|
||||
od := &OrderDetail{}
|
||||
// data 保存数据,供当前处理流程使用
|
||||
// data 用于本次流程后续判断的数据
|
||||
data := map[string]any{
|
||||
"components": []any{
|
||||
map[string]any{
|
||||
@@ -61,9 +61,9 @@ func TestParseAPIResponseAmountFromComponentData(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractPaidAmountFromText 负责TestExtractPaidAmountFrom文本相关处理。
|
||||
// TestExtractPaidAmountFromText 封装TestExtractPaidAmountFrom文本业务协调。
|
||||
func TestExtractPaidAmountFromText(t *testing.T) {
|
||||
// cases 保存cases,供当前处理流程使用
|
||||
// cases 用于本次流程后续判断的cases
|
||||
cases := map[string]string{
|
||||
"商品标价\n¥99.00\n实付款 ¥0.88\n交易成功": "0.88",
|
||||
"订单信息\n实付金额\n¥12.50\n订单编号": "12.50",
|
||||
@@ -72,7 +72,7 @@ func TestExtractPaidAmountFromText(t *testing.T) {
|
||||
}
|
||||
// input、want 表示当前遍历过程中的input、want
|
||||
for input, want := range cases {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := extractPaidAmountFromText(input); got != want {
|
||||
t.Errorf("extractPaidAmountFromText(%q)=%q want %q", input, got, want)
|
||||
}
|
||||
|
||||
@@ -18,22 +18,22 @@ var loginIDSelectors = []string{
|
||||
".fm-login-id",
|
||||
}
|
||||
|
||||
// loginPwdSelectors 保存登录PwdSelectors,供当前处理流程使用
|
||||
// loginPwdSelectors 用于本次流程后续判断的登录PwdSelectors
|
||||
var loginPwdSelectors = []string{
|
||||
"#fm-login-password", `input[type="password"]`,
|
||||
}
|
||||
|
||||
// loginBtnSelectors 保存登录BtnSelectors,供当前处理流程使用
|
||||
// loginBtnSelectors 用于本次流程后续判断的登录BtnSelectors
|
||||
var loginBtnSelectors = []string{
|
||||
"button.password-login", `button[type="submit"]`,
|
||||
}
|
||||
|
||||
// loginSuccessSelectors 保存登录SuccessSelectors,供当前处理流程使用
|
||||
// loginSuccessSelectors 用于本次流程后续判断的登录SuccessSelectors
|
||||
var loginSuccessSelectors = []string{
|
||||
".rc-virtual-list-holder-inner", // IM 页面侧边栏有子元素则已登录
|
||||
}
|
||||
|
||||
// passwordVerificationWaitInterval 保存密码VerificationWaitInterval,供当前处理流程使用
|
||||
// passwordVerificationWaitInterval 用于本次流程后续判断的密码VerificationWaitInterval
|
||||
const (
|
||||
passwordVerificationWaitInterval = 10 * time.Second
|
||||
passwordVerificationMaxWait = 5 * time.Minute
|
||||
@@ -46,7 +46,7 @@ const (
|
||||
// PasswordLogin 用账号密码通过浏览器登录闲鱼,返回完整 cookie map。
|
||||
// 移植自 xianyu_slider_stealth.login_with_password_playwright。
|
||||
// userDataDir:空字符串使用按账号划分的默认持久化目录。
|
||||
// PasswordLogin 负责密码登录相关处理。
|
||||
// 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)
|
||||
}
|
||||
@@ -56,7 +56,7 @@ func (m *Manager) PasswordLoginWithEvents(ctx context.Context, account, password
|
||||
return m.passwordLogin(ctx, account, password, cookieID, userDataDir, headless, onEvent)
|
||||
}
|
||||
|
||||
// passwordLogin 负责密码登录相关处理。
|
||||
// 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("账号或密码不能为空")
|
||||
@@ -67,7 +67,7 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
|
||||
}
|
||||
headless = quickRenewHeadless(headless)
|
||||
|
||||
// bctx、release、err 保存bctx、release、err,供当前处理流程使用
|
||||
// bctx、release、err 用于本次流程后续判断的bctx、release、err
|
||||
bctx, release, err := m.newPersistentPasswordContext(ctx, cookieID, userDataDir, headless)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -80,7 +80,7 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
|
||||
return nil, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(30000),
|
||||
@@ -92,14 +92,14 @@ 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 用于本次流程后续判断的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 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(30000),
|
||||
@@ -117,7 +117,7 @@ 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 保存handled,供当前处理流程使用
|
||||
if // handled 用于本次流程后续判断的handled
|
||||
handled := detectAndHandlePasswordSlider(page, m.logger); handled {
|
||||
m.logger.Info("密码登录:未找到表单时已处理滑块", "cookieID", cookieID)
|
||||
}
|
||||
@@ -138,9 +138,9 @@ 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 用于本次流程后续判断的checked
|
||||
checked, _ := cb.Evaluate(`el => Boolean(el.checked)`)
|
||||
if // isChecked 保存isChecked,供当前处理流程使用
|
||||
if // isChecked 用于本次流程后续判断的isChecked
|
||||
isChecked, _ := checked.(bool); !isChecked {
|
||||
_ = cb.Click()
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
@@ -171,13 +171,13 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
|
||||
return extractPageCookies(page)
|
||||
}
|
||||
|
||||
// findPasswordElement 负责find密码Element相关处理。
|
||||
// findPasswordElement 封装find密码Element业务协调。
|
||||
func findPasswordElement(page playwright.Page, selectors []string) playwright.ElementHandle {
|
||||
// frames 保存frames,供当前处理流程使用
|
||||
// frames 用于本次流程后续判断的frames
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
// frame 表示当前遍历过程中的frame
|
||||
for _, frame := range frames {
|
||||
if // el 保存el,供当前处理流程使用
|
||||
if // el 用于本次流程后续判断的el
|
||||
el := queryFirst(frame, selectors); el != nil {
|
||||
return el
|
||||
}
|
||||
@@ -185,22 +185,22 @@ func findPasswordElement(page playwright.Page, selectors []string) playwright.El
|
||||
return nil
|
||||
}
|
||||
|
||||
// clickPasswordLoginTab 负责click密码登录Tab相关处理。
|
||||
// clickPasswordLoginTab 封装click密码登录Tab业务协调。
|
||||
func clickPasswordLoginTab(page playwright.Page) bool {
|
||||
// el 保存el,供当前处理流程使用
|
||||
// el 用于本次流程后续判断的el
|
||||
el := findPasswordElement(page, []string{"a.password-login-tab-item"})
|
||||
return el != nil && el.Click() == nil
|
||||
}
|
||||
|
||||
// detectAndHandlePasswordSlider 负责detectAndHandle密码Slider相关处理。
|
||||
// detectAndHandlePasswordSlider 封装detectAndHandle密码Slider业务协调。
|
||||
func detectAndHandlePasswordSlider(page playwright.Page, logger sliderLogger) bool {
|
||||
// content 保存内容,供当前处理流程使用
|
||||
// content 用于本次流程后续判断的内容
|
||||
content, _ := page.Content()
|
||||
if !strings.Contains(content, "nc-container") && !strings.Contains(content, "scratch-captcha") {
|
||||
// 参考实现把“未发现滑块”也视为检测流程成功;调用方据此保持相同的等待节奏。
|
||||
return true
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := solveSlider(page, isScratchCaptcha(content), logger); err != nil {
|
||||
logger.Warn("密码登录滑块处理失败", "err", err)
|
||||
return false
|
||||
@@ -208,7 +208,7 @@ func detectAndHandlePasswordSlider(page playwright.Page, logger sliderLogger) bo
|
||||
return true
|
||||
}
|
||||
|
||||
// quickEnterCookiesUsable 负责quickEnterCookiesUsable相关处理。
|
||||
// quickEnterCookiesUsable 封装quickEnterCookiesUsable业务协调。
|
||||
func quickEnterCookiesUsable(cookies map[string]string) bool {
|
||||
if len(cookies) == 0 {
|
||||
return false
|
||||
@@ -216,28 +216,28 @@ func quickEnterCookiesUsable(cookies map[string]string) bool {
|
||||
return strings.TrimSpace(cookies["unb"]) != ""
|
||||
}
|
||||
|
||||
// handlePasswordLoginPending 负责handle密码登录Pending相关处理。
|
||||
// handlePasswordLoginPending 封装handle密码登录Pending业务协调。
|
||||
func (m *Manager) handlePasswordLoginPending(ctx context.Context, page playwright.Page, onEvent PasswordLoginEventHandler) (map[string]string, error) {
|
||||
if // msg 保存msg,供当前处理流程使用
|
||||
if // msg 用于本次流程后续判断的msg
|
||||
msg := passwordLoginErrorFromPage(page); msg != "" {
|
||||
if onEvent != nil {
|
||||
onEvent(PasswordLoginEventFromMessage(msg))
|
||||
}
|
||||
return nil, fmt.Errorf("密码登录失败: %s", msg)
|
||||
}
|
||||
if // event、ok 保存event、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 保存event、ok,供当前处理流程使用
|
||||
if // event、ok 用于本次流程后续判断的event、ok
|
||||
event, ok := passwordVerificationEventFromPage(page); ok {
|
||||
if onEvent != nil {
|
||||
onEvent(event)
|
||||
}
|
||||
// cookies、err 保存cookies、err,供当前处理流程使用
|
||||
// cookies、err 用于本次流程后续判断的cookies、err
|
||||
cookies, err := waitPasswordVerification(ctx, page, onEvent)
|
||||
if err == nil {
|
||||
m.logger.Info("密码登录人工验证完成")
|
||||
@@ -245,7 +245,7 @@ func (m *Manager) handlePasswordLoginPending(ctx context.Context, page playwrigh
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
// errMsg 保存errMsg,供当前处理流程使用
|
||||
// errMsg 用于本次流程后续判断的errMsg
|
||||
errMsg := "登录失败"
|
||||
if onEvent != nil {
|
||||
onEvent(PasswordLoginEventFromMessage(errMsg))
|
||||
@@ -253,12 +253,12 @@ func (m *Manager) handlePasswordLoginPending(ctx context.Context, page playwrigh
|
||||
return nil, fmt.Errorf("密码登录失败: %s", errMsg)
|
||||
}
|
||||
|
||||
// waitPasswordVerification 负责wait密码Verification相关处理。
|
||||
// waitPasswordVerification 封装wait密码Verification业务协调。
|
||||
func waitPasswordVerification(ctx context.Context, page playwright.Page, onEvent PasswordLoginEventHandler) (map[string]string, error) {
|
||||
// ticker 保存ticker,供当前处理流程使用
|
||||
// ticker 用于本次流程后续判断的ticker
|
||||
ticker := time.NewTicker(passwordVerificationWaitInterval)
|
||||
defer ticker.Stop()
|
||||
// timer 保存定时器,供当前处理流程使用
|
||||
// timer 用于本次流程后续判断的定时器
|
||||
timer := time.NewTimer(passwordVerificationMaxWait)
|
||||
defer timer.Stop()
|
||||
for {
|
||||
@@ -272,33 +272,33 @@ func waitPasswordVerification(ctx context.Context, page playwright.Page, onEvent
|
||||
if checkLoginSuccess(page) {
|
||||
return extractPageCookies(page)
|
||||
}
|
||||
if // msg 保存msg,供当前处理流程使用
|
||||
if // msg 用于本次流程后续判断的msg
|
||||
msg := passwordLoginErrorFromPage(page); msg != "" {
|
||||
return nil, fmt.Errorf("密码登录失败: %s", msg)
|
||||
}
|
||||
if // event、ok 保存event、ok,供当前处理流程使用
|
||||
if // event、ok 用于本次流程后续判断的event、ok
|
||||
event, ok := passwordBaxiaEventFromPage(page); ok {
|
||||
return nil, fmt.Errorf("密码登录失败: %s", event.Message)
|
||||
}
|
||||
if // event、ok 保存event、ok,供当前处理流程使用
|
||||
if // event、ok 用于本次流程后续判断的event、ok
|
||||
event, ok := passwordVerificationEventFromPage(page); ok && onEvent != nil {
|
||||
onEvent(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// passwordLoginErrorFromPage 负责密码登录错误From页码相关处理。
|
||||
// passwordLoginErrorFromPage 封装密码登录错误From页码业务协调。
|
||||
func passwordLoginErrorFromPage(page playwright.Page) string {
|
||||
if // el、err 保存el、err,供当前处理流程使用
|
||||
if // el、err 用于本次流程后续判断的el、err
|
||||
el, err := page.QuerySelector(".login-error-msg"); err == nil && el != nil {
|
||||
if // msg 保存msg,供当前处理流程使用
|
||||
if // msg 用于本次流程后续判断的msg
|
||||
msg, _ := el.TextContent(); strings.TrimSpace(msg) != "" {
|
||||
return strings.TrimSpace(msg)
|
||||
}
|
||||
}
|
||||
// htmlText 表示当前遍历过程中的html文本
|
||||
for _, htmlText := range passwordLoginHTMLs(page) {
|
||||
if // msg 保存msg,供当前处理流程使用
|
||||
if // msg 用于本次流程后续判断的msg
|
||||
msg := detectPasswordLoginErrorHTML(htmlText); msg != "" {
|
||||
return msg
|
||||
}
|
||||
@@ -306,11 +306,11 @@ func passwordLoginErrorFromPage(page playwright.Page) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// passwordBaxiaEventFromPage 负责密码BaxiaEventFrom页码相关处理。
|
||||
// passwordBaxiaEventFromPage 封装密码BaxiaEventFrom页码业务协调。
|
||||
func passwordBaxiaEventFromPage(page playwright.Page) (PasswordLoginEvent, bool) {
|
||||
// htmlText 表示当前遍历过程中的html文本
|
||||
for _, htmlText := range passwordLoginHTMLs(page) {
|
||||
if // event、ok 保存event、ok,供当前处理流程使用
|
||||
if // event、ok 用于本次流程后续判断的event、ok
|
||||
event, ok := detectPasswordBaxiaPunishHTML(htmlText); ok {
|
||||
return event, true
|
||||
}
|
||||
@@ -318,16 +318,16 @@ func passwordBaxiaEventFromPage(page playwright.Page) (PasswordLoginEvent, bool)
|
||||
return PasswordLoginEvent{}, false
|
||||
}
|
||||
|
||||
// passwordVerificationEventFromPage 负责密码VerificationEventFrom页码相关处理。
|
||||
// passwordVerificationEventFromPage 封装密码VerificationEventFrom页码业务协调。
|
||||
func passwordVerificationEventFromPage(page playwright.Page) (PasswordLoginEvent, bool) {
|
||||
if // event、ok 保存event、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 保存event、ok,供当前处理流程使用
|
||||
if // event、ok 用于本次流程后续判断的event、ok
|
||||
event, ok := passwordVerificationEventFromContent(frameContent(frame), frame.URL()); ok {
|
||||
event.ScreenshotPath = firstNonEmptyString(event.ScreenshotPath, passwordVerificationScreenshot(page))
|
||||
return event, true
|
||||
@@ -336,9 +336,9 @@ func passwordVerificationEventFromPage(page playwright.Page) (PasswordLoginEvent
|
||||
return PasswordLoginEvent{}, false
|
||||
}
|
||||
|
||||
// passwordVerificationEventFromContent 负责密码VerificationEventFrom内容相关处理。
|
||||
// passwordVerificationEventFromContent 封装密码VerificationEventFrom内容业务协调。
|
||||
func passwordVerificationEventFromContent(htmlText, frameURL string) (PasswordLoginEvent, bool) {
|
||||
// event、ok 保存event、ok,供当前处理流程使用
|
||||
// event、ok 用于本次流程后续判断的event、ok
|
||||
event, ok := detectPasswordVerificationHTML(htmlText)
|
||||
if !ok {
|
||||
return PasswordLoginEvent{}, false
|
||||
@@ -349,9 +349,9 @@ func passwordVerificationEventFromContent(htmlText, frameURL string) (PasswordLo
|
||||
return event, true
|
||||
}
|
||||
|
||||
// passwordLoginHTMLs 负责密码登录HTMLs相关处理。
|
||||
// passwordLoginHTMLs 封装密码登录HTMLs业务协调。
|
||||
func passwordLoginHTMLs(page playwright.Page) []string {
|
||||
// htmls 保存htmls,供当前处理流程使用
|
||||
// htmls 用于本次流程后续判断的htmls
|
||||
htmls := []string{pageContent(page)}
|
||||
// frame 表示当前遍历过程中的frame
|
||||
for _, frame := range page.Frames() {
|
||||
@@ -360,23 +360,23 @@ func passwordLoginHTMLs(page playwright.Page) []string {
|
||||
return htmls
|
||||
}
|
||||
|
||||
// pageContent 负责页码内容相关处理。
|
||||
// pageContent 封装页码内容业务协调。
|
||||
func pageContent(page playwright.Page) string {
|
||||
// content 保存内容,供当前处理流程使用
|
||||
// content 用于本次流程后续判断的内容
|
||||
content, _ := page.Content()
|
||||
return content
|
||||
}
|
||||
|
||||
// frameContent 负责frame内容相关处理。
|
||||
// frameContent 封装frame内容业务协调。
|
||||
func frameContent(frame playwright.Frame) string {
|
||||
// content 保存内容,供当前处理流程使用
|
||||
// content 用于本次流程后续判断的内容
|
||||
content, _ := frame.Content()
|
||||
return content
|
||||
}
|
||||
|
||||
// passwordVerificationScreenshot 负责密码VerificationScreenshot相关处理。
|
||||
// passwordVerificationScreenshot 封装密码VerificationScreenshot业务协调。
|
||||
func passwordVerificationScreenshot(page playwright.Page) string {
|
||||
// raw、err 保存raw、err,供当前处理流程使用
|
||||
// raw、err 用于本次流程后续判断的raw、err
|
||||
raw, err := page.Screenshot(playwright.PageScreenshotOptions{
|
||||
FullPage: playwright.Bool(true),
|
||||
Timeout: playwright.Float(5000),
|
||||
@@ -387,14 +387,14 @@ func passwordVerificationScreenshot(page playwright.Page) string {
|
||||
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
// looksLikeVerificationURL 负责looksLikeVerificationURL相关处理。
|
||||
// looksLikeVerificationURL 封装looksLikeVerificationURL业务协调。
|
||||
func looksLikeVerificationURL(raw string) bool {
|
||||
// lower 保存lower,供当前处理流程使用
|
||||
// lower 用于本次流程后续判断的lower
|
||||
lower := strings.ToLower(raw)
|
||||
return containsAny(lower, "passport", "verify", "photo", "iv/", "identity", "login", "qrcode")
|
||||
}
|
||||
|
||||
// firstNonEmptyString 负责firstNonEmptyString相关处理。
|
||||
// firstNonEmptyString 封装firstNonEmptyString业务协调。
|
||||
func firstNonEmptyString(values ...string) string {
|
||||
// value 表示当前遍历过程中的值
|
||||
for _, value := range values {
|
||||
@@ -405,11 +405,11 @@ func firstNonEmptyString(values ...string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// checkLoginSuccess 负责check登录Success相关处理。
|
||||
// checkLoginSuccess 封装check登录Success业务协调。
|
||||
func checkLoginSuccess(page playwright.Page) bool {
|
||||
// sel 表示当前遍历过程中的sel
|
||||
for _, sel := range loginSuccessSelectors {
|
||||
// el、err 保存el、err,供当前处理流程使用
|
||||
// el、err 用于本次流程后续判断的el、err
|
||||
el, err := page.QuerySelector(sel)
|
||||
if err != nil || el == nil {
|
||||
continue
|
||||
@@ -427,29 +427,29 @@ func checkLoginSuccess(page playwright.Page) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// findLoginForm 负责find登录表单相关处理。
|
||||
// findLoginForm 封装find登录表单业务协调。
|
||||
func findLoginForm(page playwright.Page) (idEl, pwdEl, submitEl playwright.ElementHandle) {
|
||||
// frames 保存frames,供当前处理流程使用
|
||||
// frames 用于本次流程后续判断的frames
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
// f 表示当前遍历过程中的f
|
||||
for _, f := range frames {
|
||||
// id 保存标识,供当前处理流程使用
|
||||
// id 用于本次流程后续判断的标识
|
||||
id := queryFirst(f, loginIDSelectors)
|
||||
if id == nil {
|
||||
continue
|
||||
}
|
||||
// pwd 保存pwd,供当前处理流程使用
|
||||
// pwd 用于本次流程后续判断的pwd
|
||||
pwd := queryFirst(f, loginPwdSelectors)
|
||||
// submit 保存submit,供当前处理流程使用
|
||||
// submit 用于本次流程后续判断的submit
|
||||
submit := queryFirst(f, loginBtnSelectors)
|
||||
return id, pwd, submit
|
||||
}
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
// sanitize 负责sanitize相关处理。
|
||||
// sanitize 封装sanitize业务协调。
|
||||
func sanitize(s string) string {
|
||||
// r 保存r,供当前处理流程使用
|
||||
// r 用于本次流程后续判断的r
|
||||
r := strings.NewReplacer("/", "_", "\\", "_", ":", "_", " ", "_")
|
||||
return r.Replace(s)
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// htmlTagPattern 保存htmlTagPattern,供当前处理流程使用
|
||||
// htmlTagPattern 用于本次流程后续判断的htmlTagPattern
|
||||
var (
|
||||
htmlTagPattern = regexp.MustCompile(`(?is)<[^>]+>`)
|
||||
scriptStylePattern = regexp.MustCompile(`(?is)<script[^>]*>.*?</script>|<style[^>]*>.*?</style>`)
|
||||
@@ -15,12 +15,12 @@ var (
|
||||
escapedSlashPattern = strings.NewReplacer(`\/`, `/`, `\u0026`, `&`)
|
||||
)
|
||||
|
||||
// detectPasswordBaxiaPunishHTML 负责detect密码BaxiaPunishHTML相关处理。
|
||||
// detectPasswordBaxiaPunishHTML 封装detect密码BaxiaPunishHTML业务协调。
|
||||
func detectPasswordBaxiaPunishHTML(htmlText string) (PasswordLoginEvent, bool) {
|
||||
if !IsBaxiaPunishMessage(htmlText) {
|
||||
return PasswordLoginEvent{}, false
|
||||
}
|
||||
// msg 保存msg,供当前处理流程使用
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := "触发闲鱼风控图形验证(baxia-punish),账号正常但暂时无法自动登录"
|
||||
return PasswordLoginEvent{
|
||||
Status: PasswordLoginStatusFailed,
|
||||
@@ -31,9 +31,9 @@ func detectPasswordBaxiaPunishHTML(htmlText string) (PasswordLoginEvent, bool) {
|
||||
}, true
|
||||
}
|
||||
|
||||
// detectPasswordLoginErrorHTML 负责detect密码登录错误HTML相关处理。
|
||||
// detectPasswordLoginErrorHTML 封装detect密码登录错误HTML业务协调。
|
||||
func detectPasswordLoginErrorHTML(htmlText string) string {
|
||||
// text 保存文本,供当前处理流程使用
|
||||
// text 用于本次流程后续判断的文本
|
||||
text := normalizeHTMLText(htmlText)
|
||||
// keyword 表示当前遍历过程中的关键词
|
||||
for _, keyword := range []string{
|
||||
@@ -48,11 +48,11 @@ func detectPasswordLoginErrorHTML(htmlText string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// detectPasswordVerificationHTML 负责detect密码VerificationHTML相关处理。
|
||||
// detectPasswordVerificationHTML 封装detect密码VerificationHTML业务协调。
|
||||
func detectPasswordVerificationHTML(htmlText string) (PasswordLoginEvent, bool) {
|
||||
// normalized 保存normalized,供当前处理流程使用
|
||||
// normalized 用于本次流程后续判断的normalized
|
||||
normalized := normalizeHTMLText(htmlText)
|
||||
// lower 保存lower,供当前处理流程使用
|
||||
// lower 用于本次流程后续判断的lower
|
||||
lower := strings.ToLower(htmlText)
|
||||
if !containsAny(normalized,
|
||||
"人脸验证", "人脸识别", "身份验证", "安全验证", "扫码验证", "验证二维码",
|
||||
@@ -63,9 +63,9 @@ func detectPasswordVerificationHTML(htmlText string) (PasswordLoginEvent, bool)
|
||||
) {
|
||||
return PasswordLoginEvent{}, false
|
||||
}
|
||||
// msg 保存msg,供当前处理流程使用
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := "密码登录需要人工验证,请在浏览器中完成验证后等待自动继续"
|
||||
// event 保存event,供当前处理流程使用
|
||||
// event 用于本次流程后续判断的event
|
||||
event := PasswordLoginEvent{
|
||||
Status: PasswordLoginStatusVerificationRequired,
|
||||
Message: msg,
|
||||
@@ -76,17 +76,17 @@ func detectPasswordVerificationHTML(htmlText string) (PasswordLoginEvent, bool)
|
||||
return event, true
|
||||
}
|
||||
|
||||
// extractPasswordVerificationURL 负责extract密码VerificationURL相关处理。
|
||||
// extractPasswordVerificationURL 封装extract密码VerificationURL业务协调。
|
||||
func extractPasswordVerificationURL(htmlText string) string {
|
||||
// cleaned 保存cleaned,供当前处理流程使用
|
||||
// cleaned 用于本次流程后续判断的cleaned
|
||||
cleaned := escapedSlashPattern.Replace(html.UnescapeString(htmlText))
|
||||
// matches 保存matches,供当前处理流程使用
|
||||
// matches 用于本次流程后续判断的matches
|
||||
matches := verificationURLRe.FindAllString(cleaned, -1)
|
||||
// raw 表示当前遍历过程中的原始
|
||||
for _, raw := range matches {
|
||||
// url 保存地址,供当前处理流程使用
|
||||
// url 用于本次流程后续判断的地址
|
||||
url := strings.TrimRight(raw, ".,);]")
|
||||
// lower 保存lower,供当前处理流程使用
|
||||
// lower 用于本次流程后续判断的lower
|
||||
lower := strings.ToLower(url)
|
||||
if containsAny(lower, "passport", "verify", "photo", "iv/", "identity", "login", "qrcode") {
|
||||
return url
|
||||
@@ -95,27 +95,27 @@ func extractPasswordVerificationURL(htmlText string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// extractPasswordQRURL 负责extract密码QRURL相关处理。
|
||||
// extractPasswordQRURL 封装extract密码QRURL业务协调。
|
||||
func extractPasswordQRURL(htmlText string) string {
|
||||
// cleaned 保存cleaned,供当前处理流程使用
|
||||
// cleaned 用于本次流程后续判断的cleaned
|
||||
cleaned := escapedSlashPattern.Replace(html.UnescapeString(htmlText))
|
||||
if // match 保存match,供当前处理流程使用
|
||||
if // match 用于本次流程后续判断的match
|
||||
match := dataImageURLRe.FindString(cleaned); match != "" {
|
||||
return match
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// normalizeHTMLText 负责normalizeHTML文本相关处理。
|
||||
// normalizeHTMLText 封装normalizeHTML文本业务协调。
|
||||
func normalizeHTMLText(htmlText string) string {
|
||||
// cleaned 保存cleaned,供当前处理流程使用
|
||||
// cleaned 用于本次流程后续判断的cleaned
|
||||
cleaned := scriptStylePattern.ReplaceAllString(htmlText, " ")
|
||||
cleaned = htmlTagPattern.ReplaceAllString(cleaned, " ")
|
||||
cleaned = escapedSlashPattern.Replace(html.UnescapeString(cleaned))
|
||||
return strings.Join(strings.Fields(cleaned), " ")
|
||||
}
|
||||
|
||||
// containsAny 负责containsAny相关处理。
|
||||
// containsAny 封装containsAny业务协调。
|
||||
func containsAny(s string, keywords ...string) bool {
|
||||
// keyword 表示当前遍历过程中的关键词
|
||||
for _, keyword := range keywords {
|
||||
|
||||
@@ -7,11 +7,11 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestDetectPasswordBaxiaPunishHTML 负责TestDetect密码BaxiaPunishHTML相关处理。
|
||||
// TestDetectPasswordBaxiaPunishHTML 封装TestDetect密码BaxiaPunishHTML业务协调。
|
||||
func TestDetectPasswordBaxiaPunishHTML(t *testing.T) {
|
||||
// html 保存html,供当前处理流程使用
|
||||
// html 用于本次流程后续判断的html
|
||||
html := `<div id="baxia-punish"><div class="captcha-question">请找两个松鼠</div></div>`
|
||||
// event、ok 保存event、ok,供当前处理流程使用
|
||||
// event、ok 用于本次流程后续判断的event、ok
|
||||
event, ok := detectPasswordBaxiaPunishHTML(html)
|
||||
if !ok {
|
||||
t.Fatal("应识别 baxia 图形验证")
|
||||
@@ -21,9 +21,9 @@ func TestDetectPasswordBaxiaPunishHTML(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPasswordEventFromMessageDoesNotTreatFaceRiskAsBaxia 负责Test密码EventFrom消息DoesNotTreatFaceRiskAsBaxia相关处理。
|
||||
// TestPasswordEventFromMessageDoesNotTreatFaceRiskAsBaxia 封装Test密码EventFrom消息DoesNotTreatFaceRiskAsBaxia业务协调。
|
||||
func TestPasswordEventFromMessageDoesNotTreatFaceRiskAsBaxia(t *testing.T) {
|
||||
// event 保存event,供当前处理流程使用
|
||||
// event 用于本次流程后续判断的event
|
||||
event := PasswordLoginEventFromMessage("账号触发风控,需要人脸验证")
|
||||
if event.Reason == "baxia_punish_captcha" {
|
||||
t.Fatalf("普通人脸验证不应按 baxia 冷却: %+v", event)
|
||||
@@ -33,9 +33,9 @@ func TestPasswordEventFromMessageDoesNotTreatFaceRiskAsBaxia(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDetectPasswordLoginErrorHTML 负责TestDetect密码登录错误HTML相关处理。
|
||||
// TestDetectPasswordLoginErrorHTML 封装TestDetect密码登录错误HTML业务协调。
|
||||
func TestDetectPasswordLoginErrorHTML(t *testing.T) {
|
||||
// msg 保存msg,供当前处理流程使用
|
||||
// msg 用于本次流程后续判断的msg
|
||||
msg := detectPasswordLoginErrorHTML(`<div class="login-error-msg">账号或密码错误</div>`)
|
||||
if msg != "账号或密码错误" {
|
||||
t.Fatalf("登录错误识别=%q", msg)
|
||||
@@ -46,11 +46,11 @@ func TestDetectPasswordLoginErrorHTML(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDetectPasswordVerificationHTML 负责TestDetect密码VerificationHTML相关处理。
|
||||
// TestDetectPasswordVerificationHTML 封装TestDetect密码VerificationHTML业务协调。
|
||||
func TestDetectPasswordVerificationHTML(t *testing.T) {
|
||||
// html 保存html,供当前处理流程使用
|
||||
// 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 用于本次流程后续判断的event、ok
|
||||
event, ok := detectPasswordVerificationHTML(html)
|
||||
if !ok {
|
||||
t.Fatal("应识别人脸验证")
|
||||
@@ -63,7 +63,7 @@ func TestDetectPasswordVerificationHTML(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestQuickEnterCookiesUsableRequiresUNB 负责TestQuickEnterCookiesUsableRequiresUNB相关处理。
|
||||
// TestQuickEnterCookiesUsableRequiresUNB 封装TestQuickEnterCookiesUsableRequiresUNB业务协调。
|
||||
func TestQuickEnterCookiesUsableRequiresUNB(t *testing.T) {
|
||||
if quickEnterCookiesUsable(map[string]string{"_m_h5_tk": "tk"}) {
|
||||
t.Fatal("快速进入未拿到 unb 不应视为成功")
|
||||
@@ -76,7 +76,7 @@ func TestQuickEnterCookiesUsableRequiresUNB(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPasswordLoginReferenceProfileAndTiming 负责Test密码登录ReferenceProfileAndTiming相关处理。
|
||||
// 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 {
|
||||
@@ -89,7 +89,7 @@ func TestPasswordLoginReferenceProfileAndTiming(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPasswordPersistentContextOptionsMatchReference 负责Test密码Persistent上下文OptionsMatchReference相关处理。
|
||||
// TestPasswordPersistentContextOptionsMatchReference 封装Test密码Persistent上下文OptionsMatchReference业务协调。
|
||||
func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) {
|
||||
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "/opt/chromium")
|
||||
// userAgent 模拟从同版本 Chromium 实测后规范化出的无头身份。
|
||||
@@ -127,9 +127,9 @@ func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit 负责Test密码登录RejectsBlankCredentialsBefore浏览器Init相关处理。
|
||||
// TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit 封装Test密码登录RejectsBlankCredentialsBefore浏览器Init业务协调。
|
||||
func TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit(t *testing.T) {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 用于本次流程后续判断的m
|
||||
m := &Manager{}
|
||||
// tc 表示当前遍历过程中的tc
|
||||
for _, tc := range []struct {
|
||||
@@ -140,7 +140,7 @@ func TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit(t *testing.T) {
|
||||
{account: "account", password: ""},
|
||||
{account: " ", password: "secret"},
|
||||
} {
|
||||
// err 保存err,供当前处理流程使用
|
||||
// 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)
|
||||
|
||||
@@ -2,7 +2,7 @@ package browser
|
||||
|
||||
import "strings"
|
||||
|
||||
// PasswordLoginStatusProcessing 保存密码登录状态Processing,供当前处理流程使用
|
||||
// PasswordLoginStatusProcessing 用于本次流程后续判断的密码登录状态Processing
|
||||
const (
|
||||
PasswordLoginStatusProcessing = "processing"
|
||||
PasswordLoginStatusVerificationRequired = "verification_required"
|
||||
@@ -21,10 +21,10 @@ type PasswordLoginEvent struct {
|
||||
CooldownHours int
|
||||
}
|
||||
|
||||
// PasswordLoginEventHandler 保存密码登录EventHandler,供当前处理流程使用
|
||||
// PasswordLoginEventHandler 用于本次流程后续判断的密码登录EventHandler
|
||||
type PasswordLoginEventHandler func(PasswordLoginEvent)
|
||||
|
||||
// PasswordLoginEventFromError 负责密码登录EventFrom错误相关处理。
|
||||
// PasswordLoginEventFromError 封装密码登录EventFrom错误业务协调。
|
||||
func PasswordLoginEventFromError(err error) PasswordLoginEvent {
|
||||
if err == nil {
|
||||
return PasswordLoginEvent{}
|
||||
@@ -32,11 +32,11 @@ func PasswordLoginEventFromError(err error) PasswordLoginEvent {
|
||||
return PasswordLoginEventFromMessage(err.Error())
|
||||
}
|
||||
|
||||
// PasswordLoginEventFromMessage 负责密码登录EventFrom消息相关处理。
|
||||
// PasswordLoginEventFromMessage 封装密码登录EventFrom消息业务协调。
|
||||
func PasswordLoginEventFromMessage(msg string) PasswordLoginEvent {
|
||||
// lower 保存lower,供当前处理流程使用
|
||||
// lower 用于本次流程后续判断的lower
|
||||
lower := strings.ToLower(msg)
|
||||
// event 保存event,供当前处理流程使用
|
||||
// event 用于本次流程后续判断的event
|
||||
event := PasswordLoginEvent{Status: PasswordLoginStatusFailed, Message: msg, Error: msg}
|
||||
switch {
|
||||
case IsBaxiaPunishMessage(msg) || (strings.Contains(msg, "风控") && strings.Contains(msg, "图形验证")):
|
||||
@@ -48,9 +48,9 @@ func PasswordLoginEventFromMessage(msg string) PasswordLoginEvent {
|
||||
return event
|
||||
}
|
||||
|
||||
// IsBaxiaPunishMessage 负责IsBaxiaPunish消息相关处理。
|
||||
// IsBaxiaPunishMessage 封装IsBaxiaPunish消息业务协调。
|
||||
func IsBaxiaPunishMessage(msg string) bool {
|
||||
// lower 保存lower,供当前处理流程使用
|
||||
// lower 用于本次流程后续判断的lower
|
||||
lower := strings.ToLower(msg)
|
||||
return strings.Contains(lower, "baxia") ||
|
||||
strings.Contains(lower, "punish") ||
|
||||
|
||||
@@ -5,25 +5,25 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestPasswordLoginEventFromErrorVerification 负责Test密码登录EventFrom错误Verification相关处理。
|
||||
// TestPasswordLoginEventFromErrorVerification 封装Test密码登录EventFrom错误Verification业务协调。
|
||||
func TestPasswordLoginEventFromErrorVerification(t *testing.T) {
|
||||
// event 保存event,供当前处理流程使用
|
||||
// event 用于本次流程后续判断的event
|
||||
event := PasswordLoginEventFromError(errors.New("需要人脸验证"))
|
||||
if event.Status != PasswordLoginStatusVerificationRequired {
|
||||
t.Fatalf("status=%q want verification_required", event.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPasswordLoginEventFromErrorBaxia 负责Test密码登录EventFrom错误Baxia相关处理。
|
||||
// TestPasswordLoginEventFromErrorBaxia 封装Test密码登录EventFrom错误Baxia业务协调。
|
||||
func TestPasswordLoginEventFromErrorBaxia(t *testing.T) {
|
||||
// event 保存event,供当前处理流程使用
|
||||
// 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消息相关处理。
|
||||
// TestIsBaxiaPunishMessage 封装TestIsBaxiaPunish消息业务协调。
|
||||
func TestIsBaxiaPunishMessage(t *testing.T) {
|
||||
// msg 表示当前遍历过程中的msg
|
||||
for _, msg := range []string{"baxia-punish", "scratch-captcha-container", "找两个松鼠"} {
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
// TestSanitize 特殊字符替换为下划线(用于 userDataDir 命名)。
|
||||
func TestSanitize(t *testing.T) {
|
||||
// cases 保存cases,供当前处理流程使用
|
||||
// cases 用于本次流程后续判断的cases
|
||||
cases := map[string]string{
|
||||
"acc_1": "acc_1",
|
||||
"acc/1:2 3": "acc_1_2_3",
|
||||
@@ -19,16 +19,16 @@ func TestSanitize(t *testing.T) {
|
||||
}
|
||||
// in、want 表示当前遍历过程中的in、want
|
||||
for in, want := range cases {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := sanitize(in); got != want {
|
||||
t.Errorf("sanitize(%q)=%q want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPureUserIDMatchesReferenceRule 负责TestPure用户IDMatchesReference规则相关处理。
|
||||
// TestPureUserIDMatchesReferenceRule 封装TestPure用户IDMatchesReference规则业务协调。
|
||||
func TestPureUserIDMatchesReferenceRule(t *testing.T) {
|
||||
// cases 保存cases,供当前处理流程使用
|
||||
// cases 用于本次流程后续判断的cases
|
||||
cases := map[string]string{
|
||||
"foo_1234567890": "foo",
|
||||
"foo_bar_1234567890": "foo_bar",
|
||||
@@ -39,14 +39,14 @@ func TestPureUserIDMatchesReferenceRule(t *testing.T) {
|
||||
}
|
||||
// in、want 表示当前遍历过程中的in、want
|
||||
for in, want := range cases {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := pureUserID(in); got != want {
|
||||
t.Fatalf("pureUserID(%q)=%q want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides 负责TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides相关处理。
|
||||
// TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides 封装TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides业务协调。
|
||||
func TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides(t *testing.T) {
|
||||
t.Setenv("BROWSER_HEADLESS", "")
|
||||
if !quickRenewHeadless(true) {
|
||||
@@ -65,7 +65,7 @@ func TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveHeadlessUsesShowBrowserConsistently 负责TestResolveHeadlessUsesShow浏览器Consistently相关处理。
|
||||
// TestResolveHeadlessUsesShowBrowserConsistently 封装TestResolveHeadlessUsesShow浏览器Consistently业务协调。
|
||||
func TestResolveHeadlessUsesShowBrowserConsistently(t *testing.T) {
|
||||
t.Setenv("BROWSER_HEADLESS", "")
|
||||
if !ResolveHeadless(false) {
|
||||
@@ -84,7 +84,7 @@ func TestResolveHeadlessUsesShowBrowserConsistently(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCookiesRefreshHeadlessUsesAccountPreference 负责TestCookiesRefreshHeadlessUses账号Preference相关处理。
|
||||
// TestCookiesRefreshHeadlessUsesAccountPreference 封装TestCookiesRefreshHeadlessUses账号Preference业务协调。
|
||||
func TestCookiesRefreshHeadlessUsesAccountPreference(t *testing.T) {
|
||||
t.Setenv("BROWSER_HEADLESS", "")
|
||||
if !cookiesRefreshHeadless(true) {
|
||||
@@ -99,14 +99,14 @@ func TestCookiesRefreshHeadlessUsesAccountPreference(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestChromiumExecutablePathFromEnv 负责TestChromiumExecutable路径FromEnv相关处理。
|
||||
// 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 用于本次流程后续判断的got
|
||||
got := chromiumExecutablePath()
|
||||
if got == nil || *got != "/usr/bin/chromium" {
|
||||
t.Fatalf("chromiumExecutablePath=%v", got)
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
// QRCookieRefresh 用扫码临时 cookie + 风控验证 URL,通过浏览器换取真实 cookie(含 unb)。
|
||||
// verificationURL 为空时跳过验证步骤(无风控场景)。
|
||||
// QRCookieRefresh 负责QR登录凭证Refresh相关处理。
|
||||
// QRCookieRefresh 封装QR登录凭证Refresh业务协调。
|
||||
func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (realCookies string, unb string, err error) {
|
||||
// err 表示管理器已关闭或调用方已取消,不能启动一次性二维码浏览器。
|
||||
if err := m.beginOperation(ctx); err != nil {
|
||||
@@ -24,7 +24,7 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
if tmpCookies == "" {
|
||||
return "", "", fmt.Errorf("扫码临时 cookie 为空")
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := m.init(); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
@@ -42,7 +42,7 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
}
|
||||
defer func() { _ = browser.Close() }()
|
||||
|
||||
// bctx、err 保存bctx、err,供当前处理流程使用
|
||||
// bctx、err 用于本次流程后续判断的bctx、err
|
||||
bctx, err := browser.NewContext(playwright.BrowserNewContextOptions{
|
||||
Viewport: &playwright.Size{Width: 1100, Height: 760},
|
||||
Locale: playwright.String(defaultLang),
|
||||
@@ -54,11 +54,11 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
}
|
||||
defer func() { _ = bctx.Close() }()
|
||||
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
|
||||
m.logger.Warn("注入 stealth 脚本失败", "err", err)
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := addCookieStr(bctx, tmpCookies); err != nil {
|
||||
return "", "", fmt.Errorf("注入临时 cookie 失败: %w", err)
|
||||
}
|
||||
@@ -74,7 +74,7 @@ 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 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := page.Goto(verificationURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(15000),
|
||||
@@ -85,10 +85,10 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
// 等待用户完成手机验证,页面会 redirect 到 ivCheckLogin.htm(最多3分钟)。
|
||||
// 每2秒截图一次并通过 onScreenshot 回调发给前端,用户可直接看到验证页面。
|
||||
m.logger.Info("等待验证完成(监测页面 redirect + 截图推送)...")
|
||||
// deadline 保存deadline,供当前处理流程使用
|
||||
// deadline 用于本次流程后续判断的deadline
|
||||
deadline := time.Now().Add(3 * time.Minute)
|
||||
for time.Now().Before(deadline) {
|
||||
// u 保存u,供当前处理流程使用
|
||||
// u 用于本次流程后续判断的u
|
||||
u := page.URL()
|
||||
if strings.Contains(u, "ivCheckLogin") {
|
||||
m.logger.Info("验证通过,页面已跳转", "url", logsafe.URL(u))
|
||||
@@ -96,7 +96,7 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
}
|
||||
// 截图并回调给前端。
|
||||
if onScreenshot != nil {
|
||||
if // img、err2 保存img、err2,供当前处理流程使用
|
||||
if // img、err2 用于本次流程后续判断的img、err2
|
||||
img, err2 := page.Screenshot(); err2 == nil {
|
||||
onScreenshot("data:image/png;base64," + base64.StdEncoding.EncodeToString(img))
|
||||
}
|
||||
@@ -112,7 +112,7 @@ 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 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(20000),
|
||||
@@ -124,14 +124,14 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
|
||||
// 轮询直到 unb 出现或超时(最长15秒)。
|
||||
var all []playwright.Cookie
|
||||
// deadline 保存deadline,供当前处理流程使用
|
||||
// deadline 用于本次流程后续判断的deadline
|
||||
deadline := time.Now().Add(15 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
// err2 保存err2,供当前处理流程使用
|
||||
// err2 用于本次流程后续判断的err2
|
||||
var err2 error
|
||||
all, err2 = bctx.Cookies()
|
||||
if err2 == nil {
|
||||
if // m2 保存m2,供当前处理流程使用
|
||||
if // m2 用于本次流程后续判断的m2
|
||||
m2 := cookiesToMap(all); m2["unb"] != "" {
|
||||
m.logger.Info("轮询拿到 unb")
|
||||
break
|
||||
@@ -146,15 +146,15 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
return "", "", fmt.Errorf("提取 cookie 失败: %w", err)
|
||||
}
|
||||
}
|
||||
// cookieMap 保存登录凭证Map,供当前处理流程使用
|
||||
// cookieMap 用于本次流程后续判断的登录凭证Map
|
||||
cookieMap := cookiesToMap(all)
|
||||
// cookieStr 保存登录凭证Str,供当前处理流程使用
|
||||
// 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 保存v、ok,供当前处理流程使用
|
||||
if // v、ok 用于本次流程后续判断的v、ok
|
||||
v, ok := cookieMap[k]; ok {
|
||||
m.logger.Info("cookie字段", "name", k, "len", len(v))
|
||||
} else {
|
||||
|
||||
@@ -3,7 +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,供当前处理流程使用
|
||||
// stealthTemplate 用于本次流程后续判断的stealthTemplate
|
||||
const stealthTemplate = `
|
||||
(() => {
|
||||
try {
|
||||
|
||||
@@ -6,34 +6,34 @@ import (
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
// TestCredentialCookieSnapshotPreservesChromiumAttributes 负责TestCredential登录凭证SnapshotPreservesChromiumAttributes相关处理。
|
||||
// TestCredentialCookieSnapshotPreservesChromiumAttributes 封装TestCredential登录凭证SnapshotPreservesChromiumAttributes业务协调。
|
||||
func TestCredentialCookieSnapshotPreservesChromiumAttributes(t *testing.T) {
|
||||
// existing 保存existing,供当前处理流程使用
|
||||
// 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 用于本次流程后续判断的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 用于本次流程后续判断的by名称
|
||||
byName := map[string]cookierefresh.BrowserCookie{}
|
||||
// cookie 表示当前遍历过程中的登录凭证
|
||||
for _, cookie := range got {
|
||||
byName[cookie.Name] = cookie
|
||||
}
|
||||
// cookie2 保存cookie2,供当前处理流程使用
|
||||
// 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 保存unb,供当前处理流程使用
|
||||
if // unb 用于本次流程后续判断的unb
|
||||
unb := byName["unb"]; unb.Domain != goofishDot || unb.Path != "/" {
|
||||
t.Fatalf("new cookie defaults=%+v", unb)
|
||||
}
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
if // ok 用于本次流程后续判断的ok
|
||||
_, ok := byName["stale"]; ok {
|
||||
t.Fatal("cookie absent from current snapshot must be removed")
|
||||
}
|
||||
|
||||
@@ -9,14 +9,14 @@ import (
|
||||
|
||||
// resolvePersistentUserDataDir prepares the profile directory required by
|
||||
// Playwright's LaunchPersistentContext. playwright-go rejects relative paths.
|
||||
// resolvePersistentUserDataDir 负责resolvePersistent用户数据Dir相关处理。
|
||||
// resolvePersistentUserDataDir 封装resolvePersistent用户数据Dir业务协调。
|
||||
func resolvePersistentUserDataDir(path string) (string, error) {
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("持久化浏览器用户数据目录不能为空")
|
||||
}
|
||||
|
||||
// absPath、err 保存absPath、err,供当前处理流程使用
|
||||
// absPath、err 用于本次流程后续判断的absPath、err
|
||||
absPath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("解析持久化浏览器用户数据目录失败: %w", err)
|
||||
@@ -25,7 +25,7 @@ func resolvePersistentUserDataDir(path string) (string, error) {
|
||||
if !filepath.IsAbs(absPath) {
|
||||
return "", fmt.Errorf("持久化浏览器用户数据目录不是绝对路径: %s", absPath)
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := os.MkdirAll(absPath, 0o700); err != nil {
|
||||
return "", fmt.Errorf("创建持久化浏览器用户数据目录失败: %w", err)
|
||||
}
|
||||
|
||||
@@ -7,22 +7,22 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestResolvePersistentUserDataDirConvertsRelativePathAndCreatesDirectory 负责TestResolvePersistent用户数据DirConvertsRelative路径AndCreatesDirectory相关处理。
|
||||
// TestResolvePersistentUserDataDirConvertsRelativePathAndCreatesDirectory 封装TestResolvePersistent用户数据DirConvertsRelative路径AndCreatesDirectory业务协调。
|
||||
func TestResolvePersistentUserDataDirConvertsRelativePathAndCreatesDirectory(t *testing.T) {
|
||||
// cwd、err 保存cwd、err,供当前处理流程使用
|
||||
// cwd、err 用于本次流程后续判断的cwd、err
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("Getwd: %v", err)
|
||||
}
|
||||
// target 保存target,供当前处理流程使用
|
||||
// target 用于本次流程后续判断的target
|
||||
target := filepath.Join(t.TempDir(), "nested", "profile")
|
||||
// relative、err 保存relative、err,供当前处理流程使用
|
||||
// relative、err 用于本次流程后续判断的relative、err
|
||||
relative, err := filepath.Rel(cwd, target)
|
||||
if err != nil {
|
||||
t.Fatalf("Rel: %v", err)
|
||||
}
|
||||
|
||||
// got、err 保存got、err,供当前处理流程使用
|
||||
// got、err 用于本次流程后续判断的got、err
|
||||
got, err := resolvePersistentUserDataDir(relative)
|
||||
if err != nil {
|
||||
t.Fatalf("resolvePersistentUserDataDir: %v", err)
|
||||
@@ -33,7 +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 用于本次流程后续判断的info、err
|
||||
info, err := os.Stat(got)
|
||||
if err != nil {
|
||||
t.Fatalf("Stat: %v", err)
|
||||
@@ -43,11 +43,11 @@ func TestResolvePersistentUserDataDirConvertsRelativePathAndCreatesDirectory(t *
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolvePersistentUserDataDirPreservesAbsolutePath 负责TestResolvePersistent用户数据DirPreservesAbsolute路径相关处理。
|
||||
// TestResolvePersistentUserDataDirPreservesAbsolutePath 封装TestResolvePersistent用户数据DirPreservesAbsolute路径业务协调。
|
||||
func TestResolvePersistentUserDataDirPreservesAbsolutePath(t *testing.T) {
|
||||
// target 保存target,供当前处理流程使用
|
||||
// target 用于本次流程后续判断的target
|
||||
target := filepath.Join(t.TempDir(), "profile")
|
||||
// got、err 保存got、err,供当前处理流程使用
|
||||
// got、err 用于本次流程后续判断的got、err
|
||||
got, err := resolvePersistentUserDataDir(" " + target + " ")
|
||||
if err != nil {
|
||||
t.Fatalf("resolvePersistentUserDataDir: %v", err)
|
||||
@@ -57,24 +57,24 @@ func TestResolvePersistentUserDataDirPreservesAbsolutePath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolvePersistentUserDataDirRejectsEmptyPath 负责TestResolvePersistent用户数据DirRejectsEmpty路径相关处理。
|
||||
// TestResolvePersistentUserDataDirRejectsEmptyPath 封装TestResolvePersistent用户数据DirRejectsEmpty路径业务协调。
|
||||
func TestResolvePersistentUserDataDirRejectsEmptyPath(t *testing.T) {
|
||||
// err 保存err,供当前处理流程使用
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := resolvePersistentUserDataDir(" ")
|
||||
if err == nil || !strings.Contains(err.Error(), "不能为空") {
|
||||
t.Fatalf("空路径应返回明确错误,got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolvePersistentUserDataDirReportsCreateFailure 负责TestResolvePersistent用户数据DirReportsCreateFailure相关处理。
|
||||
// TestResolvePersistentUserDataDirReportsCreateFailure 封装TestResolvePersistent用户数据DirReportsCreateFailure业务协调。
|
||||
func TestResolvePersistentUserDataDirReportsCreateFailure(t *testing.T) {
|
||||
// parentFile 保存parent文件,供当前处理流程使用
|
||||
// parentFile 用于本次流程后续判断的parent文件
|
||||
parentFile := filepath.Join(t.TempDir(), "file")
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := os.WriteFile(parentFile, []byte("not a directory"), 0o600); err != nil {
|
||||
t.Fatalf("WriteFile: %v", err)
|
||||
}
|
||||
// err 保存err,供当前处理流程使用
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := resolvePersistentUserDataDir(filepath.Join(parentFile, "profile"))
|
||||
if err == nil || !strings.Contains(err.Error(), "创建") {
|
||||
t.Fatalf("目录创建失败应返回明确错误,got %v", err)
|
||||
|
||||
Reference in new issue
Block a user