|
| 1 | +"""Open a file with its default app, or a URL in the default browser. |
| 2 | +
|
| 3 | +The framework can launch a literal executable (``start_exe`` / ``shell_process``), |
| 4 | +but not the single most common "hand off to another app" RPA step: open ``report.pdf`` |
| 5 | +with whatever app is registered for it, ``print`` a document, or open a URL in the |
| 6 | +default browser. ``shell_open`` adds that, routed per-OS to ``os.startfile`` / |
| 7 | +``open`` / ``xdg-open`` / ``webbrowser``. |
| 8 | +
|
| 9 | +:func:`plan_open` is a pure planner — it classifies the target (URL vs file path), |
| 10 | +validates it (URL scheme allowlist; ``realpath`` for files) and returns the |
| 11 | +dispatch descriptor, fully unit-testable. :func:`open_path` runs the plan through |
| 12 | +an injectable ``opener`` sink (the real OS call by default), so the dispatch logic |
| 13 | +is testable without launching anything. Imports no ``PySide6``. |
| 14 | +""" |
| 15 | +import os |
| 16 | +import re |
| 17 | +import sys |
| 18 | +from typing import Any, Callable, Dict, Optional |
| 19 | + |
| 20 | +# URL schemes we will hand to the browser / OS — the safety allowlist. |
| 21 | +_URL_SCHEMES = frozenset({"http", "https", "ftp", "file", "mailto", "tel"}) |
| 22 | +_SCHEME_AUTHORITY = re.compile(r"([a-zA-Z][a-zA-Z0-9+.\-]+)://") |
| 23 | +_SCHEME_OPAQUE = re.compile(r"(mailto|tel):", re.IGNORECASE) |
| 24 | + |
| 25 | +# A plan dispatcher: maps a plan dict to the real open call → bool. |
| 26 | +Opener = Callable[[Dict[str, Any]], bool] |
| 27 | + |
| 28 | + |
| 29 | +def _scheme(target: str) -> Optional[str]: |
| 30 | + """Return the URL scheme of ``target`` (e.g. ``https``), or None for a path. |
| 31 | +
|
| 32 | + Requires ``scheme://`` (so a Windows drive ``C:\\`` is not a scheme) or a known |
| 33 | + opaque scheme (``mailto:`` / ``tel:``). |
| 34 | + """ |
| 35 | + match = _SCHEME_AUTHORITY.match(target) or _SCHEME_OPAQUE.match(target) |
| 36 | + return match.group(1).lower() if match else None |
| 37 | + |
| 38 | + |
| 39 | +def _file_backend() -> str: |
| 40 | + if sys.platform.startswith("win"): |
| 41 | + return "startfile" |
| 42 | + if sys.platform == "darwin": |
| 43 | + return "open" |
| 44 | + return "xdg-open" |
| 45 | + |
| 46 | + |
| 47 | +def plan_open(target: str, *, verb: str = "open") -> Dict[str, Any]: |
| 48 | + """Classify ``target`` and return how to open it (pure, no side effect). |
| 49 | +
|
| 50 | + Returns ``{kind, target, backend, verb}`` (plus ``scheme`` for URLs). Raises |
| 51 | + ``ValueError`` for an empty target or a URL whose scheme isn't allow-listed. |
| 52 | + """ |
| 53 | + text = str(target).strip() |
| 54 | + if not text: |
| 55 | + raise ValueError("target is empty") |
| 56 | + scheme = _scheme(text) |
| 57 | + if scheme is not None: |
| 58 | + if scheme not in _URL_SCHEMES: |
| 59 | + raise ValueError(f"unsupported URL scheme: {scheme!r}") |
| 60 | + return {"kind": "url", "scheme": scheme, "target": text, |
| 61 | + "backend": "webbrowser", "verb": verb} |
| 62 | + path = os.path.realpath(os.path.expanduser(text)) |
| 63 | + return {"kind": "file", "target": path, "backend": _file_backend(), |
| 64 | + "verb": verb} |
| 65 | + |
| 66 | + |
| 67 | +def _default_opener(plan: Dict[str, Any]) -> bool: |
| 68 | + backend, target = plan["backend"], plan["target"] |
| 69 | + if backend == "webbrowser": |
| 70 | + import webbrowser |
| 71 | + return bool(webbrowser.open(target)) |
| 72 | + if backend == "startfile": |
| 73 | + if not sys.platform.startswith("win"): |
| 74 | + raise RuntimeError("startfile is only supported on Windows") |
| 75 | + # noqa: S606 / nosec B606 — verb is from the allow-listed plan, no shell |
| 76 | + os.startfile(target, plan.get("verb") or "open") # noqa: S606 # nosec B606 |
| 77 | + return True |
| 78 | + import subprocess # nosec B404 # reason: argv list, no shell |
| 79 | + subprocess.Popen([backend, target]) # nosec B603 # reason: fixed backend + argv, no shell |
| 80 | + return True |
| 81 | + |
| 82 | + |
| 83 | +def open_path(target: str, *, verb: str = "open", |
| 84 | + opener: Optional[Opener] = None) -> bool: |
| 85 | + """Open ``target`` (file → default app / verb; URL → default browser). |
| 86 | +
|
| 87 | + Pass an ``opener`` ``plan -> bool`` to intercept the dispatch (e.g. in tests); |
| 88 | + the default runs the real OS call. Returns True on success. |
| 89 | + """ |
| 90 | + plan = plan_open(target, verb=verb) |
| 91 | + dispatch = opener if opener is not None else _default_opener |
| 92 | + return bool(dispatch(plan)) |
0 commit comments