screenshot.py 36.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
# -*- coding: utf-8 -*-
"""截真实 DMS 页面:把已登录状态交给浏览器,直接打开目标 URL 后截图。
唯一的点击是采购单详情的「下一页」:明细分页显示时逐页翻页截图,直到最后一页(_page_through),截全所有零件。

浏览器 profile 按账号保留(缓存和 Cookie 都在),首屏快。一次截图只开一个浏览器,各策略复用(不再关了重开,
避免短时间内对 auth-api 新建大量连接);只有轮到需要有界面的 ui 策略而当前是无界面时才重开一次。

auth-api 断连对策(browser/relay.py):浏览器访问 auth-api 时由取数端代发,断开自动重试,预检本地答复。
无界面时浏览器标识换成普通 Chrome(去掉 HeadlessChrome)。页面卡在 callback 时像人一样刷新一次。

登录态策略(云端运行参数 strategies,按云端配置的顺序在同一个浏览器里尝试,全部失败则报错,不画替代图):
  ui     浏览器模拟人工登录(browser/ui_login.py):IAM 登录页上真实点击、逐字输入、点登录;
         ui_confirm=true 时每步在页面上等人确认(有界面,需要前台运行)。成功后 token 同步给接口会话。
         浏览器登录后真站的 token 只在 localStorage["Authorization"](JSON 字符串 "Bearer eyJ...",带引号),
         Cookie 里没有;读取统一走 ui_login._read_token(优先用代发截获的 iam-oauth 响应,再规整存储值)。
         目标页要靠接口查(如最新采购单)时,capture 在登录成功后才查,用的就是浏览器这次的 token。
  token  把 HTTP 登录得到的 Cookie 全部交给浏览器,再把 token 写进 DMS 域名下的
         Cookie[token_storage_key](真实 DMS 前端用 js-cookie 读 Cookies.get("Authorization"))和 localStorage。
         真机实测(2026-10-21)只有 "Bearer xxx" 能用,默认 bearer;auto 时先试 bearer、不行再试 raw。
  sso    把 IAM 下发的 SSO Cookie 灌进浏览器,打开 IAM 授权入口,让 DMS 前端自己走 callback 登录
         (callback 卡住时重开授权入口,最多 sso_attempts 次);成功后把浏览器拿到的新 token 同步回 HTTP 会话,
         防止单会话的 DMS 把 HTTP 的 token 踢掉、下一个任务又要输密码。
判定成功:地址停在 DMS 域(不在 IAM 登录页),且页面文字包含期望内容(如采购单号)。
每个策略失败时,把浏览器当时的样子截一张 debug_<策略>.png,并把地址、Cookie 名、localStorage 键、
失败的网络请求、页面 JS 报错写进 debug_<策略>.json(不含 Cookie/token 的值),方便定位。
审计:结果目录里 audit.jsonl / audit.html(每一步时间线 + 截图)、browser.har(浏览器请求)、http.har(取数端请求)。
"""
import hashlib
import json
import logging
import os
import time
import urllib.parse

from . import cdp, ui_login
from .cdp import CdpError, Chrome
from .confirm import ConfirmPanel
from .relay import AuthRelay
from ..connectors.base import AuthExpired, LoginError, LoginRejected
from ..connectors.gtmc import auth
from ..core import tasks
from ..infra import har as harmod
from ..infra.audit import AuditTrail
from ..infra.logs import scrub
from ..infra.tokens import describe

log = logging.getLogger("edge")


class ScreenshotError(Exception):
    pass


def po_detail_url(cfg, row):
    """与 DMS 前端一致:把采购单列表行的全部字段拼成 query(值为 null 的只写键名),再加 pageStatus=read。"""
    parts = []
    for k, v in row.items():
        if isinstance(v, (dict, list)):
            continue
        parts.append(k if v is None else "%s=%s" % (k, urllib.parse.quote(str(v), safe="")))
    parts.append("pageStatus=read")
    return "%s%s?%s" % (cfg.dms_url, cfg.po_detail_path, "&".join(parts))


def po_list_url(cfg):
    return cfg.dms_url + cfg.po_list_path


def _page_state(chrome):
    v = chrome.evaluate("JSON.stringify([location.href, document.readyState,"
                        "(document.body && document.body.innerText || '').slice(0, 50000)])")
    if not v:
        return "", "", ""
    href, ready, text = json.loads(v)
    return href, ready, text


