confirm.py 8.82 KB
# -*- coding: utf-8 -*-
"""浏览器页面上的人工确认面板(UI 登录逐步确认用)。

每一步动作之前:
  1. 把目标元素用红框标出来(红框不挡鼠标);
  2. 在页面角落(避开目标元素)浮出面板:「下一步:点击『登录』按钮(#loginButton,坐标 x,y) [确认执行] [取消]」;
  3. 只有人在面板上点「确认执行」才返回 True;点「取消」返回 False;超时没点返回 None —— 调用方都会中止,什么都不做。
  4. 动作执行前先把面板和红框撤掉,避免挡住目标。

自动慢放(auto 秒,tool.bat 菜单 12 观看用):同样标红框、显示面板,但不用点,停 auto 秒后自动执行。

防误触:面板脚本跑在 CDP 隔离环境(isolated world)里,回传通道(Runtime.addBinding)只在这个隔离环境可见,
网页自己的脚本调不到;每次确认带随机编号,只认本次面板的回传。程序自己从不点击面板。
页面跳转导致面板消失时,每秒检查一次并重新画出来。
"""
import json
import logging
import os
import threading
import time

log = logging.getLogger("edge")
WORLD = "edge_confirm"
BINDING = "__edgeConfirm"

_PANEL_JS = r"""(function(cfg){
  var old = document.getElementById('__edge_confirm'); if (old) old.remove();
  var hl = document.getElementById('__edge_hl'); if (hl) hl.remove();
  if (cfg.rect) {
    hl = document.createElement('div'); hl.id = '__edge_hl';
    hl.style.cssText = 'position:fixed;z-index:2147483646;pointer-events:none;border:3px solid #e60012;' +
      'box-shadow:0 0 0 4px rgba(230,0,18,.25);border-radius:4px;left:' + (cfg.rect.x - 4) + 'px;top:' +
      (cfg.rect.y - 4) + 'px;width:' + (cfg.rect.w + 2) + 'px;height:' + (cfg.rect.h + 2) + 'px';
    document.documentElement.appendChild(hl);
  }
  var p = document.createElement('div'); p.id = '__edge_confirm';
  var right = !(cfg.rect && cfg.rect.x + cfg.rect.w > window.innerWidth - 440 && cfg.rect.y < 260);
  p.style.cssText = 'position:fixed;z-index:2147483647;top:12px;' + (right ? 'right:12px;' : 'left:12px;') +
    'width:400px;background:#fff;border:2px solid #e60012;border-radius:8px;padding:12px 14px;' +
    'font:14px/1.6 "Microsoft YaHei",sans-serif;color:#222;box-shadow:0 6px 24px rgba(0,0,0,.25)';
  var h = '<div style="font-weight:bold;color:#e60012;margin-bottom:4px">取数端 · 请确认下一步操作(' +
    cfg.no + '/' + cfg.total + ')</div><div style="font-size:15px;font-weight:bold">' + cfg.title + '</div>' +
    '<div style="color:#555;font-size:12.5px;margin:4px 0 10px;white-space:pre-wrap">' + cfg.detail + '</div>';
  if (cfg.done) {
    h += '<div style="color:#0a7d32">' + cfg.done + '</div>';
  } else {
    h += '<button id="__edge_ok" style="background:#e60012;color:#fff;border:0;border-radius:4px;padding:6px 18px;' +
      'font-size:14px;cursor:pointer;margin-right:10px">确认执行</button>' +
      '<button id="__edge_no" style="background:#eee;border:1px solid #ccc;border-radius:4px;padding:6px 18px;' +
      'font-size:14px;cursor:pointer">取消(中止登录)</button>' +
      '<div style="color:#999;font-size:12px;margin-top:8px">' + cfg.timeout + ' 秒内不确认将自动中止,不会执行任何操作</div>';
  }
  p.innerHTML = h;
  document.documentElement.appendChild(p);
  if (!cfg.done) {
    document.getElementById('__edge_ok').onclick = function(){ window[cfg.binding](JSON.stringify({id: cfg.id, d: 'ok'})); };
    document.getElementById('__edge_no').onclick = function(){ window[cfg.binding](JSON.stringify({id: cfg.id, d: 'no'})); };
  }
  return 1;
})(%s)"""

_CLEAR_JS = r"""(function(){ ['__edge_confirm','__edge_hl'].forEach(function(i){ var e = document.getElementById(i); if (e) e.remove(); }); return 1; })()"""
_ALIVE_JS = r"""!!document.getElementById('__edge_confirm')"""


