slicer_cert_installer.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """Scripts that add the virtual-printer CA to the slicers' printer.cer.
  2. Bambu Studio and OrcaSlicer trust only the certificates in their own
  3. ``printer.cer``, and every slicer update or reinstall puts the stock file
  4. back. Settings -> Virtual Printer offers these scripts for download with this
  5. instance's CA written into them, so they need no API key and no connection to
  6. Bambuddy: one for Windows (a ``.cmd`` that elevates itself and installs a task
  7. that re-checks after updates) and one for Linux and macOS.
  8. """
  9. from dataclasses import dataclass
  10. from pathlib import Path
  11. _TEMPLATES = Path(__file__).resolve().parents[2] / "data" / "slicer_cert"
  12. # platform -> template file, which is also the download's file name.
  13. _PLATFORMS = {
  14. "windows": "bambuddy-slicer-cert.cmd",
  15. "unix": "bambuddy-slicer-cert.sh",
  16. }
  17. INSTALLER_PLATFORMS = tuple(_PLATFORMS)
  18. @dataclass(frozen=True)
  19. class SlicerCertInstaller:
  20. filename: str
  21. content: str
  22. def build_slicer_cert_installer(platform: str, pem: str, fingerprint: str) -> SlicerCertInstaller:
  23. """Return the script for ``platform`` with the CA in ``pem`` written into it.
  24. Raises ``KeyError`` for an unknown platform.
  25. """
  26. filename = _PLATFORMS[platform]
  27. template = (_TEMPLATES / filename).read_text(encoding="utf-8")
  28. content = template.replace("__BAMBUDDY_CA_PEM__", pem.strip()).replace("__BAMBUDDY_CA_FINGERPRINT__", fingerprint)
  29. if filename.endswith(".cmd"):
  30. # cmd.exe misreads a batch file with bare LF line ends.
  31. content = content.replace("\r\n", "\n").replace("\n", "\r\n")
  32. return SlicerCertInstaller(filename=filename, content=content)