def _wait_for(chrome, cfg, must_contain, what):
    """等页面出现期望文字。落到 IAM 登录页持续 4 秒即判定登录态无效(快速失败)。
    过了一半时间还没出来(卡在 callback / 菜单没加载)就像人一样刷新一次(page_refresh_retries 次)。"""
    t0 = time.time()
    deadline = t0 + cfg.page_timeout
    at_iam_since = None
    href = text = ""
    refreshed = 0
    while time.time() < deadline:
        if time.time() - t0 > cfg.page_timeout / 2 * (refreshed + 1) and refreshed < getattr(cfg, "page_refresh_retries", 0):
            refreshed += 1
            log.warning("%s:%d 秒还没加载出来(当前 %s),刷新一次(第 %d 次)", what, int(time.time() - t0),
                        href.split("?")[0] or "空", refreshed)
            try:
                chrome.reload()
            except CdpError:
                pass
            deadline = max(deadline, time.time() + cfg.page_timeout / 2)
        href, ready, text = _page_state(chrome)
        if href.startswith(cfg.iam_base):
            at_iam_since = at_iam_since or time.time()
            if time.time() - at_iam_since > 4:
                raise ScreenshotError("%s:被跳转到 IAM 登录页,登录态无效" % what)
        else:
            at_iam_since = None
            if href.startswith(cfg.dms_url) and ready == "complete" and all(m in text for m in must_contain):
                return href
        time.sleep(0.5)
    miss = [m for m in must_contain if m not in text]
    raise ScreenshotError("%s:%d 秒内页面没出现 %s(当前地址 %s)" % (
        what, int(cfg.page_timeout), "、".join(miss) or "完整内容", href.split("?")[0] or "空"))


def _dms_origin(cfg):
    p = urllib.parse.urlparse(cfg.dms_url)
    return "%s://%s" % (p.scheme, p.netloc)


def _give_jar_cookies(chrome, session):
    """把 HTTP 登录过程中拿到的全部 Cookie(IAM SSO + auth-api 下发的 dms*)交给浏览器。"""
    cookies = []
    for c in session.client.jar:
        item = {"name": c.name, "value": c.value, "domain": c.domain, "path": c.path or "/",
                "secure": bool(c.secure), "httpOnly": bool(c.has_nonstandard_attr("HttpOnly"))}
        if c.expires:
            item["expires"] = float(c.expires)
        cookies.append(item)
    if cookies:
        chrome.send("Network.setCookies", {"cookies": cookies})
    return cookies


def _token_formats(cfg):
    return ["bearer", "raw"] if cfg.token_storage_format == "auto" else [cfg.token_storage_format]


def _set_token(chrome, cfg, session, fmt, state):
    """按配置把 token 写进 Cookie 和/或 localStorage。Cookie 值按 js-cookie 的规则编码(空格 → %20)。"""
    tok = session.token.value
    val = ("Bearer " + tok) if fmt == "bearer" else tok
    origin = _dms_origin(cfg)
    if "cookie" in cfg.token_storage:
        chrome.send("Network.setCookie", {"name": cfg.token_storage_key, "value": urllib.parse.quote(val, safe=""),
                                          "url": origin + "/", "path": "/", "secure": origin.startswith("https")})
    if "localstorage" in cfg.token_storage:
        if state.get("script"):
            chrome.send("Page.removeScriptToEvaluateOnNewDocument", {"identifier": state["script"]})
        js = ("if (location.href.indexOf(%s) === 0) { try { localStorage.setItem(%s, %s); } catch (e) {} }"
              % (json.dumps(origin), json.dumps(cfg.token_storage_key), json.dumps(val)))
        state["script"] = chrome.send("Page.addScriptToEvaluateOnNewDocument", {"source": js}).get("identifier")


def _login_token(chrome, cfg, session, first_target):
    """token 策略:给 Cookie + 写 token,打开第一个目标页验证;auto 格式时 raw 不行再试 bearer。"""
    n = len(_give_jar_cookies(chrome, session))
    fname, url, must = first_target[:3]
    errors, state = [], {}
    for fmt in _token_formats(cfg):
        _set_token(chrome, cfg, session, fmt, state)
        log.info("token:已交给浏览器 %d 个 Cookie,token 写入 %s(格式 %s),打开 %s",
                 n, "+".join(cfg.token_storage), fmt, url.split("?")[0])
        chrome.navigate(url)
        try:
            _wait_for(chrome, cfg, must, "token(%s)/%s" % (fmt, fname))
            log.info("截图登录态可用:token 策略,格式 %s", fmt)
            return
        except ScreenshotError as e:
            errors.append(str(e))
            log.warning("token 格式 %s 不行:%s", fmt, e)
    raise ScreenshotError(";".join(errors))


