From c4615bc8e39f515320fa673a62cadaafe24911be Mon Sep 17 00:00:00 2001 From: spudding <1115683088@qq.com> Date: Mon, 16 Nov 2026 11:28:01 +0800 Subject: [PATCH] =?UTF-8?q?chore(tools):=20=E6=96=B0=E5=A2=9E=E6=89=93?= =?UTF-8?q?=E5=8D=B0/PDF/=E8=A1=A8=E6=A0=BC=E5=B7=A5=E5=85=B7=E4=B8=8E=20O?= =?UTF-8?q?A=E2=86=92ERP=20=E5=8D=95=E7=82=B9=E7=99=BB=E5=BD=95=E8=84=9A?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tools/printer_probe.py:打印机协议非破坏性探测(端口/IPP 能力/LPD 队列,绝不提交作业) - tools/printer_client.py:IPP 直连打印(info / validate 干跑 / print 需显式 --yes) - tools/doc2pdf.py:网页 / HTML / Excel 指定区域转 PDF,产物可直接交给 printer_client - tools/sheet_print.py:Excel·WPS 表格按列过滤排版后分页打印 - tools/xq0012_payapply_pdf.py:XQ0012 套打 PDF 本地预览工具 - workflows/share/erp_sso_login.py:读 OA 登录态换 ERP 会话(新版/旧版,纯接口无浏览器) - workflows/README.md 新增 4.9 节说明 --- tools/doc2pdf.py | 203 +++++++++++++ tools/printer_client.py | 491 +++++++++++++++++++++++++++++++ tools/printer_probe.py | 387 ++++++++++++++++++++++++ tools/sheet_print.py | 481 ++++++++++++++++++++++++++++++ tools/xq0012_payapply_pdf.py | 48 +++ workflows/README.md | 14 + workflows/share/erp_sso_login.py | 436 +++++++++++++++++++++++++++ 7 files changed, 2060 insertions(+) create mode 100644 tools/doc2pdf.py create mode 100644 tools/printer_client.py create mode 100644 tools/printer_probe.py create mode 100644 tools/sheet_print.py create mode 100644 tools/xq0012_payapply_pdf.py create mode 100644 workflows/share/erp_sso_login.py diff --git a/tools/doc2pdf.py b/tools/doc2pdf.py new file mode 100644 index 0000000..81fe335 --- /dev/null +++ b/tools/doc2pdf.py @@ -0,0 +1,203 @@ +# -*- coding: utf-8 -*- +"""把「网页」和「WPS 表格固定区域」转换成 PDF(全程不弹窗、不打印)。 + +两条通道 +-------- +1. 网页 : Edge/Chrome 无头模式 --print-to-pdf + (等价于在浏览器里按 Ctrl+P 选"另存为 PDF",但无对话框) +2. 表格 : WPS COM 自动化(KET.Application / Excel.Application) + 设置 PrintArea = "A1:F20" 后 ExportAsFixedFormat 导出 PDF + +产物可直接交给 tools/printer_client.py print --input xxx.pdf 走 IPP 直连打印。 + +用法 +---- + # 网页 -> PDF + python tools/doc2pdf.py web --url "https://example.com/report" --out out.pdf + python tools/doc2pdf.py web --html page.html --out out.pdf --landscape + + # WPS 表格固定区域 -> PDF + python tools/doc2pdf.py sheet --file book.xlsx --sheet Sheet1 --range "A1:F20" --out out.pdf + python tools/doc2pdf.py sheet --file book.xlsx --auto-area --out out.pdf +""" + +from __future__ import annotations + +import argparse +import os +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +EDGE_CANDIDATES = [ + r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe", + r"C:\Program Files\Microsoft\Edge\Application\msedge.exe", + r"C:\Program Files\Google\Chrome\Application\chrome.exe", + r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", +] + + +# --------------------------------------------------------------------------- # +# 1) 网页 -> PDF +# --------------------------------------------------------------------------- # +def find_browser() -> str: + for p in EDGE_CANDIDATES: + if Path(p).exists(): + return p + raise RuntimeError("未找到 Edge/Chrome,可执行文件不在预期路径") + + +def web_to_pdf(url: str | None = None, html: str | None = None, + out: str = "out.pdf", landscape: bool = False, + margin: float = 10.0, scale: float = 1.0, + no_header_footer: bool = True, timeout: int = 90) -> str: + """用无头浏览器把网页打印成 PDF。不弹任何窗口。""" + browser = find_browser() + out_path = Path(out).resolve() + out_path.parent.mkdir(parents=True, exist_ok=True) + + if url is None: + if html is None: + raise ValueError("url 与 html 必须给一个") + p = Path(html).resolve() + if not p.exists(): + raise FileNotFoundError(p) + url = p.as_uri() + + profile = Path(tempfile.gettempdir()) / "doc2pdf-profile" + cmd = [ + browser, + "--headless=new", + "--disable-gpu", + "--no-first-run", + "--no-default-browser-check", + f"--user-data-dir={profile}", + "--print-to-pdf-no-header" if no_header_footer else "--no-pdf-header-footer", + f"--print-to-pdf={out_path}", + ] + if landscape: + cmd.append("--print-to-pdf-landscape") + cmd.append(url) + + t0 = time.time() + proc = subprocess.run(cmd, capture_output=True, timeout=timeout, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + if not out_path.exists() or out_path.stat().st_size == 0: + raise RuntimeError(f"生成失败 rc={proc.returncode}\n" + f"{proc.stderr.decode('utf-8', 'replace')[:800]}") + print(f"[web] {out_path} {out_path.stat().st_size/1024:.1f} KB " + f"{time.time()-t0:.1f}s") + return str(out_path) + + +# --------------------------------------------------------------------------- # +# 2) WPS / Excel 表格固定区域 -> PDF +# --------------------------------------------------------------------------- # +def _com_app(prog_ids: list[str]): + """按优先级尝试 ProgID,返回 (app, 使用的 progid)。""" + import win32com.client as win32 + last = None + for pid in prog_ids: + try: + app = win32.DispatchEx(pid) + return app, pid + except Exception as e: # noqa: BLE001 + last = e + raise RuntimeError(f"无法启动表格 COM(试过 {prog_ids}):{last}") + + +def sheet_to_pdf(file: str, sheet: str | None = None, rng: str | None = None, + out: str = "out.pdf", auto_area: bool = False, + landscape: bool = False, fit_one_page: bool = True, + print_title_rows: str | None = None) -> str: + """用 WPS 表格 COM 把指定区域导出为 PDF(不打印、不弹窗)。""" + src = Path(file).resolve() + if not src.exists(): + raise FileNotFoundError(src) + out_path = Path(out).resolve() + out_path.parent.mkdir(parents=True, exist_ok=True) + + app, pid = _com_app(["KET.Application", "Ket.Application", "Excel.Application"]) + print(f"[sheet] 使用 COM: {pid}") + app.Visible = False + app.DisplayAlerts = False + wb = None + try: + wb = app.Workbooks.Open(str(src)) + ws = wb.Worksheets(sheet) if sheet else wb.ActiveSheet + + if auto_area: + rng = ws.UsedRange.Address(False, False).replace("$", "") + print(f"[sheet] 自动区域 = {rng}") + if rng: + ws.PageSetup.PrintArea = rng.replace(" ", "") + if print_title_rows: + ws.PageSetup.PrintTitleRows = print_title_rows + if landscape: + ws.PageSetup.Orientation = 2 # xlLandscape + if fit_one_page: + ws.PageSetup.Zoom = False + ws.PageSetup.FitToPagesWide = 1 + ws.PageSetup.FitToPagesTall = 1 + + # 0 = xlTypePDF,只导出不送打印机 + ws.ExportAsFixedFormat(0, str(out_path)) + finally: + if wb is not None: + try: + wb.Close(SaveChanges=False) + except Exception: # noqa: BLE001 + pass + try: + app.Quit() + except Exception: # noqa: BLE001 + pass + + if not out_path.exists() or out_path.stat().st_size == 0: + raise RuntimeError("导出 PDF 失败") + print(f"[sheet] {out_path} {out_path.stat().st_size/1024:.1f} KB 区域={rng}") + return str(out_path) + + +# --------------------------------------------------------------------------- # +# CLI +# --------------------------------------------------------------------------- # +def main() -> int: + ap = argparse.ArgumentParser(description="网页/WPS表格 -> PDF(不打印)") + sub = ap.add_subparsers(dest="cmd", required=True) + + w = sub.add_parser("web", help="网页转 PDF") + w.add_argument("--url") + w.add_argument("--html") + w.add_argument("--out", default="out.pdf") + w.add_argument("--landscape", action="store_true") + + s = sub.add_parser("sheet", help="WPS 表格区域转 PDF") + s.add_argument("--file", required=True) + s.add_argument("--sheet") + s.add_argument("--range", dest="rng") + s.add_argument("--auto-area", action="store_true") + s.add_argument("--print-title-rows", default=None, help='如 "$1:$1"') + s.add_argument("--landscape", action="store_true") + s.add_argument("--no-fit", action="store_true", help="不强制缩放到一页") + s.add_argument("--out", default="out.pdf") + + a = ap.parse_args() + try: + if a.cmd == "web": + web_to_pdf(url=a.url, html=a.html, out=a.out, landscape=a.landscape) + else: + sheet_to_pdf(a.file, sheet=a.sheet, rng=a.rng, out=a.out, + auto_area=a.auto_area, landscape=a.landscape, + fit_one_page=not a.no_fit, + print_title_rows=a.print_title_rows) + except Exception as e: # noqa: BLE001 + print(f"失败: {type(e).__name__}: {e}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/printer_client.py b/tools/printer_client.py new file mode 100644 index 0000000..034df48 --- /dev/null +++ b/tools/printer_client.py @@ -0,0 +1,491 @@ +# -*- coding: utf-8 -*- +"""EPSON 网络打印机直连打印客户端(IPP over TLS)。 + +设计目标 +-------- +不依赖 Windows 打印队列 / 厂商驱动,直接按 IPP (RFC 8010/8011) 与打印机通信。 +本机实测设备:EPSON L6570 Series @ 172.30.40.254 + +安全默认 +-------- +`python tools/printer_client.py info` 读取设备能力(只读,绝不打印) +`python tools/printer_client.py validate` 提交 Validate-Job(协议规定的"只校验不打印"操作) +`python tools/printer_client.py print` 真正打印,必须显式加 --yes 才会执行 + +协议要点(逆向实测结论) +------------------------ +1. 631 端口同时提供 IPP 与 IPPS;直接明文 POST 会被 426 Upgrade Required 拒绝, + 必须走 TLS(设备自签证书,测试期不校验证书)。 +2. 设备支持 document-format: application/octet-stream / image/pwg-raster / + image/urf / image/jpeg / application/vnd.epson.escpr。 +3. 支持 Validate-Job(0x0004),可实现"校验通过但不出纸"的联调。 +""" + +from __future__ import annotations + +import argparse +import json +import socket +import ssl +import struct +import sys +import time +from pathlib import Path + +DEFAULT_IP = "172.30.40.254" +IPP_PORT = 631 + +# IPP 操作码 +OP_PRINT_JOB = 0x0002 +OP_VALIDATE_JOB = 0x0004 +OP_CREATE_JOB = 0x0005 +OP_GET_JOBS = 0x000A +OP_GET_PRINTER_ATTRIBUTES = 0x000B + +STATUS_TEXT = { + 0x0000: "successful-ok", + 0x0001: "successful-ok-ignored-or-substituted-attributes", + 0x0002: "successful-ok-conflicting-attributes", + 0x0400: "client-error-bad-request", + 0x0401: "client-error-forbidden", + 0x0403: "client-error-not-found", + 0x0404: "client-error-not-possible", + 0x0405: "client-error-timeout", + 0x0406: "client-error-not-found(?)", + 0x040B: "client-error-document-format-not-supported", + 0x040A: "client-error-attributes-or-values-not-supported", + 0x0500: "server-error-internal-error", + 0x0502: "server-error-service-unavailable", +} + +# IPP 值标签 +T_OPERATION = 0x01 +T_JOB = 0x02 +T_END = 0x03 +T_INTEGER = 0x21 +T_BOOLEAN = 0x22 +T_ENUM = 0x23 +T_STRING = 0x30 +T_NAME = 0x42 +T_KEYWORD = 0x44 +T_URI = 0x45 +T_CHARSET = 0x47 +T_LANGUAGE = 0x48 +T_MIME = 0x49 + + +# --------------------------------------------------------------------------- # +# IPP 报文构造/解析 +# --------------------------------------------------------------------------- # +def attr(tag: int, name: bytes | str, value: bytes | str | int) -> bytes: + """构造一个 IPP 属性三元组 (value-tag, name-length+name, value-length+value)。""" + nb = name.encode() if isinstance(name, str) else name + if isinstance(value, int): + vb, tag = struct.pack(">i", value), T_INTEGER + elif isinstance(value, str): + vb = value.encode("utf-8") + else: + vb = value + return bytes([tag]) + struct.pack(">H", len(nb)) + nb + struct.pack(">H", len(vb)) + vb + + +def build_request(op: int, uri: str, operation_attrs: list[bytes], + job_attrs: list[bytes] | None = None, req_id: int = 1) -> bytes: + body = bytes([T_OPERATION]) + body += attr(T_CHARSET, b"attributes-charset", b"utf-8") + body += attr(T_LANGUAGE, b"attributes-natural-language", b"en-us") + body += attr(T_URI, b"printer-uri", uri.encode()) + body += attr(T_NAME, b"requesting-user-name", b"37du-auto") + for a in operation_attrs: + body += a + if job_attrs: + body += bytes([T_JOB]) + for a in job_attrs: + body += a + body += bytes([T_END]) + return struct.pack(">BBHI", 2, 0, op, req_id) + body + + +def parse_attributes(payload: bytes) -> tuple[int, dict]: + """解析 IPP 响应体,返回 (状态码, 属性字典)。""" + if len(payload) < 8: + return -1, {} + status = struct.unpack(">H", payload[2:4])[0] + attrs: dict[str, list] = {} + i, cur = 8, None + while i < len(payload): + tag = payload[i] + if tag == T_END: + break + if tag < 0x10: + i += 1 + continue + if i + 3 > len(payload): + break + nl = struct.unpack(">H", payload[i + 1:i + 3])[0] + name = payload[i + 3:i + 3 + nl].decode("utf-8", "replace") + i += 3 + nl + if i + 2 > len(payload): + break + vl = struct.unpack(">H", payload[i:i + 2])[0] + raw = payload[i + 2:i + 2 + vl] + i += 2 + vl + if name: + cur = name + attrs.setdefault(cur or "?", []).append((tag, raw)) + return status, attrs + + +def _val(tag: int, raw: bytes): + if tag in (T_INTEGER, T_ENUM): + return int.from_bytes(raw, "big", signed=(tag == T_INTEGER)) + if tag == T_BOOLEAN: + return bool(raw and raw[0]) + if tag == 0x33: # rangeOfInteger + return raw.hex(" ") + return raw.decode("utf-8", "replace") + + +# --------------------------------------------------------------------------- # +# 传输层 +# --------------------------------------------------------------------------- # +class PrinterClient: + def __init__(self, ip: str = DEFAULT_IP, port: int = IPP_PORT, + path: str = "/ipp/print", timeout: float = 30.0, + tls: bool = True): + self.ip, self.port, self.path, self.timeout = ip, port, path, timeout + self.tls = tls + # IPv6 字面量在 URI / Host 头里必须加方括号(含 zone index 的链路本地地址也一样) + host = f"[{ip}]" if ":" in ip else ip + self.host_header = f"{host}:{port}" + self.uri = f"{'ipps' if tls else 'ipp'}://{host}:{port}{path}" + self._req_id = 0 + + def _connect(self) -> ssl.SSLSocket | socket.socket: + sock = socket.create_connection((self.ip, self.port), timeout=self.timeout) + if not self.tls: + return sock + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + try: + ctx.set_ciphers("DEFAULT:@SECLEVEL=1") + except ssl.SSLError: + pass + # IP 字面量不做 SNI(含 %zone 的链路本地地址不是合法 SNI 名) + return ctx.wrap_socket(sock, server_hostname=None) + + def request(self, op: int, operation_attrs: list[bytes], + job_attrs: list[bytes] | None = None, + document: bytes = b"", + document_format: str | None = None) -> tuple[int, dict, bytes]: + self._req_id += 1 + ops = list(operation_attrs) + if document_format: + ops.append(attr(T_MIME, b"document-format", document_format.encode())) + body = build_request(op, self.uri, ops, job_attrs, self._req_id) + head = ( + f"POST {self.path} HTTP/1.1\r\n" + f"Host: {self.host_header}\r\n" + "Content-Type: application/ipp\r\n" + f"Content-Length: {len(body) + len(document)}\r\n" + "Connection: close\r\n\r\n" + ).encode() + s = self._connect() + try: + s.sendall(head + body + document) + data = b"" + while True: + try: + chunk = s.recv(65536) + except (socket.timeout, ssl.SSLError): + break + if not chunk: + break + data += chunk + finally: + s.close() + http_head, _, payload = data.partition(b"\r\n\r\n") + http_code = 0 + for tok in http_head.split(b"\r\n", 1)[0].split(): + if tok.isdigit(): + http_code = int(tok) + status, attrs = parse_attributes(payload) + return (status if status >= 0 else http_code), attrs, data + + # --- 能力探测与参数降级 --- + def caps(self) -> dict: + """缓存设备能力属性(首次调用走一次 Get-Printer-Attributes)。""" + if getattr(self, "_caps", None) is None: + self._caps = self.get_attributes()["attrs"] + return self._caps + + def check_options(self, opts: dict) -> dict: + """提前剔除设备不支持的参数。 + + EPSON 这两台即使带 ipp-attribute-fidelity=true 也**不报错**, + 只会静默忽略(实测),所以必须在客户端侧先判断,避免"以为打了双面"。 + """ + c = self.caps() + warn = [] + if opts.get("sides") and "sides-supported" in c and opts["sides"] not in c["sides-supported"]: + warn.append(f"不支持 sides={opts['sides']}(支持 {c['sides-supported']}),已改为单面") + opts["sides"] = None + if opts.get("media") and "media-supported" in c and opts["media"] not in c["media-supported"]: + warn.append(f"不支持 media={opts['media']},已改用默认 {c.get('media-default')}") + opts["media"] = None + if opts.get("color") and "print-color-mode-supported" in c \ + and opts["color"] not in c["print-color-mode-supported"]: + warn.append(f"不支持 color={opts['color']},已改用默认") + opts["color"] = None + for w in warn: + print(f"[warn] {w}") + return opts + + # --- 高层操作 --- + def get_attributes(self, wanted: list[str] | None = None) -> dict: + ops = [attr(T_KEYWORD, b"requested-attributes", w.encode()) + for w in (wanted or ["all"])] + status, attrs, _ = self.request(OP_GET_PRINTER_ATTRIBUTES, ops) + flat = {k: [_val(t, v) for t, v in vv] for k, vv in attrs.items()} + return {"status": STATUS_TEXT.get(status, hex(status)), "attrs": flat} + + def validate_job(self, document: bytes, doc_format: str, + job_name: str = "37du-validate", **opts) -> dict: + """Validate-Job:协议层校验作业是否可被接受,设备不得打印。""" + opts = self.check_options(dict(opts)) + job_attrs = [attr(T_NAME, b"job-name", job_name.encode())] + job_attrs += _job_options(**opts) + status, attrs, raw = self.request( + OP_VALIDATE_JOB, [], job_attrs, document=document, document_format=doc_format) + flat = {k: [_val(t, v) for t, v in vv] for k, vv in attrs.items()} + return {"status": STATUS_TEXT.get(status, hex(status)), + "status_code": status, "attrs": flat, "bytes": len(raw)} + + def print_job(self, document: bytes, doc_format: str, + job_name: str = "37du-print", **opts) -> dict: + """Print-Job:真正打印作业。""" + opts = self.check_options(dict(opts)) + job_attrs = [attr(T_NAME, b"job-name", job_name.encode())] + job_attrs += _job_options(**opts) + status, attrs, raw = self.request( + OP_PRINT_JOB, [], job_attrs, document=document, document_format=doc_format) + flat = {k: [_val(t, v) for t, v in vv] for k, vv in attrs.items()} + return {"status": STATUS_TEXT.get(status, hex(status)), + "status_code": status, "attrs": flat, "bytes": len(raw)} + + def get_jobs(self, which: str = "completed", limit: int = 10) -> dict: + ops = [attr(T_KEYWORD, b"which-jobs", which.encode()), + attr(T_INTEGER, b"limit", limit)] + status, attrs, _ = self.request(OP_GET_JOBS, ops) + return {"status": STATUS_TEXT.get(status, hex(status)), + "attrs": {k: [_val(t, v) for t, v in vv] for k, vv in attrs.items()}} + + +def _job_options(media: str | None = None, copies: int | None = None, + sides: str | None = None, color: str | None = None, + quality: int | None = None, scaling: str | None = None, + resolution: tuple[int, int] | None = None) -> list[bytes]: + out: list[bytes] = [] + if media: + out.append(attr(T_KEYWORD, b"media", media.encode())) + if copies: + out.append(attr(T_INTEGER, b"copies", copies)) + if sides: + out.append(attr(T_KEYWORD, b"sides", sides.encode())) + if color: + out.append(attr(T_KEYWORD, b"print-color-mode", color.encode())) + if quality: + out.append(attr(T_INTEGER, b"print-quality", quality)) + if scaling: + out.append(attr(T_KEYWORD, b"print-scaling", scaling.encode())) + if resolution: + out.append(attr(T_INTEGER, b"printer-resolution", resolution[0])) + return out + + +# --------------------------------------------------------------------------- # +# 测试载荷生成 +# --------------------------------------------------------------------------- # +def make_jpeg(text: str = "37du test", size: tuple[int, int] = (600, 300)) -> bytes: + """生成一张测试图(不落盘),仅用于 Validate-Job 探测格式兼容性。""" + from io import BytesIO + + from PIL import Image, ImageDraw + img = Image.new("RGB", size, "white") + d = ImageDraw.Draw(img) + d.rectangle([4, 4, size[0] - 5, size[1] - 5], outline="black", width=3) + d.text((24, size[1] // 2 - 8), text, fill="black") + buf = BytesIO() + img.save(buf, "JPEG", quality=90) + return buf.getvalue() + + +def make_escpr_stub() -> bytes: + """最小 ESC/P-R 起始序列(仅用于格式协商测试,不含页面数据,不会成像)。""" + return (b"\x1b@\x1b(G\x00\x01\x00\x00\x01" # ESC @ 复位 + ESC ( G 图形模式 + b"\x1b\x01@EJL 1284.4\n@EJL \n") # Epson EJL 作业语言头 + + +def render_pages(src: Path, dpi: int = 300, quality: int = 92) -> list[bytes]: + """把 PDF / 图片渲染成逐页 JPEG 字节流。 + + 设备 document-format 支持 image/jpeg(Mopria 2.0 认证),因此 + 任意文档 = 先栅格化再逐页提交,无需厂商驱动、无需 ESC/P-R 编码器。 + """ + from io import BytesIO + + from PIL import Image + + pages: list[bytes] = [] + if src.suffix.lower() == ".pdf": + import pypdfium2 as pdfium + pdf = pdfium.PdfDocument(str(src)) + scale = dpi / 72.0 + for i in range(len(pdf)): + bitmap = pdf[i].render(scale=scale, rotation=0) + img = bitmap.to_pil().convert("RGB") + buf = BytesIO() + img.save(buf, "JPEG", quality=quality, dpi=(dpi, dpi)) + pages.append(buf.getvalue()) + img.close() + pdf.close() + else: + img = Image.open(src).convert("RGB") + buf = BytesIO() + img.save(buf, "JPEG", quality=quality, dpi=(dpi, dpi)) + pages.append(buf.getvalue()) + img.close() + return pages + + +# --------------------------------------------------------------------------- # +# CLI +# --------------------------------------------------------------------------- # +def _resolve_payload(args) -> tuple[list[tuple[bytes, str]], str]: + """返回 [(载荷, mime), ...];一个元素=一个 IPP 作业。""" + if args.input: + pages = render_pages(Path(args.input), dpi=args.dpi) + return [(p, "image/jpeg") for p in pages], f"渲染 {len(pages)} 页 @ {args.dpi}dpi" + if args.file: + p = Path(args.file) + mime = {"jpeg": "image/jpeg", "escpr": "application/vnd.epson.escpr", + "pwg": "image/pwg-raster"}[args.fmt] + return [(p.read_bytes(), mime)], f"读取 {p.name} ({p.stat().st_size}B)" + if args.fmt == "jpeg": + return [(make_jpeg(), "image/jpeg")], "内置测试图" + return [(make_escpr_stub(), "application/vnd.epson.escpr" + if args.fmt == "escpr" else "image/pwg-raster")], "内置最小载荷" + + +def cmd_info(c: PrinterClient) -> int: + r = c.get_attributes() + a = r["attrs"] + print(f"IPP 状态 : {r['status']}") + for k in ("printer-make-and-model", "printer-name", "printer-state", + "printer-state-reasons", "printer-is-accepting-jobs", + "document-format-supported", "document-format-default", + "media-default", "sides-supported", "print-color-mode-supported", + "printer-device-id", "printer-firmware-string-version", "pages-per-minute", + "mopria-certified", "queued-job-count"): + if k in a: + print(f"{k:<30}: {a[k]}") + return 0 + + +def cmd_validate(c: PrinterClient, args) -> int: + payloads, note = _resolve_payload(args) + doc, mime = payloads[0] + print(f"载荷: {note}") + r = c.validate_job(doc, mime, job_name=f"37du-validate-{args.fmt}", + media=args.media, sides=args.sides, color=args.color) + print(f"Validate-Job [{mime}] -> {r['status']} (0x{r['status_code']:04X})" + f",载荷 {len(doc)}B") + for k, v in r["attrs"].items(): + if k in ("status-message", "job-state-reasons", "document-format-supported"): + print(f" {k} = {v}") + ok = r["status_code"] < 0x0100 + print("结论: 设备接受该作业参数与格式(Device did NOT print)" if ok + else "结论: 设备拒绝该作业") + return 0 if ok else 2 + + +def cmd_print(c: PrinterClient, args) -> int: + payloads, note = _resolve_payload(args) + print(f"载荷: {note},共 {len(payloads)} 个作业") + if not args.yes: + for i, (doc, mime) in enumerate(payloads, 1): + print(f" [干跑] 作业{i}: {mime} {len(doc)}B " + f"MD5={__import__('hashlib').md5(doc).hexdigest()[:16]}") + print("拒绝执行:真正打印必须显式加 --yes。已完成干跑,未向设备发送任何作业。") + return 3 + rc = 0 + for i, (doc, mime) in enumerate(payloads, 1): + r = c.print_job(doc, mime, job_name=f"37du-{i}", + media=args.media, sides=args.sides, color=args.color) + print(f" Print-Job 页{i} -> {r['status']}") + if r["status_code"] >= 0x0100: + rc = 2 + print(" " + json.dumps(r["attrs"], ensure_ascii=False)) + return rc + + +def cmd_render(args) -> int: + """只做栅格化,把将要发给打印机的字节落盘,便于离线检查。""" + pages = render_pages(Path(args.input), dpi=args.dpi) + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + for i, p in enumerate(pages, 1): + f = out / f"page-{i:03d}.jpg" + f.write_bytes(p) + print(f" {f} {len(p)}B ({len(p)/1024:.1f} KB)") + print(f"共 {len(pages)} 页,未连接打印机。") + return 0 + + +def main() -> int: + ap = argparse.ArgumentParser(description="EPSON IPP 直连打印客户端") + ap.add_argument("action", choices=["info", "validate", "print", "render", "jobs"]) + ap.add_argument("--ip", default=DEFAULT_IP) + ap.add_argument("--port", type=int, default=IPP_PORT) + ap.add_argument("--path", default="/ipp/print") + ap.add_argument("--fmt", default="jpeg", choices=["jpeg", "escpr", "pwg"]) + ap.add_argument("--input", help="源文档 pdf/png/jpg,自动栅格化为 JPEG") + ap.add_argument("--file", help="现成载荷文件(配合 --fmt 指定 mime)") + ap.add_argument("--out", default="tools/out", help="render 输出目录") + ap.add_argument("--dpi", type=int, default=300) + ap.add_argument("--media", default=None, help="如 iso_a4_210x297mm") + ap.add_argument("--sides", default=None, + choices=["one-sided", "two-sided-long-edge", "two-sided-short-edge"]) + ap.add_argument("--color", default=None, + choices=["color", "monochrome", "auto"]) + ap.add_argument("--yes", action="store_true", help="确认真正打印") + ap.add_argument("--no-tls", action="store_true", help="明文 IPP(本机实测会被 426 拒绝)") + args = ap.parse_args() + + if args.action == "render": + if not args.input: + print("render 需要 --input", file=sys.stderr) + return 1 + return cmd_render(args) + + c = PrinterClient(args.ip, args.port, args.path, tls=not args.no_tls) + print(f"目标: {c.uri}") + try: + if args.action == "info": + return cmd_info(c) + if args.action == "validate": + return cmd_validate(c, args) + if args.action == "print": + return cmd_print(c, args) + if args.action == "jobs": + print(json.dumps(c.get_jobs(), ensure_ascii=False, indent=1)) + return 0 + except (socket.error, ssl.SSLError, OSError) as e: + print(f"通信失败: {type(e).__name__}: {e}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/printer_probe.py b/tools/printer_probe.py new file mode 100644 index 0000000..29fe93f --- /dev/null +++ b/tools/printer_probe.py @@ -0,0 +1,387 @@ +# -*- coding: utf-8 -*- +"""打印机协议探测脚本(只探测,不打印)。 + +用途:对指定 IP 的网络打印机做非破坏性探测,逆向识别 + - 开放端口(Raw9100 / IPP631 / LPD515 / HTTP80 / HTTPS443) + - 厂商与型号(HTTP Server 头、IPP Get-Printer-Attributes) + - 支持的文档格式与打印语言(application/pdf / ESC/P-R / ESC/POS ...) + - LPD 队列名(仅发送查询类命令,不提交打印作业) +本脚本不会向任何端口写入任何打印数据,可安全反复运行。 + +用法: + .venv\\Scripts\\python.exe tools\\printer_probe.py + .venv\\Scripts\\python.exe tools\\printer_probe.py --ip 172.30.40.254 +结果同时打印到控制台并落盘 tools/printer_probe_result.json +""" + +from __future__ import annotations + +import argparse +import json +import socket +import struct +import sys +import time +from pathlib import Path + +DEFAULT_IP = "172.30.40.254" +COMMON_PORTS = [21, 23, 80, 443, 515, 631, 9100, 8080, 8443, 161, 427, 3702, 5353] + + +# --------------------------------------------------------------------------- # +# 基础网络工具 +# --------------------------------------------------------------------------- # +def tcp_open(ip: str, port: int, timeout: float = 0.9) -> bool: + """判断 TCP 端口是否可建立连接(不做任何读写)。""" + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.settimeout(timeout) + try: + return s.connect_ex((ip, port)) == 0 + except OSError: + return False + finally: + s.close() + + +def send_recv(ip: str, port: int, payload: bytes = b"", wait: float = 0.8, + timeout: float = 4.0, first: bool = False) -> bytes: + """建立连接、可选发送数据、读回响应。payload 为空则只做被动读取。""" + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.settimeout(timeout) + s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + data = b"" + try: + s.connect((ip, port)) + if payload: + s.sendall(payload) + time.sleep(wait) + while True: + try: + chunk = s.recv(4096) + except socket.timeout: + break + if not chunk: + break + data += chunk + if first and data: + break + if len(data) > 200_000: + break + except OSError: + pass + finally: + s.close() + return data + + +def dump(data: bytes, limit: int = 700) -> str: + """把响应渲染成可读文本(不可见字节转 '.'),便于看协议头。""" + if not data: + return "<空>" + txt = data.decode("utf-8", "replace") + return "".join(c if c in "\r\n\t" or 0x20 <= ord(c) <= 0x7E else "." for c in txt)[:limit] + + +# --------------------------------------------------------------------------- # +# HTTP / HTTPS 探测 +# --------------------------------------------------------------------------- # +HTTP_PATHS = [ + "/", "/index.html", "/PRESENTATION/HTML/TOP/INDEX.HTML", + "/EPSON_HTM/HTML/TOP/INDEX.HTML", "/webconfig", "/cgi-bin/status", + "/status", "/ipp/print", "/info", "/wnstatus.cgi", +] + + +def http_get(ip: str, port: int, path: str, timeout: float = 4.0) -> tuple[int, str, bytes]: + """极简 HTTP/1.0 GET(Epson 嵌入式服务器对 HTTP/1.1 会直接断链)。""" + req = ( + f"GET {path} HTTP/1.0\r\n" + f"Host: {ip}:{port}\r\n" + "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\r\n" + "Accept: */*\r\n" + "Connection: close\r\n\r\n" + ).encode("ascii", "ignore") + raw = send_recv(ip, port, req, wait=0.6, timeout=timeout) + if not raw: + return 0, "", b"" + head = raw.split(b"\r\n\r\n", 1)[0].decode("latin-1", "replace") + first = head.split("\r\n", 1)[0] + code = 0 + for tok in first.split(): + if tok.isdigit(): + code = int(tok) + break + body = raw.split(b"\r\n\r\n", 1)[1] if b"\r\n\r\n" in raw else b"" + return code, head, body + + +def probe_http(ip: str, port: int) -> dict: + hits = [] + for path in HTTP_PATHS: + code, head, body = http_get(ip, port, path) + if code: + hits.append({"path": path, "status": code, "headers": head, "body_len": len(body)}) + print(f" {path:<38} {code} body={len(body)}B") + time.sleep(0.05) + server = "" + for h in hits: + if h["path"] == "/": + for line in h["headers"].split("\r\n"): + if line.lower().startswith("server:"): + server = line.split(":", 1)[1].strip() + return {"port": port, "server": server, "hits": hits} + + +# --------------------------------------------------------------------------- # +# IPP 1.1/2.0 构造(RFC 8010 / 8011) +# --------------------------------------------------------------------------- # +TAG_OPERATION = 0x01 +TAG_END = 0x03 +TAG_CHARSET = 0x47 +TAG_LANGUAGE = 0x48 +TAG_URI = 0x45 +TAG_KEYWORD = 0x44 +TAG_NAME = 0x42 + +OP_GET_PRINTER_ATTRIBUTES = 0x000B +OP_GET_JOBS = 0x000A + + +def _attr(tag: int, name: str, value: bytes) -> bytes: + n = name.encode("utf-8") + return bytes([tag]) + struct.pack(">H", len(n)) + n + struct.pack(">H", len(value)) + value + + +def ipp_request(op: int, uri: str, req_id: int = 1, extra: bytes = b"") -> bytes: + body = bytes([TAG_OPERATION]) + body += _attr(TAG_CHARSET, "attributes-charset", b"utf-8") + body += _attr(TAG_LANGUAGE, "attributes-natural-language", b"en-us") + body += _attr(TAG_URI, "printer-uri", uri.encode("utf-8")) + body += extra + body += bytes([TAG_END]) + return struct.pack(">BBHI", 2, 0, op, req_id) + body + + +def ipp_parse(data: bytes) -> tuple[int, dict]: + """解析 IPP 响应的头两字节状态码 + 属性表(不含集合/1setOf 展开)。""" + if len(data) < 8: + return -1, {} + status = struct.unpack(">H", data[2:4])[0] + attrs: dict[str, list] = {} + i, cur = 8, None + while i < len(data): + tag = data[i] + if tag == TAG_END: + break + if tag < 0x10: # 分隔标签 + i += 1 + continue + if i + 2 > len(data): + break + nlen = struct.unpack(">H", data[i + 1:i + 3])[0] + name = data[i + 3:i + 3 + nlen].decode("utf-8", "replace") + i += 3 + nlen + if i + 2 > len(data): + break + vlen = struct.unpack(">H", data[i:i + 2])[0] + raw = data[i + 2:i + 2 + vlen] + i += 2 + vlen + cur = name or cur + attrs.setdefault(cur or "?", []).append((tag, raw)) + return status, attrs + + +def _decode(tag: int, raw: bytes): + try: + if tag in (0x21, 0x23): # integer / enum + return struct.unpack(">i", raw)[0] if len(raw) == 4 else int.from_bytes(raw, "big") + if tag == 0x22: + return struct.unpack(">b", raw)[0] if len(raw) == 1 else None + if tag == 0x41: # textWithLanguage 简化 + return raw.decode("utf-8", "replace") + return raw.decode("utf-8", "replace") + except Exception: + return raw.hex() + + +IPP_STATUS = { + 0x0000: "successful-ok", + 0x0400: "client-error-bad-request", + 0x0401: "client-error-forbidden", + 0x0403: "client-error-not-found", + 0x0500: "server-error-internal-error", + 0x0502: "server-error-service-unavailable", +} + + +def ipp_post(ip: str, port: int, path: str, body: bytes, timeout: float = 8.0, + http11: bool = True) -> tuple[int, bytes]: + """IPP 走 HTTP POST + Content-Type: application/ipp(RFC 8010 第 4 章)。""" + ver = "HTTP/1.1" if http11 else "HTTP/1.0" + head = ( + f"POST {path} {ver}\r\n" + f"Host: {ip}:{port}\r\n" + "Content-Type: application/ipp\r\n" + f"Content-Length: {len(body)}\r\n" + "Connection: close\r\n\r\n" + ).encode("ascii") + raw = send_recv(ip, port, head + body, wait=1.2, timeout=timeout) + if not raw: + return 0, b"" + code = 0 + for tok in raw.split(b"\r\n", 1)[0].split(): + if tok.isdigit(): + code = int(tok) + break + resp = raw.split(b"\r\n\r\n", 1) + return code, (resp[1] if len(resp) > 1 else b"") + + +def probe_ipp(ip: str, port: int = 631) -> dict: + """对 IPP 服务做 Get-Printer-Attributes,读取型号/格式/状态。""" + result: dict = {"port": port, "uri": None, "status": None, "attrs": {}} + candidates = [(f"ipp://{ip}:{port}/ipp/print", "/ipp/print"), + (f"ipp://{ip}:{port}/ipp/printer", "/ipp/printer"), + (f"ipp://{ip}:{port}/", "/"), + (f"ipp://{ip}/ipp/print", "/ipp/print")] + wanted = [b"printer-name", b"printer-info", b"printer-make-and-model", + b"printer-state", b"printer-state-reasons", b"document-format-supported", + b"document-format-default", b"compression-supported", b"ipp-versions-supported", + b"operations-supported", b"printer-location", b"printer-uuid", + b"printer-device-id", b"media-supported", b"printer-supply-info-uri", + b"sides-supported", b"output-bin-default", b"media-default", + b"print-color-mode-supported", b"printer-resolution-supported", + b"job-creation-attributes-supported", b"pdf-versions-supported", + b"document-format-preferred"] + extra = b"" + payload = b"" + for kw in wanted: + payload += _attr(TAG_KEYWORD, "requested-attributes", kw) + + for uri, path in candidates: + req = ipp_request(OP_GET_PRINTER_ATTRIBUTES, uri, 1, payload) + code, body = ipp_post(ip, port, path, req) + status, attrs = ipp_parse(body) if len(body) >= 8 else (-1, {}) + print(f" {path:<14} http={code or 'ERR':<4} ipp={IPP_STATUS.get(status, hex(status) if status >= 0 else 'none'):<26} attrs={len(attrs)}") + if attrs: + flat = {} + for k, vals in attrs.items(): + flat[k] = [_decode(t, v) for t, v in vals] + result.update({"uri": uri, "path": path, "http_status": code, + "status": IPP_STATUS.get(status, hex(status)), + "attrs": flat, "raw_len": len(body)}) + return result + if code: + result.update({"uri": uri, "path": path, "http_status": code, + "status": IPP_STATUS.get(status, hex(status) if status >= 0 else "none")}) + time.sleep(0.05) + # / 目录下的打印机列表 + root_uri = f"ipp://{ip}:{port}/" + req = ipp_request(OP_GET_PRINTER_ATTRIBUTES, root_uri, 2, + _attr(TAG_KEYWORD, "requested-attributes", b"printer-name") + + _attr(TAG_KEYWORD, "requested-attributes", b"printer-uri-supported")) + raw = send_recv(ip, port, req, wait=1.0, timeout=6.0) + if len(raw) >= 8: + st, at = ipp_parse(raw) + if at: + result["root_uri"] = root_uri + result["root_attrs"] = {k: [_decode(t, v) for t, v in vv] for k, vv in at.items()} + return result + + +# --------------------------------------------------------------------------- # +# LPD (RFC 1179) 队列探测:只发查询,不发打印 +# --------------------------------------------------------------------------- # +LPD_QUEUES = ["PASSTHRU", "EPSON", "PRINT", "lp", "LPT1", "RAW", "TEXT", "BINARY_P1", "auto"] + + +def probe_lpd(ip: str, port: int = 515) -> dict: + """发送 LPD 状态查询命令(\\x04queue\\n),返回队列是否存在。 + + 注意:\\x04 是 "查询队列状态",不是打印命令;本函数不会发送 \\x02 作业提交。 + """ + out = {} + for q in LPD_QUEUES: + req = b"\x04" + q.encode() + b"\n" + raw = send_recv(ip, port, req, wait=0.6, timeout=3.0) + state = "no-reply" + if raw: + state = dump(raw, 160).replace("\r", "\\r").replace("\n", "\\n") + out[q] = state + print(f" queue {q:<12} -> {state[:90]}") + time.sleep(0.05) + return {"port": port, "queues": out} + + +# --------------------------------------------------------------------------- # +# 9100 Raw 探测:只发送 PJL 状态命令(UEL + INFO),绝不发送打印数据 +# --------------------------------------------------------------------------- # +PJL_INFO = ( + b"\x1b%-12345X@PJL\r\n" + b"@PJL INFO ID\r\n" + b"@PJL INFO STATUS\r\n" + b"@PJL INFO CONFIG\r\n" + b"@PJL USTATUS DEVICE = ON\r\n" + b"\x1b%-12345X" +) + + +def probe_raw(ip: str, port: int = 9100) -> dict: + """9100 端口 PJL 探测。EPSON 喷墨多数不实现 PJL,会静默或回显。""" + raw = send_recv(ip, port, PJL_INFO, wait=1.2, timeout=4.0) + print(f" PJL INFO -> {len(raw)}B {dump(raw, 240)}") + + # Epson 远程状态查询:ESC/P 的 "ESC ( U" 等需要真实打印通道,此处不发送。 + # 仅做连通性与静默性判定:连接成功但不回数据,说明为纯打印数据通道。 + return {"port": port, "pjl_bytes": len(raw), "pjl_reply": dump(raw, 600), + "pure_data_channel": len(raw) == 0} + + +# --------------------------------------------------------------------------- # +# 主流程 +# --------------------------------------------------------------------------- # +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--ip", default=DEFAULT_IP) + ap.add_argument("--out", default="tools/printer_probe_result.json") + args = ap.parse_args() + ip = args.ip + + report: dict = {"ip": ip, "time": time.strftime("%Y-%m-%d %H:%M:%S"), "ports": {}} + + print(f"[1/5] 端口扫描 {ip}") + for p in COMMON_PORTS: + open_ = tcp_open(ip, p) + report["ports"][p] = open_ + if open_: + print(f" {p:<6} OPEN") + + if report["ports"].get(80): + print("[2/5] HTTP 探测 :80") + report["http80"] = probe_http(ip, 80) + if report["ports"].get(443): + print("[2/5] HTTPS 探测 :443") + report["https443"] = {"note": "443 开放;嵌入式 Epson 多为自签证书," + "本次仅记录端口,未做 TLS 握手(避免证书告警)"} + + if report["ports"].get(631): + print("[3/5] IPP Get-Printer-Attributes :631") + report["ipp"] = probe_ipp(ip, 631) + + if report["ports"].get(515): + print("[4/5] LPD 队列查询 :515") + report["lpd"] = probe_lpd(ip, 515) + + if report["ports"].get(9100): + print("[5/5] Raw 9100 PJL 探测") + report["raw9100"] = probe_raw(ip, 9100) + + out = Path(args.out) + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") + print(f"\n结果已写入 {out.resolve()}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/sheet_print.py b/tools/sheet_print.py new file mode 100644 index 0000000..d5c6db7 --- /dev/null +++ b/tools/sheet_print.py @@ -0,0 +1,481 @@ +# -*- coding: utf-8 -*- +"""读取 Excel/WPS 工作表 → 按列过滤 → 生成矢量 PDF(可选直接送打印机)。 + +解决的是"WPS 固定区域打印"这类需求:不依赖 WPS 的导出(本机 12.1 版导出 PDF +有排版缩放 bug),改为自己读单元格值、自己排版、自己出 PDF。 + +过滤规则(默认,可关) +-------------------- +丢掉:空值 / 0 / Excel 错误值(#REF! #N/A #VALUE! ...) / 文本"错误" + +用法 +---- + # 只看不打印 + python tools/sheet_print.py --file "D:\\x.xlsx" --sheet 单子传递打印 \ + --col "FRECTUNIT#Name" --out tools/out/out.pdf + + # 渲染并真机打印 + python tools/sheet_print.py --file "D:\\x.xlsx" --sheet 单子传递打印 \ + --col "FRECTUNIT#Name" --print-to "fe80::9eae:d3ff:fef8:17ea%8" --yes +""" + +from __future__ import annotations + +import argparse +import datetime as _dt +import math +import re +import sys +from pathlib import Path + +import fitz # PyMuPDF +import openpyxl + +FONT_R = r"C:\Windows\Fonts\msyh.ttc" +FONT_B = r"C:\Windows\Fonts\msyhbd.ttc" + +A4_W, A4_H = 595.28, 841.89 +ERR_RE = re.compile(r"^#(REF!|N/A|VALUE!|DIV/0!|NAME\?|NULL!|NUM!|GETTING_DATA)$", re.I) +ERR_WORDS = {"错误", "error", "#error"} + + +# --------------------------------------------------------------------------- # +# 取值与过滤 +# --------------------------------------------------------------------------- # +def fmt_value(v) -> str: + """把单元格值转成可打印文本。""" + if v is None: + return "" + if isinstance(v, _dt.datetime): + return v.strftime("%Y-%m-%d") if (v.hour, v.minute) == (0, 0) else v.strftime("%Y-%m-%d %H:%M") + if isinstance(v, _dt.date): + return v.strftime("%Y-%m-%d") + if isinstance(v, bool): + return "是" if v else "否" + if isinstance(v, float): + return str(int(v)) if v.is_integer() else f"{v:g}" + return str(v) + + +def is_bad(v) -> bool: + """空 / 0 / 错误值 / 文本"错误" → 丢弃。""" + if v is None: + return True + if isinstance(v, str): + s = v.strip() + if s == "" or s == "0" or ERR_RE.match(s) or s.lower() in ERR_WORDS: + return True + return False + if isinstance(v, (int, float)) and not isinstance(v, bool): + return v == 0 + return False + + +def find_column(ws, key: str, header_row: int) -> int: + """按字段名(第1行)或中文标题(header_row)或列字母定位列号。""" + if re.fullmatch(r"[A-Za-z]{1,3}", key): + return openpyxl.utils.column_index_from_string(key.upper()) + for r in (1, header_row): + for c in range(1, ws.max_column + 1): + v = ws.cell(row=r, column=c).value + if v is not None and str(v).strip() == key: + return c + # 宽松匹配 + for r in (1, header_row): + for c in range(1, ws.max_column + 1): + v = ws.cell(row=r, column=c).value + if v is not None and key.lower() in str(v).lower(): + return c + raise ValueError(f"找不到列 {key!r}") + + +# --------------------------------------------------------------------------- # +# 排版 +# --------------------------------------------------------------------------- # +class TablePDF: + def __init__(self, title: str = "", fontsize: float = 9.0, + margin: float = 42.0, landscape: bool = False): + self.font_r = fitz.Font(fontfile=FONT_R) + self.font_b = fitz.Font(fontfile=FONT_B) + self.title = title + self.fs = fontsize + self.margin = margin + self.doc = fitz.open() + self.W, self.H = (A4_H, A4_W) if landscape else (A4_W, A4_H) + self.page = None + self.y = 0.0 + self.page_no = 0 + self.cont = True # 第 2 页起页脚加"(续)" + self._new_page() + + # --- 页面 --- + def _new_page(self): + self.page = self.doc.new_page(width=self.W, height=self.H) + self.page.insert_font(fontname="cjk", fontfile=FONT_R) + self.page.insert_font(fontname="cjkb", fontfile=FONT_B) + self.page_no += 1 + self.y = self.margin + if self.title: + self.page.insert_text((self.margin, self.y + 14), self.title, + fontname="cjkb", fontsize=self.fs + 5) + self.y += 34 + + def _measure(self, text: str, bold: bool = False, size: float | None = None) -> float: + f = self.font_b if bold else self.font_r + return f.text_length(text, fontsize=size or self.fs) + + # 收尾标点不允许出现在行首(中文排版禁则) + CLOSERS = "))】]},,。.、;;::!!??%" + + def _wrap(self, text: str, width: float, bold: bool = False, + size: float | None = None) -> list[str]: + """按实际字形宽度折行(中文可任意断行,英文尽量不断在单词中间)。""" + if not text: + return [""] + size = size or self.fs + lines, cur = [], "" + for ch in text: + if self._measure(cur + ch, bold, size) <= width: + cur += ch + continue + if cur and ch in self.CLOSERS: + # 收尾标点挂在行尾(允许 1 字溢出),避免 "(序号" 换行后只剩 ")" + cur += ch + lines.append(cur) + cur = "" + continue + if cur and ch not in " ": + # 英文单词尽量不断开 + m = re.search(r"[A-Za-z0-9_#%\.\-]+$", cur) + if m and ch.isalnum(): + keep = cur[:m.start()] + if keep: + lines.append(keep) + cur = cur[m.start():] + ch + continue + lines.append(cur) + cur = "" if ch == " " else ch + lines.append(cur) + return lines or [""] + + # --- 表格 --- + def table(self, header_rows: list[list[str]], rows: list[list[str]], + weights: list[float] | None = None, min_widths: list[float] | None = None, + total_row: list[str] | None = None): + """header_rows: 多行表头,例如 [英文字段行, 中文标题行]。 + total_row: 末尾合计行(加粗 + 双线上边框)。""" + avail = self.W - 2 * self.margin + n = len(header_rows[0]) + fs = self.fs + + # 英文字段行不一定放得下,自动缩字号直到整行放得下(不低于 6pt) + fs_key = max(6.0, fs * 0.86) + # 单列宽度上限:防止某个超长单元格把其它列挤成竖排单字 + cap = max(120.0, avail / n * 2.2) + floor = max(34.0, min(56.0, avail / n * 0.55)) + + def natural_widths(key_size: float) -> list[float]: + out = [] + for i in range(n): + w = 0.0 + for bi, hr in enumerate(header_rows): + sz = key_size if bi == 0 else fs + w = max(w, self._measure(hr[i], bold=True, size=sz) + 12) + for r in rows[:400]: + w = max(w, self._measure(r[i], size=fs) + 12) + out.append(min(w, cap)) + return out + + def fit_to_avail(nat: list[float]) -> list[float]: + """按比例铺满可用宽度,同时保证每列不小于 floor。""" + w = list(nat) + tot = sum(w) or 1.0 + w = [x * avail / tot for x in w] + for _ in range(5): + low = [i for i, x in enumerate(w) if x < floor] + if not low or len(low) == n: + if len(low) == n: + return [avail / n] * n + break + rest = avail - floor * len(low) + high = [i for i in range(n) if i not in low] + htot = sum(w[i] for i in high) or 1.0 + for i in high: + w[i] = w[i] * rest / htot + for i in low: + w[i] = floor + if all(w[i] >= floor for i in high): + break + return w + + nat = natural_widths(fs_key) + while sum(nat) > avail and fs_key > 6.0: + fs_key *= 0.94 + nat = natural_widths(fs_key) + + widths = fit_to_avail(nat) + if min_widths: + widths = [max(w, min_widths[i]) for i, w in enumerate(widths)] + k = avail / sum(widths) + widths = [w * k for w in widths] + + lh = fs * 1.45 + pad = 3.0 + bottom_limit = self.H - self.margin - 14 + + def header_bands(): + """返回 [(该行折行结果, 该行高度, 该行字号), ...]。""" + out = [] + for bi, hr in enumerate(header_rows): + sz = fs_key if bi == 0 else fs + wrapped = [self._wrap(hr[i], widths[i] - 2 * pad, bold=True, size=sz) + for i in range(n)] + out.append((wrapped, max(len(x) for x in wrapped) * sz * 1.45 + 2 * pad, sz)) + return out + + bands = header_bands() + header_h = sum(h for _, h, _ in bands) + + # 数字列右对齐(金额、序号等),文本列左对齐 + num_re = re.compile(r"^-?[\d,]+(\.\d+)?%?$") + aligns: list[str] = [] + for i in range(n): + vals = [r[i].strip() for r in rows if r[i].strip()] + aligns.append("right" if vals and all(num_re.match(v) for v in vals) else "left") + + # 每个数据行先算好折行与行高;超过一整页的极端单元格做截断,避免死循环 + # 注意:每页都重绘标题,可用高度要扣掉标题占位 + title_h = 34.0 if self.title else 0.0 + avail_for_rows = bottom_limit - (self.margin + title_h) - header_h + max_cell_lines = max(1, int(avail_for_rows // lh) - 1) + prepared: list[tuple[list[list[str]], float]] = [] + for row in rows: + cells = [self._wrap(row[i], widths[i] - 2 * pad) for i in range(n)] + over = [j for j in range(n) if len(cells[j]) > max_cell_lines] + if over: + cells = [c[:max_cell_lines] for c in cells] + for j in over: # 只给真正被截断的单元格加省略号 + cells[j][-1] += "…" + h = max(len(c) for c in cells) * lh + 2 * pad + prepared.append((cells, h)) + + # 记录每页表格区域 [(page, top, bottom)],用于最后统画竖线和外框 + regions: list[list] = [] + open_region: list[list | None] = [None] + + def start_region(): + if open_region[0] is None: + # 存页号而不是 Page 对象:新增页面后旧 Page 引用会失效 + open_region[0] = [self.page.number, self.y, None] + + def close_region(): + if open_region[0] is not None: + open_region[0][2] = self.y + regions.append(open_region[0]) + open_region[0] = None + + def page_break(): + close_region() + self._new_page() + + def draw_header(): + if self.y + header_h > bottom_limit: + page_break() + start_region() + y0 = self.y + for bi, (wrapped, h, sz) in enumerate(bands): + # 英文字段行浅灰,中文标题行更深一点的灰 + fill = (0.87, 0.87, 0.87) if bi == 0 else (0.94, 0.94, 0.94) + self.page.draw_rect(fitz.Rect(self.margin, y0, self.margin + avail, y0 + h), + color=None, fill=fill) + x = self.margin + for i in range(n): + ty = y0 + pad + sz + for ln in wrapped[i]: + self.page.insert_text((x + pad, ty), ln, fontname="cjkb", fontsize=sz) + ty += sz * 1.45 + x += widths[i] + y0 += h + self.page.draw_line(fitz.Point(self.margin, y0), + fitz.Point(self.margin + avail, y0), + color=(0, 0, 0), width=0.6) + self.y = y0 + + def draw_row(cells: list[list[str]], h: float, bold: bool = False): + x = self.margin + for i in range(n): + ty = self.y + pad + fs + for ln in cells[i]: + tx = x + pad + if aligns[i] == "right": + tx = x + widths[i] - pad - self._measure(ln, bold, fs) + self.page.insert_text((tx, ty), ln, + fontname="cjkb" if bold else "cjk", fontsize=fs) + ty += lh + x += widths[i] + self.page.draw_line(fitz.Point(self.margin, self.y + h), + fitz.Point(self.margin + avail, self.y + h), + color=(0, 0, 0), width=1.2 if bold else 0.6) + self.y += h + + draw_header() + for ri, (cells, h) in enumerate(prepared): + if self.y + h > bottom_limit: + page_break() + draw_header() + if ri % 2 == 1: + self.page.draw_rect(fitz.Rect(self.margin, self.y, self.margin + avail, self.y + h), + color=None, fill=(0.965, 0.965, 0.965)) + draw_row(cells, h) + + # 合计行:加粗 + 粗上边框,尽量跟最后一行同页 + if total_row: + tcells = [self._wrap(total_row[i], widths[i] - 2 * pad, bold=True) for i in range(n)] + th = max(len(c) for c in tcells) * lh + 2 * pad + if self.y + th > bottom_limit: + page_break() + draw_header() + self.page.draw_rect(fitz.Rect(self.margin, self.y, self.margin + avail, self.y + th), + color=None, fill=(0.90, 0.90, 0.90)) + draw_row(tcells, th, bold=True) + close_region() + + # 每页分别补竖线与外框(分页时每页都要有完整边框) + for pno, top, bottom in regions: + pg = self.doc[pno] + x = self.margin + for i in range(n - 1): + x += widths[i] + pg.draw_line(fitz.Point(x, top), fitz.Point(x, bottom), + color=(0, 0, 0), width=0.6) + pg.draw_rect(fitz.Rect(self.margin, top, self.margin + avail, bottom), + color=(0, 0, 0), width=0.8) + + def footer(self, text: str): + for i, p in enumerate(self.doc): + t = text.replace("{page}", str(i + 1)).replace("{total}", str(len(self.doc))) + if self.cont and i > 0: + t = "(续)" + t + p.insert_text((self.W / 2 - self._measure(t) / 2, self.H - 22), + t, fontname="cjk", fontsize=8, color=(0.35, 0.35, 0.35)) + + def save(self, path: str) -> str: + p = Path(path) + p.parent.mkdir(parents=True, exist_ok=True) + try: + self.doc.subset_fonts() # 只嵌入用到的字形,否则整份 ttc 一起进去(几十 MB) + except Exception: + pass + self.doc.save(str(p), garbage=4, deflate=True) + self.doc.close() + return str(p) + + +# --------------------------------------------------------------------------- # +# 主流程 +# --------------------------------------------------------------------------- # +def build_pdf(src: str, sheet: str | None, col: str, header_row: int, + title: str, out: str, drop_bad: bool = True, + landscape: bool = False, fontsize: float = 9.0, + key_row: int | None = 1, with_total: bool = False) -> tuple[str, int]: + wb = openpyxl.load_workbook(src, data_only=True) + ws = wb[sheet] if sheet else wb.active + + ci = find_column(ws, col, header_row) + + # 表头行:第 1 行是英文字段名(如 FRECTUNIT#Name),第 2 行是中文标题 + hr_list = sorted({r for r in (key_row, header_row) if r and r >= 1}) + header_rows: list[list[str]] = [] + for r in hr_list: + line = [] + for c in range(1, ws.max_column + 1): + v = fmt_value(ws.cell(row=r, column=c).value) + line.append(v if v.strip() else f"列{openpyxl.utils.get_column_letter(c)}") + header_rows.append(line) + + first_data = max(hr_list) + 1 + rows = [] + for r in range(first_data, ws.max_row + 1): + key = ws.cell(row=r, column=ci).value + if drop_bad and is_bad(key): + continue + vals = [fmt_value(ws.cell(row=r, column=c).value) for c in range(1, ws.max_column + 1)] + if not any(v.strip() for v in vals): + continue + rows.append(vals) + wb.close() + + # 合计行:对每一列,若所有非空值都是数字则求和 + total_row = None + if with_total and rows: + ncol = len(header_rows[0]) + total_row = ["合计"] + [""] * (ncol - 1) + for i in range(1, ncol): + nums, ok = [], True + for r in rows: + sv = r[i].strip().replace(",", "") + if sv == "": + continue + try: + nums.append(float(sv)) + except ValueError: + ok = False + break + if ok and nums: + s = sum(nums) + has_dec = any("." in r[i] for r in rows) + total_row[i] = f"{s:,.2f}" if has_dec else f"{int(round(s)):,}" + + pdf = TablePDF(title=title, fontsize=fontsize, landscape=landscape) + pdf.table(header_rows, rows, total_row=total_row) + pdf.footer(f"共 {len(rows)} 行 · 第 {{page}} / {{total}} 页") + path = pdf.save(out) + return path, len(rows) + + +def main() -> int: + ap = argparse.ArgumentParser(description="Excel 工作表 → 过滤 → 矢量 PDF / 打印") + ap.add_argument("--file", required=True) + ap.add_argument("--sheet", default=None) + ap.add_argument("--col", required=True, help="过滤列:字段名(如 FRECTUNIT#Name) 或列字母") + ap.add_argument("--header-row", type=int, default=2, help="中文标题行(默认第 2 行)") + ap.add_argument("--key-row", type=int, default=1, + help="英文字段名行(默认第 1 行);设 0 表示不打印该行") + ap.add_argument("--title", default="") + ap.add_argument("--out", default="tools/out/sheet.pdf") + ap.add_argument("--fontsize", type=float, default=9.0) + ap.add_argument("--landscape", action="store_true") + ap.add_argument("--keep-bad", action="store_true", help="不过滤 0/错误/空") + ap.add_argument("--print-to", default=None, help="打印机 IPv4/IPv6 地址,给了就打印") + ap.add_argument("--yes", action="store_true", help="确认真正打印") + ap.add_argument("--allow-empty", action="store_true", help="0 行时也允许打印空表") + ap.add_argument("--total", action="store_true", help="末尾加合计行(数字列求和)") + a = ap.parse_args() + + path, n = build_pdf(a.file, a.sheet, a.col, a.header_row, + a.title or (a.sheet or ""), a.out, + drop_bad=not a.keep_bad, landscape=a.landscape, fontsize=a.fontsize, + key_row=a.key_row or None, with_total=a.total) + print(f"PDF: {path} 数据行={n} 大小={Path(path).stat().st_size/1024:.1f} KB") + + if a.print_to: + if n == 0: + print("过滤后 0 行,已跳过打印(确实要打空表加 --allow-empty)") + if not a.allow_empty: + return 0 + sys.path.insert(0, str(Path(__file__).parent)) + from printer_client import PrinterClient, render_pages + pages = render_pages(Path(path), dpi=300) + c = PrinterClient(a.print_to) + if not a.yes: + print(f"[干跑] 将发送 {len(pages)} 页 -> {c.uri}") + return 0 + for i, pg in enumerate(pages, 1): + r = c.print_job(pg, "image/jpeg", job_name=f"sheet-{i}", + media="iso_a4_210x297mm", color="color") + print(f" Print-Job 页{i} -> {r['status']}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/xq0012_payapply_pdf.py b/tools/xq0012_payapply_pdf.py new file mode 100644 index 0000000..dee6492 --- /dev/null +++ b/tools/xq0012_payapply_pdf.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +"""XQ0012 套打 PDF 开发入口(薄封装)。 + +真正的实现在插件里:`plugins/XQ0001-0100/XQ0012 .../report/payapply_pdf.py`(随插件发布)。 +本脚本只是开发期的便利入口:从测试服取一张单,按套打版面出一张 PDF,便于比对/打印。 + +用法: + .venv\\Scripts\\python.exe tools/xq0012_payapply_pdf.py +""" +import importlib.util +import os +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +_PLUGIN_MOD = (ROOT / 'plugins' / 'XQ0001-0100' / + 'XQ0012 EHR预支及支付报酬自动发起ERP付款申请' / 'report' / 'payapply_pdf.py') + +_spec = importlib.util.spec_from_file_location('xq0012_payapply_pdf', _PLUGIN_MOD) +_mod = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_mod) + +from_view = _mod.from_view +render_payapply = _mod.render_payapply + +BILL_NO = 'FKSQ20261100023' # 演练单;可改成任意已存在的单据编号 +ACCT = '6842cfeb653336' # 集团备份账套(唯一开了 MQ) + + +def main(): + sys.path.insert(0, str(ROOT / 'libs' / 'erpsdk')) + from erpsdk import ErpClient + + kv = {} + for line in (ROOT / '.env').read_text(encoding='utf-8').splitlines(): + line = line.strip() + if line and not line.startswith('#') and '=' in line: + k, v = line.split('=', 1) + kv[k.strip()] = v.strip() + erp = ErpClient('test', acct=ACCT).login( + kv['test_erp_login_username'], kv['test_erp_login_password']) + doc = erp.view('CN_PAYAPPLY', number=BILL_NO) + out = str(ROOT / 'out' / f'套打_付款申请单_{BILL_NO}.pdf') + print(render_payapply(from_view(doc, BILL_NO), out)) + + +if __name__ == '__main__': + main() diff --git a/workflows/README.md b/workflows/README.md index 44e8164..8820879 100644 --- a/workflows/README.md +++ b/workflows/README.md @@ -91,6 +91,7 @@ workflows/ | 共享配置 | 项目根 `.env`(`workflows/share/*.py` 按文件位置上溯两级定位;缺失时再兼容当前工作目录 `.env` 与系统环境变量) | | OA 登录态 | `%LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json` | | HR 登录态 | `%LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json` | +| ERP 登录态(新版 / 旧版) | `%LOCALAPPDATA%\37duAutomation\.sessions\erp_cookies.json` / `erp_cookies_old.json`(由 `erp_sso_login.py` 经 OA 单点登录写入) | | 花名册文件(「37du花名册导出」指令输出) | `D:\资料\人资\花名册\花名册.xlsx` | > 桌面端(electron-shell)执行插件时,平台会话按账号隔离到 `.sessions\<账号>\`;影刀版沿用上述共享文件,二者互不影响。 @@ -185,6 +186,19 @@ workflows/ - 占位符仅允许纯变量(如 `{{姓名}}`、`{{下月}}`、`{{一次性扣款}}`),脚本自动兼容旧写法(`{{当前月+1}}`/`{{费用*2}}`) - 依赖:`openpyxl python-docx pywin32` +### 4.9 erp_sso_login.py(ERP 单点登录,OA → 金蝶云星空) + +- 独立模块,**纯接口无浏览器**:读 OA 登录态 → 向 OA 要 ERP 入口令牌 → 调 K3Cloud `Verify` 换 `kdservice-sessionid`,全程约 1 秒 +- 逆向来源:OA「系统入口 → ERP(新)/ERP(旧)」快捷方式(2026-11 实测通过);身份 = **OA 当前登录人**,权限随该员工在 ERP 中的角色 +- 入口: + - `ensure_login(app='new', force=False)` → `{success, cookie_path, message, relogin, identity}` + - `build_session(app='new', force=False)` → 可直接调 ERP WebAPI 的 `requests.Session`(有效则复用缓存,失效自动重登) + - `main(app='new', force=True)`:影刀自定义指令入口 +- `app`:`'new'` = criterion.erp.37du.co(OA 侧 `appName=erpnew`)/ `'old'` = erp.37du.co(`appName=erp`) +- 落盘:`erp_cookies.json`(新版)、`erp_cookies_old.json`(旧版),**新旧互不覆盖**;会话摘要 `erp_session_meta*.json` 记录 SSO 身份 +- ⚠ 报文必须 **JSON 体 + `Content-Type: text/json`**(用表单会解析失败);SSO 握手走 `Kingdee.BOS.ServiceFacade.ServicesStub`(`k3cloud` 小写、服务名保留官方拼写 `StartAppVerifySerivce`),业务接口走 `Kingdee.BOS.WebApi.ServicesStub`;`ud` 有时效需一口气跑完;`BuildSessionWithHtml5` 无需调用 +- 依赖:仅 `requests`;前置条件是 OA 登录态有效(由「37duOA登录」指令维护) + ## 5. 模块通信(弱耦合:文件 + 全局变量) ### 5.1 登录态通信(文件级,登录一次全局复用) diff --git a/workflows/share/erp_sso_login.py b/workflows/share/erp_sso_login.py new file mode 100644 index 0000000..8458843 --- /dev/null +++ b/workflows/share/erp_sso_login.py @@ -0,0 +1,436 @@ +# -*- coding: utf-8 -*- +""" +@FileName: erp_sso_login.py +@Description: 金蝶云星空 ERP 单点登录(OA → ERP),纯接口无浏览器版共享模块。 + 逆向自 OA「系统入口 → ERP(新)/ERP(旧)」的 SSO 链路(2026-11 实测通过)。 + +链路(全程 requests,无浏览器,约 1 秒): + 1. 读 OA 登录态 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json, + 并校验其有效(sysNotifyTodo.do?method=sumTodoCount 返回 JSON 即有效); + 2. GET https://oa.37du.co/portal/sso.do?method=token&appName=&redirect=/index + → 302 Location: https://?token=; + 3. GET 该 Location(跟随跳转)→ 落到 /K3Cloud/HTML5/lightstartapp.aspx?ud=, + 从最终 URL 取出 ud(内含 dbid/username/appid/signeddata/timestamp), + 同时会话里拿到 sl-session / ASP.NET_SessionId; + 4. POST /k3cloud/Kingdee.BOS.ServiceFacade.ServicesStub.StartAppVerifySerivce.Verify.common.kdsvc + Content-Type: text/json,JSON 体(ap0=clientinfo, customArgs=ud, ...), + → 返回 ResultType=1,并下发 kdservice-sessionid(关键会话凭据); + 5. 落盘 erp_cookies.json(app='old' 时为 erp_cookies_old.json,新旧互不覆盖), + 并用一次只读查询校验会话可用。 + +关键实现要点(踩坑记录,勿随意改动): + ⚠ 报文必须是 **JSON 体 + Content-Type: text/json**;用表单 data= 会报 + "Unexpected character encountered while parsing value: n",握手失败; + ⚠ 路径分两套:SSO 握手走 Kingdee.BOS.ServiceFacade.ServicesStub(k3cloud 小写、 + 服务名保留官方拼写 StartAppVerifySerivce),业务接口走 Kingdee.BOS.WebApi.ServicesStub; + ⚠ ud 有时效,第 3~4 步必须紧接连跑,不能中间插入长耗时操作; + ⚠ BuildSessionWithHtml5 在纯接口下返回 false,不需要调,Verify 已给会话; + ⚠ 登录身份 = OA 当前登录人,不是独立 ERP 账号,权限随该员工在 ERP 中的角色; + ⚠ ud 里的账套(dbid)由 OA 的 ERP 入口决定,本模块不硬编码账套。 + +对外入口: + ensure_login(app='new', force=False) -> dict + {success, cookie_path, message, relogin, identity} + build_session(app='new', force=False) -> requests.Session + 业务脚本用:登录态有效则复用,失效自动重登。 + main(app='new', force=True) -> dict + 影刀自定义指令调用入口(JSON 安全 dict)。 + +依赖(影刀「Python包管理」安装): + pip install requests + +配置: + 无新增环境变量;复用 OA 登录态文件,OA 登录由「37duOA登录」指令负责。 +""" + +import base64 +import datetime +import json +import os +import time +import urllib.parse +import uuid + +import requests + +# ================== 共享路径(与 oa_login / hr_login 统一) ================== +_APP_DATA_DIR = os.path.join( + os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), + '37duAutomation') +_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions') +OA_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json') +ERP_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'erp_cookies.json') # 新版 +ERP_COOKIE_FILE_OLD = os.path.join(_SESSIONS_DIR, 'erp_cookies_old.json') # 旧版 +ERP_META_FILE = os.path.join(_SESSIONS_DIR, 'erp_session_meta.json') +ERP_META_FILE_OLD = os.path.join(_SESSIONS_DIR, 'erp_session_meta_old.json') + +# ================== 站点与接口常量 ================== +OA_BASE = 'https://oa.37du.co' +OA_VALIDATE_URL = OA_BASE + '/sys/notify/sys_notify_todo/sysNotifyTodo.do?method=sumTodoCount' +SSO_URL_TPL = OA_BASE + '/portal/sso.do?method=token&appName={app}&redirect=/index' + +# app 标识 → (ERP 主机, OA 侧 appName) +ERP_SITES = { + 'new': ('criterion.erp.37du.co', 'erpnew'), + 'old': ('erp.37du.co', 'erp'), +} + +# SSO 握手服务(Kingdee.BOS.ServiceFacade,路径小写 k3cloud,服务名保留官方拼写) +VERIFY_SVC = ('/k3cloud/Kingdee.BOS.ServiceFacade.ServicesStub' + '.StartAppVerifySerivce.Verify.common.kdsvc') +# 业务查询服务(Kingdee.BOS.WebApi) +QUERY_SVC = ('/K3Cloud/Kingdee.BOS.WebApi.ServicesStub' + '.DynamicFormService.ExecuteBillQuery.common.kdsvc') + +UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' + '(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36') +XHR_HEADERS = { + 'User-Agent': UA, + 'X-Requested-With': 'XMLHttpRequest', + 'Referer': OA_BASE + '/sys/portal/page.jsp', +} +JSON_HEADERS = { + 'User-Agent': UA, + 'X-Requested-With': 'XMLHttpRequest', + 'Content-Type': 'text/json', +} + +TIMEOUT = 20 +RETRY_MAX = 3 # 项目规范:全局重试 3 次 +RETRY_SLEEP = 1.5 + +# 会话失效判定关键字(业务权限报错不算失效) +_SESSION_DEAD = ('会话信息已丢失', '请重新登录', 'Unexpectable request', '401 Forbidden') + + +# ================== 通用 ================== +def _set_login_state(value): + """写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。""" + try: + glv['login_state'] = value + print(f"已写入影刀全局变量 login_state={value}") + except Exception as e: + print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}") + + +def _ensure_dir(path): + if path: + os.makedirs(path, exist_ok=True) + + +def _utc_ts(): + """K3Cloud 客户端时间戳格式:2026-11-13T10:53:00.000Z""" + return datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.') + '000Z' + + +def _client_info(entry_url, custom_args): + """K3Cloud HTML5 客户端信息(服务端只做基础校验,值可固定)。""" + return { + 'ipAddress': 'mozila', 'macAddress': 'browser', 'hostName': 'mozila', + 'IsDefaultInfo': True, + 'IpAddress': 'mozila', 'MacAddress': 'browser', 'HostName': 'mozila', + 'OperationSystem': '', + 'BrowserType': 'win|chrome|157.0.0.0', 'Version': 'HTML5', 'ClientType': 16, + 'vH': 0, 'vW': 764, + 'AvailableAreaSize': {'Height': 595, 'Width': 764}, + 'ScreenSize': {'Height': 600, 'Width': 800}, + 'EntryPageUrl': entry_url, + 'customArgs': custom_args, + } + + +# ================== Cookies 持久化(结构对齐 oa/hr 登录模块) ================== +def _load_cookies(path): + """读取 cookies 文件 → requests 可用的 [{name, value, domain, path}]。""" + if not path or not os.path.exists(path): + return [] + try: + with open(path, 'r', encoding='utf-8') as f: + data = json.load(f) + return data if isinstance(data, list) else [] + except Exception as e: + print(f"读取 cookies 失败({path}):{e}") + return [] + + +def _save_cookies(session, path): + """requests.Session → [{name, value, domain, path, expires}, ...],与其他登录模块结构兼容。""" + cookies = [] + for c in session.cookies: + cookies.append({ + 'name': c.name, + 'value': c.value, + 'domain': c.domain or '', + 'path': c.path or '/', + 'expires': c.expires, + }) + _ensure_dir(os.path.dirname(os.path.abspath(path))) + with open(path, 'w', encoding='utf-8') as f: + json.dump(cookies, f, ensure_ascii=False, indent=2) + print(f"已保存 {len(cookies)} 个 ERP cookies → {path}") + return cookies + + +def _session_from_cookies(cookies): + """把 cookies 列表灌进 requests.Session。""" + s = requests.Session() + for c in cookies or []: + try: + s.cookies.set(c.get('name'), c.get('value'), + domain=c.get('domain') or None, + path=c.get('path') or '/') + except Exception: + pass + return s + + +# ================== OA 登录态校验 ================== +def _oa_cookies_valid(cookies): + """OA 会话是否有效:sumTodoCount 返回 JSON 即有效(被重定向回登录页会返回 HTML)。""" + if not cookies: + print("未找到 OA 登录态(oa_cookies.json 缺失或为空),请先运行「37duOA登录」指令") + return False + s = _session_from_cookies(cookies) + for delay in (0, 0.8, 2.0): # OA 网关偶发 468 风控,退避重试 + if delay: + time.sleep(delay) + try: + r = s.get(OA_VALIDATE_URL, headers=XHR_HEADERS, timeout=TIMEOUT) + txt = (r.text or '').strip() + if r.status_code == 200 and txt.startswith(('{', '[')): + print("OA 登录态有效") + return True + print(f"OA 会话校验未通过(HTTP {r.status_code}),稍后重试...") + except Exception as e: + print(f"OA 会话校验异常:{e}") + print("OA 登录态已失效,请先运行「37duOA登录」指令更新 oa_cookies.json") + return False + + +# ================== SSO 握手 ================== +def _get_sso_entry(app): + """第 2 步:向 OA 要 ERP 入口地址(302 Location 内含 OA 令牌)。""" + app_name = ERP_SITES[app][1] + url = SSO_URL_TPL.format(app=app_name) + oa_cookies = _load_cookies(OA_COOKIE_FILE) + if not _oa_cookies_valid(oa_cookies): + return None, None + s = _session_from_cookies(oa_cookies) + r = s.get(url, headers=XHR_HEADERS, timeout=TIMEOUT, allow_redirects=False) + loc = r.headers.get('Location') or '' + if r.status_code not in (301, 302, 303, 307, 308) or not loc: + print(f"SSO 未返回跳转地址(HTTP {r.status_code}),可能 OA 侧 ERP 入口配置有变") + return None, None + print(f"已取得 ERP SSO 入口(appName={app_name})") + return s, loc + + +def _exchange_session(erp_session, entry_url, host): + """ + 第 3~4 步:跟随到中转页取 ud,再用 Verify 换 kdservice-sessionid。 + 返回 (ok, message)。 + """ + resp = erp_session.get(entry_url, headers={'User-Agent': UA}, + timeout=TIMEOUT, allow_redirects=True) + final_url = str(resp.url) + if 'lightstartapp.aspx' not in final_url.lower(): + return False, f"中转页异常(未落到 lightstartapp.aspx):{final_url[:150]}", None + if host not in final_url: + # OA 侧入口指错了站点时会落到别的域,Verify 必然失败,这里先给出明确提示 + print(f"⚠ SSO 落点与预期站点不一致:期望 {host},实际 {final_url.split('/')[2]}") + ud = urllib.parse.parse_qs(urllib.parse.urlparse(final_url).query).get('ud', [''])[0] + if not ud: + return False, "中转页 URL 中缺少 ud 参数", None + username = None + try: + pad = ud + '=' * (-len(ud) % 4) + payload = json.loads(base64.b64decode(pad).decode('utf-8')) + username = payload.get('username') + print(f"SSO 身份:{username} 账套:{payload.get('dbid')}") + except Exception: + print("ud 解析失败(不影响后续握手)") + + base = f'https://{host}' + ci = json.dumps(_client_info(final_url, ud), separators=(',', ':')) + body = { + 'ap0': ci, + 'customArgs': ud, + 'clientinfo': ci, + 'forminfo': {'scope': 'BODY_'}, + 'nonce': '', + 'v': '1.0', + 'format': '1', + 'sign': '', + 'timestamp': _utc_ts(), + 'compressed': False, + 'compressedapx': False, + 'useragent': 'KD.HTML5.GZIP', + } + headers = dict(JSON_HEADERS) + headers['Referer'] = final_url + r = erp_session.post(base + VERIFY_SVC, json=body, headers=headers, timeout=TIMEOUT) + if r.status_code != 200: + return False, f"Verify 握手失败:HTTP {r.status_code}", None + try: + j = r.json() + except Exception: + return False, f"Verify 返回非 JSON:{r.text[:150]}", None + result_type = j.get('ResultType') + if result_type != 1: + return False, f"Verify 未通过:{j.get('Message') or j.get('MessageCode') or result_type}", None + if 'kdservice-sessionid' not in erp_session.cookies.get_dict(): + return False, "Verify 通过但未下发 kdservice-sessionid", None + print("SSO 握手完成,已取得 kdservice-sessionid") + return True, 'SSO 登录成功', username + + +def _erp_session_valid(session, host): + """业务查询探活:返回 JSON 且不含会话失效关键字即视为有效(权限报错同样算有效)。""" + url = f'https://{host}' + QUERY_SVC + body = {'parameters': [{'FormId': 'BD_MATERIAL', 'FieldKeys': 'FNumber', + 'FilterString': '', 'OrderString': '', + 'TopRowCount': 1, 'StartRow': 0, 'Limit': 0}]} + try: + r = session.post(url, json=body, timeout=TIMEOUT) + except Exception as e: + print(f"ERP 会话探活异常:{e}") + return False + txt = (r.text or '').strip() + if r.status_code != 200: + print(f"ERP 会话探活 HTTP {r.status_code}") + return False + if any(k in txt for k in _SESSION_DEAD): + return False + return txt.startswith(('[', '{')) + + +def _cookie_file(app): + """按站点取 cookies 落盘路径(新旧版登录态互不覆盖)。""" + return ERP_COOKIE_FILE_OLD if app == 'old' else ERP_COOKIE_FILE + + +def _saved_session(app): + """用已落盘的 cookies 建会话(不做校验)。""" + host = ERP_SITES[app][0] + path = _cookie_file(app) + cookies = [c for c in _load_cookies(path) + if host in (c.get('domain') or '')] or _load_cookies(path) + return _session_from_cookies(cookies) + + +def _meta_file(app): + """按站点取会话摘要路径。""" + return ERP_META_FILE_OLD if app == 'old' else ERP_META_FILE + + +def _save_meta(app, host, identity): + """会话摘要(与其它平台 *_session_meta.json 同风格):记录 SSO 身份,便于日志与排查。""" + meta = {'app': app, 'host': host, 'identity': identity, + 'saved_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} + try: + with open(_meta_file(app), 'w', encoding='utf-8') as f: + json.dump(meta, f, ensure_ascii=False, indent=2) + except Exception as e: + print(f"写入会话摘要失败(忽略):{e}") + + +def _load_identity(app): + """从会话摘要里读上次 SSO 的登录人(读不到返回 None)。""" + try: + with open(_meta_file(app), 'r', encoding='utf-8') as f: + return (json.load(f) or {}).get('identity') + except Exception: + return None + + +# ================== 主入口 ================== +def ensure_login(app='new', force=False): + """ + 确保存在有效的 ERP 登录态(纯接口 SSO),必要时重新握手并落盘。 + + 参数: + app 'new'=新版 criterion.erp.37du.co / 'old'=旧版 erp.37du.co + force True 强制重新握手(忽略缓存) + 返回: + {success, cookie_path, message, relogin, identity} + """ + _set_login_state(False) + if app not in ERP_SITES: + return {'success': False, 'cookie_path': ERP_COOKIE_FILE, + 'message': f"无效的 app 参数:{app}(可选 'new' / 'old')", + 'relogin': False, 'identity': None} + host = ERP_SITES[app][0] + cookie_path = _cookie_file(app) + + # 优先复用已保存的 ERP 会话 + if not force: + sess = _saved_session(app) + if _erp_session_valid(sess, host): + print("已通过缓存的 Cookies 复用 ERP 登录态") + _set_login_state(True) + return {'success': True, 'cookie_path': cookie_path, + 'message': '复用缓存登录态', 'relogin': False, + 'identity': _load_identity(app)} + + last_msg = '' + for attempt in range(1, RETRY_MAX + 1): + print(f"--- 第 {attempt}/{RETRY_MAX} 轮 ERP SSO 登录 ---") + try: + oa_sess, entry = _get_sso_entry(app) + if not entry: + last_msg = '未取得 SSO 入口(OA 登录态失效或 OA 侧入口变更)' + time.sleep(RETRY_SLEEP) + continue + erp_sess = requests.Session() + ok, msg, identity = _exchange_session(erp_sess, entry, host) + if not ok: + last_msg = msg + time.sleep(RETRY_SLEEP) + continue + if not _erp_session_valid(erp_sess, host): + last_msg = 'SSO 完成但业务接口校验未通过' + time.sleep(RETRY_SLEEP) + continue + _save_cookies(erp_sess, cookie_path) + _save_meta(app, host, identity) + _set_login_state(True) + return {'success': True, 'cookie_path': cookie_path, + 'message': 'SSO 登录成功', 'relogin': True, 'identity': identity} + except Exception as e: + last_msg = f'SSO 过程异常:{e}' + print(last_msg) + time.sleep(RETRY_SLEEP) + + return {'success': False, 'cookie_path': cookie_path, + 'message': last_msg or 'ERP SSO 登录失败(重试耗尽)', + 'relogin': False, 'identity': None} + + +def build_session(app='new', force=False): + """ + 业务脚本入口:返回可直接调用 ERP WebAPI 的 requests.Session。 + 登录态有效则复用 erp_cookies.json,失效自动重新 SSO 登录。 + """ + result = ensure_login(app=app, force=force) + if not result.get('success'): + print(f"ERP 会话不可用:{result.get('message')}") + return _saved_session(app) + + +# ================== 影刀自定义指令入口 ================== +def main(app='new', force=True): + """ + 影刀自定义指令调用入口。 + app: 'new' / 'old',用于选择新版或旧版 ERP + force: bool 是否强制重新握手(默认 True,便于本地独立运行直接刷新登录态) + 返回: dict {success, cookie_path, message, relogin, identity} + """ + try: + return ensure_login(app=app, force=force) + except Exception as e: + return {'success': False, 'cookie_path': ERP_COOKIE_FILE, + 'message': f'登录过程异常:{e}', 'relogin': False, 'identity': None} + + +if __name__ == '__main__': + print("最终结果:", main(app='new', force=True))