Skillfarm / skills · skillfarm.ai / converted / pptx / scripts / office / helpers / __init__.py
| 1 | import os |
| 2 | import posixpath |
| 3 | import re |
| 4 | import stat |
| 5 | import tempfile |
| 6 | import urllib.parse |
| 7 | import zipfile |
| 8 | from pathlib import Path, PureWindowsPath |
| 9 | |
| 10 | OOXML_FAMILY = { |
| 11 | ".docx": "docx", |
| 12 | ".dotx": "docx", |
| 13 | ".pptx": "pptx", |
| 14 | ".potx": "pptx", |
| 15 | ".xlsx": "xlsx", |
| 16 | ".xltx": "xlsx", |
| 17 | } |
| 18 | |
| 19 | _SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.\-]*:") |
| 20 | |
| 21 | SLIDE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" |
| 22 | |
| 23 | |
| 24 | def one_line(text: str, limit: int) -> str: |
| 25 | return "".join(c if c.isprintable() else c.encode("unicode_escape").decode() for c in text)[:limit] |
| 26 | |
| 27 | |
| 28 | def names_another_root(name: str) -> bool: |
| 29 | return bool(PureWindowsPath(name).anchor) |
| 30 | |
| 31 | |
| 32 | def opc_target(target: str, source_part: str, target_mode: str = "") -> str | None: |
| 33 | if not target: |
| 34 | return None |
| 35 | if target_mode.lower() == "external": |
| 36 | return None |
| 37 | target = urllib.parse.unquote(target) |
| 38 | |
| 39 | if _SCHEME_RE.match(target): |
| 40 | return None |
| 41 | |
| 42 | if "\\" in target: |
| 43 | raise ValueError(f"relationship target is not a POSIX part name: {target!r}") |
| 44 | |
| 45 | if target.startswith("/"): |
| 46 | joined = target.lstrip("/") |
| 47 | else: |
| 48 | joined = posixpath.join(posixpath.dirname(source_part), target) |
| 49 | |
| 50 | parts: list[str] = [] |
| 51 | for segment in posixpath.normpath(joined).split("/"): |
| 52 | if segment in ("", "."): |
| 53 | continue |
| 54 | if segment == "..": |
| 55 | if not parts: |
| 56 | raise ValueError(f"relationship target escapes the package: {target!r}") |
| 57 | parts.pop() |
| 58 | else: |
| 59 | parts.append(segment) |
| 60 | |
| 61 | if not parts: |
| 62 | raise ValueError(f"relationship target resolves to nothing: {target!r}") |
| 63 | if names_another_root("/".join(parts)): |
| 64 | raise ValueError(f"relationship target is not a part name: {target!r}") |
| 65 | return "/".join(parts) |
| 66 | |
| 67 | |
| 68 | def rels_source_part(rels_file: Path, unpacked_dir: Path) -> str: |
| 69 | owner_dir = rels_file.parent.parent.relative_to(unpacked_dir) |
| 70 | part = posixpath.join(owner_dir.as_posix(), rels_file.name[: -len(".rels")]) |
| 71 | return part.removeprefix("./") |
| 72 | |
| 73 | |
| 74 | def part_text(data: bytes) -> str: |
| 75 | return data.decode("utf-8", "surrogateescape") |
| 76 | |
| 77 | |
| 78 | XML_SPACE = " \t\r\n" |
| 79 | |
| 80 | |
| 81 | def rendered_text(text: str, preserve: bool) -> str: |
| 82 | return text if preserve else text.strip(XML_SPACE) |
| 83 | |
| 84 | |
| 85 | def safe_extract(zf: zipfile.ZipFile, dest: Path) -> None: |
| 86 | dest = dest.resolve() |
| 87 | for m in zf.infolist(): |
| 88 | if stat.S_ISLNK(m.external_attr >> 16): |
| 89 | raise ValueError(f"symlink archive entry not allowed: {m.filename!r}") |
| 90 | if names_another_root(m.filename): |
| 91 | raise ValueError(f"unsafe archive entry: {m.filename!r}") |
| 92 | target = (dest / m.filename).resolve() |
| 93 | if not target.is_relative_to(dest): |
| 94 | raise ValueError(f"unsafe archive entry: {m.filename!r}") |
| 95 | zf.extract(m, dest) |
| 96 | |
| 97 | |
| 98 | def folder_entries(package: Path) -> list[str]: |
| 99 | with zipfile.ZipFile(package) as zf: |
| 100 | return [info.filename for info in zf.infolist() if info.is_dir()] |
| 101 | |
| 102 | |
| 103 | def rezip(src_dir: Path, out_path: Path) -> None: |
| 104 | files = sorted(p for p in src_dir.rglob("*") if p.is_file()) |
| 105 | ct = src_dir / "[Content_Types].xml" |
| 106 | fd, tmp_name = tempfile.mkstemp( |
| 107 | prefix=out_path.name + ".", suffix=".tmp", dir=out_path.parent |
| 108 | ) |
| 109 | tmp_out = Path(tmp_name) |
| 110 | try: |
| 111 | with os.fdopen(fd, "wb") as fh: |
| 112 | with zipfile.ZipFile(fh, "w", zipfile.ZIP_DEFLATED) as zf: |
| 113 | if ct.exists(): |
| 114 | zf.write(ct, ct.relative_to(src_dir), compress_type=zipfile.ZIP_STORED) |
| 115 | for f in files: |
| 116 | if f == ct: |
| 117 | continue |
| 118 | zf.write(f, f.relative_to(src_dir)) |
| 119 | if out_path.exists(): |
| 120 | mode = out_path.stat().st_mode & 0o777 |
| 121 | else: |
| 122 | umask = os.umask(0) |
| 123 | os.umask(umask) |
| 124 | mode = 0o666 & ~umask |
| 125 | os.chmod(tmp_out, mode) |
| 126 | os.replace(tmp_out, out_path) |
| 127 | finally: |
| 128 | if tmp_out.exists(): |
| 129 | tmp_out.unlink() |