def _login_sso(chrome, cfg, session, first_target):
    cookies = _give_jar_cookies(chrome, session)
    if not cookies:
        raise ScreenshotError("sso:HTTP 会话里没有 IAM Cookie,无法交给浏览器")
    href = ""
    fname, url, must = first_target[:3]
    for i in range(max(1, cfg.sso_attempts)):
        log.info("sso:已把 %d 个 Cookie 交给浏览器,打开授权入口让 DMS 前端自行登录(第 %d/%d 次)",
                 len(cookies), i + 1, cfg.sso_attempts)
        chrome.navigate(auth.authorize_url(cfg))
        deadline = time.time() + cfg.page_timeout
        while time.time() < deadline:
            href, ready, _ = _page_state(chrome)
            if href.startswith(cfg.dms_url) and "/iam/auth/callback" not in href and ready == "complete":
                _adopt_browser_token(chrome, cfg, session)
                chrome.navigate(url)
                _wait_for(chrome, cfg, must, "sso/%s" % fname)
                return
            time.sleep(0.5)
        bad = [p for p in chrome.problems if "auth-api" in p["url"] or "iam-oauth" in p["url"]]
        log.warning("sso:%d 秒内没有从 callback 回到 DMS(当前 %s)%s", int(cfg.page_timeout), href.split("?")[0],
                    ";auth-api 请求问题:%s" % ",".join("%s %s" % (p["kind"], p["detail"]) for p in bad[-3:]) if bad else "")
    raise ScreenshotError("sso:试了 %d 次,都没有从 IAM 回到 DMS(当前 %s)" % (cfg.sso_attempts, href.split("?")[0]))


_STATE_JS = """JSON.stringify({href: location.href, title: document.title,
  local_storage_keys: (function(){ try { return Object.keys(localStorage); } catch (e) { return ['<读不到>']; } })(),
  session_storage_keys: (function(){ try { return Object.keys(sessionStorage); } catch (e) { return ['<读不到>']; } })(),
  text: (document.body && document.body.innerText || '').slice(0, 800)})"""


_TOKEN_STORAGE_JS = """JSON.stringify((function(key){ var out = {};
  try { for (var i = 0; i < localStorage.length; i++) { var k = localStorage.key(i);
    if (k === key || /authori|token/i.test(k)) out[k] = localStorage.getItem(k); } } catch (e) {}
  return out; })(%s))"""


def _token_shapes(chrome, cfg):
    """token 相关存储项的「形态」(长度 / 是否 JSON 引号 / 是否带 Bearer / 指纹 / exp),不记任何值。
    同一个 token 指纹相同,可以和 HAR 里 Authorization 的指纹直接比对。"""
    key = cfg.token_storage_key
    out = {}
    try:
        for k, v in (json.loads(chrome.evaluate(_TOKEN_STORAGE_JS % json.dumps(key)) or "{}") or {}).items():
            out["localStorage." + k] = describe(v)
        for c in chrome.send("Network.getAllCookies").get("cookies") or []:
            if c.get("name") == key:
                out["cookie.%s@%s" % (key, c.get("domain"))] = describe(urllib.parse.unquote(c.get("value") or ""))
    except Exception as e:  # noqa: BLE001
        out["error"] = repr(e)
    issued = getattr(getattr(chrome, "relay", None), "issued_token", None)
    out["relay.issued_token"] = describe(issued) if issued else "无"
    return out


def _debug_dump(chrome, cfg, out_dir, strategy, err):
    """策略失败时:截浏览器当前画面 + 记录地址 / Cookie 名 / storage 键 / 失败请求 / JS 报错(不记任何值)。"""
    info = {"strategy": strategy, "error": str(err), "time": time.strftime("%Y-%m-%d %H:%M:%S")}
    try:
        info.update(json.loads(chrome.evaluate(_STATE_JS) or "{}"))
    except Exception as e:  # noqa: BLE001
        info["state_error"] = repr(e)
    try:
        info["cookies"] = ["%s @%s (%d字节)" % (c.get("name"), c.get("domain"), len(c.get("value") or ""))
                           for c in chrome.send("Network.getAllCookies").get("cookies") or []]
    except Exception as e:  # noqa: BLE001
        info["cookies"] = ["<读取失败 %r>" % e]
    info["token_shapes"] = _token_shapes(chrome, cfg)
    info["problems"] = list(chrome.problems)
    png = os.path.join(out_dir, "debug_%s.png" % strategy)
    try:
        chrome.screenshot(png)
        info["screenshot"] = os.path.basename(png)
    except Exception as e:  # noqa: BLE001
        info["screenshot_error"] = repr(e)
    with open(os.path.join(out_dir, "debug_%s.json" % strategy), "w", encoding="utf-8") as f:
        f.write(scrub(json.dumps(info, ensure_ascii=False, indent=2)))
    log.warning("截图诊断(%s):停在 %s,标题「%s」,浏览器 Cookie %d 个,localStorage 键 %s,失败请求/报错 %d 条%s",
                strategy, scrub(str(info.get("href", "")).split("?")[0]), info.get("title", ""),
                len(info.get("cookies") or []), info.get("local_storage_keys"), len(info["problems"]),
                ":" + scrub(";".join("%s %s %s" % (p["kind"], p["url"].split("?")[0], p["detail"])
                                      for p in info["problems"][-4:])) if info["problems"] else "")