def _esc(s):
    return (str(s or "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))


class ConfirmPanel(object):
    def __init__(self, chrome, timeout=180, total=5, waiter=None, auto=0):
        """waiter(detail, timeout) → 上下文管理器:等确认期间暂停任务步骤计时(core.tasks.human_wait)。
        auto > 0:自动慢放,每步只展示 auto 秒,不等人点。"""
        self.chrome = chrome
        self.timeout = int(timeout)
        self.total = total
        self.auto = float(auto or 0)
        self.no = 0
        self.waiter = waiter
        self._answers = {}
        self._ev = threading.Event()
        self._isolated = True
        self._ctx_key = self._ctx_id = None
        chrome.on("Runtime.bindingCalled", self._on_binding)
        try:
            chrome.send("Runtime.addBinding", {"name": BINDING, "executionContextName": WORLD})
        except Exception:  # noqa: BLE001  老版本不支持指定隔离环境:退回主环境(编号仍随机)
            self._isolated = False
            chrome.send("Runtime.addBinding", {"name": BINDING})

    def _on_binding(self, p):
        if p.get("name") != BINDING:
            return
        try:
            d = json.loads(p.get("payload") or "{}")
        except ValueError:
            return
        self._answers[d.get("id")] = d.get("d")
        self._ev.set()

    def _context(self):
        if not self._isolated:
            return None
        try:
            frame = self.chrome.send("Page.getFrameTree")["frameTree"]["frame"]
            key = (frame["id"], frame.get("loaderId"))           # 同一个页面(文档)复用同一个隔离环境
            if self._ctx_key != key:
                self._ctx_id = self.chrome.send("Page.createIsolatedWorld", {
                    "frameId": frame["id"], "worldName": WORLD, "grantUniveralAccess": False})["executionContextId"]
                self._ctx_key = key
            return self._ctx_id
        except Exception:  # noqa: BLE001
            self._ctx_key = None
            return None

    def _eval(self, js):
        params = {"expression": js, "returnByValue": True}
        ctx = self._context()
        if ctx:
            params["contextId"] = ctx
        try:
            r = self.chrome.send("Runtime.evaluate", params, timeout=10)
            return (r.get("result") or {}).get("value")
        except Exception:  # noqa: BLE001
            return None

    def _draw(self, cfg):
        return self._eval(_PANEL_JS % json.dumps(cfg, ensure_ascii=False))

    def ask(self, title, detail, rect=None):
        """画面板等人确认。返回 True=确认 / False=取消 / None=超时。"""
        self.no += 1
        rid = os.urandom(8).hex()
        cfg = {"id": rid, "binding": BINDING, "no": self.no, "total": self.total, "title": _esc(title),
               "detail": _esc(detail), "timeout": self.timeout, "rect": rect, "done": ""}
        self.chrome.bring_to_front()
        if self.auto:
            log.info("(%d/%d)%s %s", self.no, self.total, title, detail)
            self.show(title, detail, rect, "自动慢放:%g 秒后执行这一步" % self.auto, self.auto, count=False)
            self._eval(_CLEAR_JS)
            return True
        self._draw(cfg)
        log.warning("等待人工确认(%d/%d):%s —— 请在浏览器页面右上角的面板上点「确认执行」或「取消」(%d 秒内)",
                    self.no, self.total, title, self.timeout)
        deadline = time.time() + self.timeout
        cm = self.waiter("%s(%d/%d)" % (title, self.no, self.total), self.timeout) if self.waiter else None
        answer = None
        try:
            if cm:
                cm.__enter__()
            while time.time() < deadline:
                self._ev.wait(1.0)
                self._ev.clear()
                if rid in self._answers:
                    answer = self._answers.pop(rid) == "ok"
                    break
                if not self._eval(_ALIVE_JS):             # 页面跳转把面板冲掉了:重画
                    self._draw(cfg)
        finally:
            self._eval(_CLEAR_JS)
            if cm:
                cm.__exit__(None, None, None) if answer else cm.__exit__(RuntimeError, RuntimeError("未确认"), None)
        return answer

    def show(self, title, detail, rect, msg, seconds, count=True):
        """只展示(标红框 + 面板说明,没有按钮),停 seconds 秒。不执行任何操作。"""
        if count:
            self.no += 1
        self._draw({"id": "", "binding": BINDING, "no": self.no, "total": self.total, "title": _esc(title),
                    "detail": _esc(detail), "timeout": 0, "rect": rect, "done": _esc(msg)})
        time.sleep(max(0.0, float(seconds)))

    def done(self, title, msg):
        """动作完成后给人看一眼结果(不需要点)。"""
        self._draw({"id": "", "binding": BINDING, "no": self.no, "total": self.total, "title": _esc(title),
                    "detail": "", "timeout": 0, "rect": None, "done": _esc(msg)})

    def clear(self):
        self._eval(_CLEAR_JS)