mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-02 20:20:35 -05:00
Exercise PdfCraft web print permissions and cancellation on Chromium
This commit is contained in:
1 parent
33dcc3fc01
commit
bdd278c04c
2 files changed
+252
No files matched your search
@@ -0,0 +1,193 @@
|
||||
"""Verify the built PdfCraft web app through Chromium's real print preview and PDF output."""
|
||||
import functools
|
||||
import http.server
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
from PIL import Image, ImageGrab
|
||||
from reportlab.pdfgen import canvas
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
|
||||
|
||||
SITE = Path("qa-site").resolve()
|
||||
RESULTS = Path("browser-capture").resolve()
|
||||
RED = (220, 40, 50)
|
||||
BLUE = (25, 55, 215)
|
||||
|
||||
|
||||
def fixture():
|
||||
source = SITE / "source.pdf"
|
||||
pdf = canvas.Canvas(str(source), pagesize=(612, 792))
|
||||
for color in ((65, 65, 65), RED, BLUE):
|
||||
pdf.setFillColorRGB(*(channel / 255 for channel in color))
|
||||
pdf.rect(165, 250, 282, 292, fill=1, stroke=0)
|
||||
pdf.showPage()
|
||||
pdf.save()
|
||||
for mode in ("low", "none"):
|
||||
subprocess.run(["qpdf", "--encrypt", "", "qa-fixture-owner", "256", f"--print={mode}", "--",
|
||||
source, SITE / f"{mode}.pdf"], check=True)
|
||||
(RESULTS / f"{mode}-permissions.txt").write_text(
|
||||
subprocess.check_output(["qpdf", "--show-encryption", SITE / f"{mode}.pdf"], text=True))
|
||||
|
||||
|
||||
def command(driver, method, params=None):
|
||||
return driver.execute_async_script("""
|
||||
const [method, params, receive] = arguments;
|
||||
window.pdfcraft.request(method, params).then(receive, error => receive({ok:false, error:String(error)}));
|
||||
""", method, params or {})
|
||||
|
||||
|
||||
def result(driver, method, params=None):
|
||||
reply = command(driver, method, params)
|
||||
assert reply.get("ok"), (method, reply)
|
||||
return reply.get("result")
|
||||
|
||||
|
||||
def open_app(driver, url, mode):
|
||||
driver.get(f"{url}/?control&file=/{mode}.pdf")
|
||||
wait = WebDriverWait(driver, 90)
|
||||
wait.until(lambda browser: browser.execute_script("return typeof window.pdfcraft?.request === 'function'"))
|
||||
wait.until(lambda browser: result(browser, "ui.state").get("active"))
|
||||
(RESULTS / f"{mode}-state.json").write_text(json.dumps(result(driver, "ui.state"), indent=2))
|
||||
|
||||
|
||||
def choose_print(driver, selected=None):
|
||||
if selected is not None:
|
||||
result(driver, "ui.set", {"key": "select", "value": str(selected)})
|
||||
active = result(driver, "ui.state")["active"]
|
||||
assert active["selected_pages"] == [selected], active
|
||||
result(driver, "ui.command", {"id": "print.dialog"})
|
||||
tree = result(driver, "ui.inspect", {"query": "Print", "limit": 50})
|
||||
(RESULTS / f"dialog-{selected or 'denied'}.json").write_text(json.dumps(tree, indent=2))
|
||||
return command(driver, "ui.dialog.confirm", {"dialog": "top"})
|
||||
|
||||
|
||||
def preview(name, color, visible):
|
||||
deadline = time.monotonic() + 55
|
||||
while True:
|
||||
screenshot = ImageGrab.grab().convert("RGB")
|
||||
count = sum(max(abs(a - b) for a, b in zip(pixel, color)) < 18
|
||||
for pixel in screenshot.resize((320, 240)).getdata())
|
||||
if (count > 300) == visible:
|
||||
screenshot.save(RESULTS / f"{name}.png")
|
||||
print(f"{name}: {count} matching pixels", flush=True)
|
||||
return
|
||||
if time.monotonic() > deadline:
|
||||
screenshot.save(RESULTS / f"{name}-timeout.png")
|
||||
raise TimeoutError(f"{name}: {count} matching pixels")
|
||||
time.sleep(0.35)
|
||||
|
||||
|
||||
def key(name):
|
||||
subprocess.run(["xdotool", "key", name], check=True)
|
||||
|
||||
|
||||
def pdf_files():
|
||||
return set(RESULTS.glob("*.pdf"))
|
||||
|
||||
|
||||
def save_pdf():
|
||||
key("Return")
|
||||
picker = False
|
||||
deadline = time.monotonic() + 55
|
||||
while time.monotonic() < deadline:
|
||||
files = pdf_files()
|
||||
assert len(files) <= 1, files
|
||||
if files:
|
||||
path, = files
|
||||
if path.read_bytes().rstrip().endswith(b"%%EOF"):
|
||||
return path.rename(RESULTS / "retry-captured.pdf")
|
||||
if not picker:
|
||||
title = subprocess.check_output(["xdotool", "getwindowfocus", "getwindowname"], text=True)
|
||||
image = io.BytesIO()
|
||||
ImageGrab.grab().save(image, format="PNG")
|
||||
words = subprocess.check_output(["tesseract", "stdin", "stdout", "--psm", "6"], input=image.getvalue()).decode()
|
||||
if "save" in title.lower() or ("Name:" in words and "Save" in words):
|
||||
picker = True
|
||||
key("ctrl+l")
|
||||
subprocess.run(["xdotool", "type", "--clearmodifiers", str(RESULTS / "retry.pdf")], check=True)
|
||||
key("Return")
|
||||
time.sleep(0.3)
|
||||
raise TimeoutError("no complete retry PDF")
|
||||
|
||||
|
||||
def verify_pdf(path):
|
||||
info = subprocess.check_output(["pdfinfo", path], text=True)
|
||||
(RESULTS / "retry.pdfinfo").write_text(info)
|
||||
assert next(int(line.split()[1]) for line in info.splitlines() if line.startswith("Pages:")) == 1, info
|
||||
prefix = RESULTS / "retry-page"
|
||||
subprocess.run(["pdftoppm", "-r", "36", "-singlefile", "-png", path, prefix], check=True)
|
||||
with Image.open(prefix.with_suffix(".png")) as image:
|
||||
actual = image.convert("RGB").getpixel((image.width // 2, image.height // 2))
|
||||
assert max(abs(a - b) for a, b in zip(actual, BLUE)) < 20, actual
|
||||
print(f"One selected sheet rendered at center RGB {actual}", flush=True)
|
||||
|
||||
|
||||
def denied_print(driver):
|
||||
opened = command(driver, "ui.command", {"id": "print.dialog"})
|
||||
if opened.get("ok"):
|
||||
command(driver, "ui.dialog.confirm", {"dialog": "top"})
|
||||
tree = result(driver, "ui.inspect", {"limit": 350})
|
||||
(RESULTS / "denied-dialog.json").write_text(json.dumps(tree, indent=2))
|
||||
message = json.dumps([opened, tree]).lower()
|
||||
assert ("not permitted" in message or "doesn't allow" in message
|
||||
or "does not allow" in message or "not allowed" in message), message
|
||||
assert not driver.execute_script("return !!document.querySelector('iframe[srcdoc]')")
|
||||
assert len(pdf_files()) == 1
|
||||
ImageGrab.grab().save(RESULTS / "print-denied.png")
|
||||
|
||||
|
||||
def main():
|
||||
RESULTS.mkdir()
|
||||
fixture()
|
||||
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=SITE)
|
||||
os.environ["CUPS_SERVER"] = str(RESULTS / "absent-cups.sock")
|
||||
options = webdriver.ChromeOptions()
|
||||
for argument in ("--no-first-run", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader",
|
||||
"--window-position=0,0", "--window-size=1440,1070", "--lang=en-US"):
|
||||
options.add_argument(argument)
|
||||
options.add_experimental_option("prefs", {
|
||||
"download.default_directory": str(RESULTS),
|
||||
"savefile.default_directory": str(RESULTS),
|
||||
"printing.print_preview_sticky_settings.appState": json.dumps({
|
||||
"version": 2, "recentDestinations": [{"id": "Save as PDF", "origin": "local"}],
|
||||
"selectedDestinationId": "Save as PDF",
|
||||
}),
|
||||
})
|
||||
options.set_capability("goog:loggingPrefs", {"browser": "ALL"})
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) as server:
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
url = f"http://127.0.0.1:{server.server_port}"
|
||||
with webdriver.Chrome(options=options, service=Service(shutil.which("chromedriver"))) as driver:
|
||||
print("Chrome", driver.capabilities["browserVersion"], flush=True)
|
||||
try:
|
||||
open_app(driver, url, "low")
|
||||
answer = choose_print(driver, 2)
|
||||
assert answer.get("ok"), answer
|
||||
preview("selected-red", RED, True)
|
||||
key("Escape")
|
||||
preview("cancelled-red", RED, False)
|
||||
assert not pdf_files()
|
||||
WebDriverWait(driver, 20).until(
|
||||
lambda browser: not browser.execute_script("return !!document.querySelector('iframe[srcdoc]')"))
|
||||
answer = choose_print(driver, 3)
|
||||
assert answer.get("ok"), answer
|
||||
preview("retry-blue", BLUE, True)
|
||||
verify_pdf(save_pdf())
|
||||
open_app(driver, url, "none")
|
||||
denied_print(driver)
|
||||
finally:
|
||||
ImageGrab.grab().save(RESULTS / "last-screen.png")
|
||||
(RESULTS / "browser-log.json").write_text(json.dumps(driver.get_log("browser"), indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,59 @@
|
||||
name: PdfCraft browser print output
|
||||
on:
|
||||
push:
|
||||
branches: [verify/pdfcraft-web-print-4859]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
print:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
CARGO_PROFILE_DEV_DEBUG: '0'
|
||||
CARGO_INCREMENTAL: '0'
|
||||
VERIFY_FRAMEWORK: e230bc3f3154d0075e76e6fb43c76f8966f4d5b1
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
|
||||
with:
|
||||
packages: xvfb xauth xdotool tesseract-ocr poppler-utils qpdf python3-selenium python3-reportlab python3-pil
|
||||
- name: Build PdfCraft's web entry point with its baseline plus the shared HTML handoff
|
||||
run: |
|
||||
set -euo pipefail
|
||||
old=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8
|
||||
git grep -lz -F "$old" -- Cargo.toml Cargo.lock ':(glob)**/Cargo.toml' | xargs -0 sed -i "s/$old/$VERIFY_FRAMEWORK/g"
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
lock = Path("Cargo.lock")
|
||||
s = lock.read_text()
|
||||
start = s.index('name = "craft-print"\n')
|
||||
end = s.index('[[package]]', start)
|
||||
block = s[start:end]
|
||||
assert '"wasm-bindgen-futures"' not in block
|
||||
lock.write_text(s[:start] + block.replace(' "wasm-bindgen",\n', ' "wasm-bindgen",\n "wasm-bindgen-futures",\n') + s[end:])
|
||||
PY
|
||||
rustup target add wasm32-unknown-unknown
|
||||
cargo build --locked --target wasm32-unknown-unknown -p pdfcraft-web --config 'profile.dev.package."*".opt-level=1'
|
||||
archive="$RUNNER_TEMP/wasm-bindgen.tar.gz"
|
||||
curl --fail --location --silent --show-error https://github.com/wasm-bindgen/wasm-bindgen/releases/download/0.2.129/wasm-bindgen-0.2.129-x86_64-unknown-linux-musl.tar.gz -o "$archive"
|
||||
echo "82d12bb940e2d4e72e0d5605387fc1b8ca179044e012b620f0ce4e7440e8320e $archive" | sha256sum --check
|
||||
tar -xf "$archive" -C "$RUNNER_TEMP" wasm-bindgen-0.2.129-x86_64-unknown-linux-musl/wasm-bindgen
|
||||
mkdir qa-site
|
||||
"$RUNNER_TEMP/wasm-bindgen-0.2.129-x86_64-unknown-linux-musl/wasm-bindgen" --target web --out-name pdfcraft --out-dir qa-site target/wasm32-unknown-unknown/debug/pdfcraft-web.wasm
|
||||
sed '/data-trunk/d; s|</body>|<script type="module">import init from "./pdfcraft.js"; init();</script></body>|' apps/pdfcraft-web/index.html >qa-site/index.html
|
||||
- name: Exercise selected low-resolution pages and a denied print through the app
|
||||
run: |
|
||||
set -euo pipefail
|
||||
xvfb-run -a -s '-screen 0 1440x1100x24' /usr/bin/python3 .github/qa/verify-web-print.py
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
|
||||
if: always()
|
||||
with:
|
||||
name: pdfcraft-browser-print-output
|
||||
path: browser-capture/
|
||||
if-no-files-found: warn
|
||||
Reference in new issue
Block a user