_NO_SCROLLBAR_JS = r"""(function(){
  if (document.getElementById('__rp_noscroll')) return 0;
  var st = document.createElement('style'); st.id = '__rp_noscroll';
  st.textContent = '::-webkit-scrollbar{width:0!important;height:0!important;display:none!important}*{scrollbar-width:none!important}';
  (document.head || document.documentElement).appendChild(st); return 1; })()"""

# 横向:页面里还需要多宽才不出现横向滚动(整页 + 内部 overflow:auto/scroll 的区域)
_EXTRA_WIDTH_JS = r"""(function(){
  var extra = Math.max(0, document.documentElement.scrollWidth - window.innerWidth);
  var els = document.querySelectorAll('*');
  for (var i = 0; i < els.length && i < 20000; i++) { var e = els[i], cs = getComputedStyle(e);
    if ((cs.overflowX == 'auto' || cs.overflowX == 'scroll') && e.scrollWidth > e.clientWidth + 2)
      extra = Math.max(extra, e.scrollWidth - e.clientWidth); }
  return extra; })()"""

# 纵向:把固定高度、内部滚动的区域展开(表格等),返回展开了几个
_EXPAND_Y_JS = r"""(function(){
  var n = 0, els = document.querySelectorAll('*');
  for (var i = 0; i < els.length && i < 20000; i++) { var e = els[i];
    if (e === document.documentElement || e === document.body) continue;
    var cs = getComputedStyle(e);
    if ((cs.overflowY == 'auto' || cs.overflowY == 'scroll') && e.scrollHeight > e.clientHeight + 2) {
      e.style.setProperty('height', 'auto', 'important'); e.style.setProperty('max-height', 'none', 'important');
      e.style.setProperty('overflow-y', 'visible', 'important'); n++; } }
  return n; })()"""

_CONTENT_HEIGHT_JS = r"""(function(){
  var h = Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0);
  var els = document.querySelectorAll('body *');
  for (var i = 0; i < els.length && i < 20000; i++) { var r = els[i].getBoundingClientRect();
    if (r.height > 0) h = Math.max(h, r.bottom + window.scrollY); }
  return Math.ceil(h); })()"""


def _metrics(chrome, cfg, width, height):
    chrome.send("Emulation.setDeviceMetricsOverride", {"width": int(width), "height": int(height),
                                                       "deviceScaleFactor": cfg.device_scale, "mobile": False})


def shoot(chrome, cfg, path):
    """截完整页面、不带滚动条:先加宽到没有横向滚动,再展开内部纵向滚动区,最后把视口设成整页高度再截。"""
    chrome.evaluate(_NO_SCROLLBAR_JS)
    if not cfg.full_page:
        chrome.screenshot(path)
        return path
    width = cfg.viewport_width
    _metrics(chrome, cfg, width, 1000)
    time.sleep(0.8)
    for _ in range(4):                                  # 页面加宽后表格会重新布局,最多迭代几次
        extra = int(chrome.evaluate(_EXTRA_WIDTH_JS) or 0)
        if extra <= 2 or width >= cfg.max_width:
            break
        width = min(width + extra + 24, cfg.max_width)
        _metrics(chrome, cfg, width, 1000)
        time.sleep(0.8)
    if width >= cfg.max_width and int(chrome.evaluate(_EXTRA_WIDTH_JS) or 0) > 2:
        log.warning("页面太宽,加宽到上限 %d 像素仍有横向滚动,截图右侧可能不完整(可调大 max_width)", cfg.max_width)
    if cfg.expand_scroll_areas:
        n = chrome.evaluate(_EXPAND_Y_JS) or 0
        if n:
            log.info("展开了 %d 个内部滚动区域", n)
            time.sleep(0.6)
    height = int(chrome.evaluate(_CONTENT_HEIGHT_JS) or 1000)
    if height > cfg.max_height:
        log.warning("页面高 %d 像素,超过上限 %d,只截上面部分(可调大 max_height)", height, cfg.max_height)
        height = cfg.max_height
    _metrics(chrome, cfg, width, max(height, 600))
    time.sleep(0.8)
    chrome.screenshot(path)
    chrome.send("Emulation.clearDeviceMetricsOverride")
    log.info("整页截图 %dx%d(缩放 %.2f)", width, height, cfg.device_scale)
    return path


# ---------------------------------------------------------------- 详情分页:逐页翻页截图
# 找明细表的分页器(Element UI / Ant Design / vxe / iView,或文字是「下一页」「>」的按钮),返回这一页能看到哪些应截的零件号、
# 「下一页」能不能点、「共 N 条」。act = "click" 时点一下「下一页」。只认页面上看得见的元素。
_PAGER_JS = r"""(function(parts, act){
  function vis(e){ return !!(e && (e.offsetWidth || e.offsetHeight || e.getClientRects().length)); }
  var txt = (document.body && document.body.innerText) || '';
  var seen = parts.filter(function(p){
    return new RegExp('(^|[^0-9A-Za-z])' + p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '([^0-9A-Za-z]|$)').test(txt); });
  var sels = ['.el-pagination', '.ant-pagination', '.vxe-pager', '.ivu-page', '.pagination'];
  var pagers = [];
  sels.forEach(function(s){ document.querySelectorAll(s).forEach(function(e){ if (vis(e) && pagers.indexOf(e) < 0) pagers.push(e); }); });
  var pg = pagers.length ? pagers[pagers.length - 1] : null;
  var next = pg ? pg.querySelector('.btn-next, .ant-pagination-next, .vxe-pager--next-btn, .ivu-page-next, '
                                   + '[aria-label="next page"], [aria-label="Next Page"], [title="下一页"]') : null;
  if (!next) {
    var c = Array.prototype.filter.call(document.querySelectorAll('button, a, li'), function(e){
      var t = ((e.innerText || '') + '').trim() || e.getAttribute('title') || '';
      return vis(e) && /^(下一页|>|›|»)$/.test(t); });
    next = c.length ? c[c.length - 1] : null;
  }
  function off(e){
    if (!e) return true;
    if (e.disabled || e.getAttribute('aria-disabled') === 'true') return true;
    if (/(^|\s|-)disabled(\s|$)/.test(e.className || '')) return true;
    var p = e.parentElement;
    return !!(p && /(^|\s|-)disabled(\s|$)/.test(p.className || ''));
  }
  var m = ((pg && pg.innerText) || txt).match(/共\s*(\d+)\s*条/);
  var out = {seen: seen, pager: !!(pg || next), disabled: off(next), total: m ? +m[1] : null};
  if (act === 'click' && next && !out.disabled) { next.scrollIntoView({block: 'center'}); next.click(); out.clicked = true; }
  return JSON.stringify(out);
})(%s, %s)"""


def _pager(chrome, parts, act="probe"):
    v = chrome.evaluate(_PAGER_JS % (json.dumps(list(parts)), json.dumps(act)))
    return json.loads(v) if v else {"seen": [], "pager": False, "disabled": True, "total": None}


def _page_through(chrome, cfg, out_dir, fname, opts, audit, strategy):
    """详情第 1 页已经截好:有分页且「下一页」能点,就逐页点下一页 → 等新一页的零件号出现 → 截图,直到最后一页。
    opts["parts"] = 这张单全部零件号(DMS 明细顺序);结果写回 opts["result"]:pages 页数 / seen 截到的零件 /
    missing 应截但没截到的 / pager 有没有分页器 / total 页面上的「共 N 条」。返回第 2 页起的文件路径。"""
    parts = [str(x).strip().upper() for x in (opts.get("parts") or []) if str(x).strip()]
    res = opts.setdefault("result", {})
    st = _pager(chrome, parts)
    seen = set(st["seen"])
    files, page = [], 1
    base, ext = os.path.splitext(fname)
    limit = max(int(getattr(cfg, "detail_max_pages", 30) or 30), 1)
    while st["pager"] and not st["disabled"] and page < limit:
        before = set(st["seen"])
        st = _pager(chrome, parts, "click")
        if not st.get("clicked"):
            break
        deadline = time.time() + max(cfg.page_timeout / 2, 10)
        while time.time() < deadline:                    # 等表格换成下一页:出现上一页没有的零件号
            time.sleep(0.5)
            st = _pager(chrome, parts)
            if st["seen"] and set(st["seen"]) != before:
                break
        else:
            log.warning("详情第 %d 页:点了下一页,%d 秒内表格没有换页,停止翻页", page + 1, int(max(cfg.page_timeout / 2, 10)))
            audit.event("page_stuck", "详情第 %d 页没加载出来,停止翻页" % (page + 1))
            break
        page += 1
        time.sleep(cfg.settle_seconds)                  # 等表格渲染完
        st = _pager(chrome, parts)
        seen.update(st["seen"])
        path = os.path.join(out_dir, "%s_p%d%s" % (base, page, ext))
        _stage(chrome, cfg, "截图:采购订单详情第 %d 页" % page, "整页截图保存为 %s" % os.path.basename(path))
        shoot(chrome, cfg, path)
        log.info("截图完成(策略 %s):%s(详情第 %d 页)", strategy, path, page)
        audit.event("shot", "截图完成:%s(详情第 %d 页)" % (os.path.basename(path), page), shot=os.path.basename(path))
        files.append(path)
    if st["pager"] and not st["disabled"] and page >= limit:
        log.warning("采购单详情超过 %d 页,后面的页没有截(缺的零件会用接口数据渲染补一张完整明细)", limit)
    res.update(pages=page, seen=sorted(seen), missing=[x for x in parts if x not in seen], pager=bool(st["pager"]),
               total=st.get("total"))
    return files


def _adopt_browser_token(chrome, cfg, session):
    """SSO 登录后浏览器里有了新 token:同步给 HTTP 会话(单会话 DMS 下旧 token 已被踢掉)。"""
    try:
        val = ui_login._read_token(chrome, cfg)
    except Exception as e:  # noqa: BLE001
        log.debug("读取浏览器 token 失败:%s", e)
        val = None
    if val:
        session.adopt_token(val)


def profile_dir(cfg):
    """浏览器 profile 按(厂商系统, 账号)分目录保留。"""
    who = hashlib.sha1(("%s|%s" % (cfg.username, cfg.dms_url)).encode("utf-8")).hexdigest()[:10]
    return os.path.join(cfg.chrome_profile, "%s_%s" % (getattr(cfg, "dms", "") or "dms", who))


def _start_chrome(cfg, visible=False, har=None):
    headless = bool(cfg.headless) and not visible
    ua = cdp.NORMAL_UA if (headless and getattr(cfg, "fake_normal_ua", True)) else ""
    extra = list(cfg.extra_args or [])
    if getattr(cfg, "relay_disable_cors", "auto") == "on":
        extra.append("--disable-web-security")
    try:
        return Chrome(cfg.chrome_path, profile_dir(cfg), headless, cfg.window_size, extra, user_agent=ua, har=har)
    except CdpError as e:
        if cdp.CANCEL.is_set() or "找不到 Chrome" in str(e):
            raise
        log.warning("浏览器启动失败(%s),清空浏览器缓存目录后重试一次", e)
        return Chrome(cfg.chrome_path, profile_dir(cfg), headless, cfg.window_size, extra, fresh=True,
                      user_agent=ua, har=har)


def relay_hosts(cfg):
    """要代发的地址前缀:auth-api(只拦这个前缀,DMS 页面、IAM、parts-api 照常由浏览器自己访问)。"""
    a = (getattr(cfg, "auth_api", "") or "").rstrip("/")
    return [a] if a else []


def open_browser(cfg, audit=None, har=None, visible=False):
    """启动浏览器 + 开启网络观察 + auth-api 代发。返回 (chrome, relay 或 None)。"""
    chrome = _start_chrome(cfg, visible, har)
    chrome.watch()
    relay = None
    if getattr(cfg, "browser_relay", True):
        try:
            relay = AuthRelay(chrome, cfg, relay_hosts(cfg), audit).start()
        except CdpError as e:
            log.warning("auth-api 代发没能开启(%s),浏览器自己访问 auth-api", e)
    chrome.relay = relay                         # ui 登录要看代发是否还在重试、代发签发的 token
    if audit:
        audit.event("browser", "启动浏览器(%s%s)" % ("有界面" if not chrome.headless else "无界面",
                                                ",auth-api 代发" if relay else ""), args=" ".join(chrome.args))
    return chrome, relay


# 观看模式(tool.bat 菜单 12,桌面前台):mode = confirm 逐步确认 / auto 自动慢放;hold() 结束时等人按回车再关浏览器。
# 服务模式下为空,下面的 _stage 什么都不做。
WATCH = {"mode": "", "panel": None, "hold": None}
PAGE_CN = {"po_list.png": "采购订单管理(列表)", "po_detail.png": "采购订单详情", "check_po_list.png": "采购订单管理(列表)"}


def _watch_panel(chrome, cfg):
    if not WATCH["mode"]:
        return None
    if WATCH["panel"] is None or WATCH["panel"].chrome is not chrome:
        WATCH["panel"] = ConfirmPanel(chrome, cfg.ui_confirm_timeout, total=9,
                                      auto=2 if WATCH["mode"] == "auto" else 0)
    return WATCH["panel"]


def _stage(chrome, cfg, title, detail=""):
    """观看模式下,打开页面 / 截图之前也停一下(逐步确认要点「确认执行」)。"""
    p = _watch_panel(chrome, cfg)
    if p is None:
        return
    ans = p.ask(title, detail)
    if ans is not True:
        raise ui_login.UiLoginAborted("观看演示在「%s」%s,已停止" % (title, "被取消" if ans is False else "等待确认超时"))


def _confirm_panel(chrome, cfg):
    """ui 登录的逐步确认面板:ui_confirm=false 时不确认(返回 None)。"""
    return ConfirmPanel(chrome, cfg.ui_confirm_timeout, total=5, waiter=tasks.human_wait) \
        if getattr(cfg, "ui_confirm", True) else None


def _login_ui(chrome, cfg, session, audit, out_dir=None):
    """ui 策略:浏览器里模拟人工登录(逐步确认),token 同步给接口会话并调一次接口验证(不打开目标页)。"""
    confirm = _watch_panel(chrome, cfg) or _confirm_panel(chrome, cfg)
    if confirm:
        log.warning("ui 登录:浏览器窗口已打开,每一步都会在页面右上角弹出确认面板,请在电脑前逐步确认")
    before = session.token
    tok = session.run_password_login(lambda: ui_login.to_token(ui_login.login(chrome, cfg, audit, out_dir, confirm)),
                                     how="浏览器模拟人工登录")
    try:
        session._probe()
    except AuthExpired as e:
        why = "浏览器登录后拿到的 token 调接口不可用(%s;token %s)" % (e, describe(tok.value))
        session.discard_token(before, why)
        raise ScreenshotError("ui:" + why)
    audit.event("ui.adopt", "浏览器登录的 token 已同步给取数端接口会话(调接口验证通过)")


def ui_fallback_login(cfg, session):
    """接口登录失败(不是账号被拒)时的兜底:开浏览器模拟人工登录拿 token。
    在 run_password_login 里面调用(外层已做节流 / 计数),这里不再套一层。审计放在结果目录 *_ui_login。"""
    from ..infra.localstore import RunDir
    visible = ui_login.need_visible(cfg)
    if visible and not ui_login.interactive_desktop():
        raise ui_login.UiLoginSkipped("接口登录失败,浏览器兜底需要人工逐步确认,但取数端在后台服务里运行(看不到窗口),没有执行")
    rd = RunDir(cfg.data_dir, "ui_login")
    audit = AuditTrail(rd.path, title="浏览器模拟人工登录(接口登录失败后的兜底)")
    bhar = harmod.BrowserHar() if getattr(cfg, "har_capture", True) else None
    mark = session.client.har.mark()
    chrome = relay = None
    ok = False
    try:
        chrome, relay = open_browser(cfg, audit, bhar, visible)
        tok = ui_login.to_token(ui_login.login(chrome, cfg, audit, rd.path, _confirm_panel(chrome, cfg)))
        ok = True
        return tok
    finally:
        if relay:
            audit.event("relay.summary", relay.summary())
            relay.stop()
        if chrome:
            chrome.close()
        _write_hars(rd.path, session, bhar, [relay] if relay else [], mark)
        audit.finish(ok)
        rd.note("浏览器模拟人工登录", "成功" if ok else "失败,详见审计时间线 audit.html", "info" if ok else "err")
        rd.files += ["audit.html", "audit.jsonl", "browser.har", "http.har"]
        rd.finish(ok, {"message": "浏览器兜底登录" + ("成功" if ok else "失败")})


def _write_hars(out_dir, session, bhar, relays, mark):
    try:
        if bhar is not None:
            harmod.write(os.path.join(out_dir, "browser.har"), bhar.entries(), "store_edge browser")
        items = session.client.har.since(mark)
        for r in relays:
            items += list(r.client.har.items)
        harmod.write(os.path.join(out_dir, "http.har"), items, "store_edge python")
    except Exception as e:  # noqa: BLE001
        log.warning("抓包文件没能保存:%s", e)


def capture(cfg, session, targets, out_dir):
    """targets: [(文件名, url, [页面必须包含的文字]) 或 (文件名, url, [...], 选项)],或返回这个列表的函数(登录成功后才调用,
    只调一次——目标要靠接口查出来时,ui 方式用浏览器刚登录的 token 去查,不用先做一次接口登录)。
    选项 {"paged": True, "parts": [全部零件号]}:截完第 1 页后逐页翻页截图(_page_through),翻页结果写进选项的 "result"。
    返回 [文件路径];全部策略失败抛 ScreenshotError。"""
    os.makedirs(out_dir, exist_ok=True)
    audit = AuditTrail(out_dir, title="截图 / 浏览器登录审计")
    bhar = harmod.BrowserHar() if getattr(cfg, "har_capture", True) else None
    mark = session.client.har.mark()
    resolved = [] if callable(targets) else list(targets)

    def _targets():
        if not resolved:
            resolved.extend(targets())
        return resolved

    audit.event("start", "开始截图%s;登录方式顺序 %s" % (
        ":" + "、".join(t[0] for t in resolved) if resolved else "", " → ".join(cfg.strategies)))
    errors, relays = [], []
    chrome = relay = None
    validated = False
    login_err = None                 # 截图前的接口登录(ensure_valid)失败了:后面的 token / sso 不再触发第二次密码登录
    ok = False
    try:
        for strategy in cfg.strategies:
            login = {"token": _login_token, "sso": _login_sso, "ui": _login_ui}.get(strategy)
            if not login:
                errors.append("未知截图策略 %s" % strategy)
                continue
            visible = strategy == "ui" and ui_login.need_visible(cfg)
            if visible and not ui_login.interactive_desktop():
                # 服务在后台会话里看不到浏览器窗口:逐步确认的 ui 方式直接跳过(不算失败、不刷错误日志)
                log.debug("截图登录方式 ui 需要有人在电脑前逐步确认,服务模式下跳过")
                errors.append("ui: 以服务在后台运行时跳过(要观看请在门店电脑上用 tool.bat 菜单 12)")
                continue
            try:
                with audit.step("strategy", "登录方式 %s" % strategy, strategy=strategy):
                    if strategy != "ui" and login_err is not None:
                        # token / sso 都靠接口登录:它刚失败过(含验证码问题),不要再提交一次密码
                        raise ScreenshotError("接口登录刚失败,不再重试(%s)" % login_err)
                    if strategy != "ui" and not validated:
                        try:
                            how = session.ensure_valid()
                        except LoginRejected:
                            raise
                        except Exception as e:
                            login_err = e
                            raise
                        validated = True
                        log.info("截图前确认登录态:%s", {"reused": "复用已有登录,不用重新登录", "login": "新登录",
                                                          "relogin": "原登录已失效,已重新登录"}.get(how, how))
                    if chrome is not None and (chrome.proc.poll() is not None or (visible and chrome.headless)):
                        if relay:
                            relay.stop()
                        chrome.close()
                        chrome = None
                    if chrome is None:
                        chrome, relay = open_browser(cfg, audit, bhar, visible)
                        if relay:
                            relays.append(relay)
                    if strategy == "ui":
                        login(chrome, cfg, session, audit, out_dir)     # 只登录;目标页在下面逐个打开
                        tg, opened = _targets(), 0
                    else:
                        tg, opened = _targets(), 1
                        login(chrome, cfg, session, tg[0])    # 打开并等到第一个目标页(不再重复打开)
                    if strategy == "token":
                        _adopt_browser_token(chrome, cfg, session)  # 浏览器若借 SSO Cookie 自己换了 token,同步回来
                    files = []
                    for i, t in enumerate(tg):
                        fname, url, must = t[:3]
                        opts = t[3] if len(t) > 3 else None
                        if i >= opened:
                            _stage(chrome, cfg, "打开「%s」页面" % PAGE_CN.get(fname, fname),
                                   "直接打开网址%s:%s" % ("(登录后不点菜单)" if not i else "", url))
                            chrome.navigate(url)
                            _wait_for(chrome, cfg, must, "%s/%s" % (strategy, fname))
                        time.sleep(cfg.settle_seconds)          # 等表格渲染完
                        _stage(chrome, cfg, "截图:%s" % PAGE_CN.get(fname, fname), "整页截图保存为 %s" % fname)
                        if WATCH["panel"]:
                            WATCH["panel"].clear()              # 面板不能出现在截图里
                        path = os.path.join(out_dir, fname)
                        shoot(chrome, cfg, path)
                        log.info("截图完成(策略 %s):%s", strategy, path)
                        audit.event("shot", "截图完成:%s" % fname, shot=fname)
                        files.append(path)
                        if opts and opts.get("paged"):
                            files.extend(_page_through(chrome, cfg, out_dir, fname, opts, audit, strategy))
                ok = True
                return files
            except LoginRejected as e:
                errors.append("%s: %s" % (strategy, e))
                log.error("截图策略 %s:账号密码被拒(%s),停止尝试其它方式", strategy, e)
                raise
            except (CdpError, ScreenshotError, OSError, LoginError) as e:
                log.warning("截图策略 %s 失败:%s", strategy, e)
                errors.append("%s: %s" % (strategy, e))
                if chrome and chrome.ws and chrome.proc.poll() is None:
                    try:
                        _debug_dump(chrome, cfg, out_dir, strategy, e)
                    except Exception as de:  # noqa: BLE001
                        log.warning("截图诊断信息没能保存:%r", de)
                if cdp.CANCEL.is_set():
                    break
    finally:
        if WATCH["hold"] and chrome and chrome.proc.poll() is None:
            try:
                if WATCH["panel"]:
                    WATCH["panel"].done("观看结束", "全部完成" if ok else "已停止:" + ";".join(errors)[-200:])
                WATCH["hold"]()                                  # 浏览器先留着给人看,回车再关
            except Exception:  # noqa: BLE001
                pass
        for r in relays:
            audit.event("relay.summary", r.summary())
            r.stop()
        if chrome:
            chrome.close()
        _write_hars(out_dir, session, bhar, relays, mark)
        audit.finish(ok, "" if ok else ";".join(errors))
    raise ScreenshotError("截图失败(所有登录态策略都没成功,诊断截图见 debug_*.png,审计见 audit.html):" + ";".join(errors))