windows_store_update.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. """Run a Store check, download, or install with the packaged interpreter.
  2. The desktop keeps the backend alive during download, then stops it before
  3. requesting installation. Each invocation reports one final JSON result.
  4. Exit 0 means success, 2 means a check found updates, and 1 means failure.
  5. Run with the bundled payload python: ``python -P -m hermes_cli.windows_store_update``.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. import json
  10. import os
  11. import site
  12. import sys
  13. import time
  14. def perform(context, mode, wait, completed_state) -> dict:
  15. """Use the same update objects for the query and the requested operation."""
  16. updates = wait(context.get_app_and_optional_store_package_updates_async())
  17. packages = [update.package.id.full_name for update in updates]
  18. result = {"available": bool(updates), "packages": packages, "ok": True}
  19. if mode == "check" or not updates:
  20. return result
  21. request = {
  22. "download": context.request_download_store_package_updates_async,
  23. "install": context.request_download_and_install_store_package_updates_async,
  24. }[mode]
  25. outcome = wait(request(updates))
  26. if outcome.overall_state != completed_state:
  27. result.update(ok=False, error=f"Microsoft Store {mode}: {outcome.overall_state.name}")
  28. return result
  29. def _wait(operation):
  30. """Keep the STA responsive while Store displays consent and progress UI."""
  31. import win32con
  32. import win32event
  33. import win32gui
  34. from winrt.windows.foundation import AsyncStatus
  35. deadline = time.monotonic() + 1800
  36. while operation.status == AsyncStatus.STARTED:
  37. if time.monotonic() >= deadline:
  38. operation.cancel()
  39. raise TimeoutError("Microsoft Store request timed out")
  40. win32event.MsgWaitForMultipleObjects((), False, 50, win32con.QS_ALLINPUT)
  41. if win32gui.PumpWaitingMessages():
  42. operation.cancel()
  43. raise RuntimeError("Microsoft Store request was interrupted")
  44. return operation.get_results()
  45. def _execute(mode: str, window_handle: int | None) -> dict:
  46. from winrt.runtime.interop import initialize_with_window
  47. from winrt.windows.services.store import StoreContext, StorePackageUpdateState
  48. import winrt.windows.applicationmodel
  49. import winrt.windows.foundation.collections
  50. if mode != "check" and not window_handle:
  51. raise ValueError("A desktop window is required for Microsoft Store consent")
  52. context = StoreContext.get_default()
  53. if window_handle:
  54. initialize_with_window(context, window_handle)
  55. return perform(context, mode, _wait, StorePackageUpdateState.COMPLETED)
  56. def main(argv=None) -> int:
  57. parser = argparse.ArgumentParser(description=__doc__)
  58. parser.add_argument("--mode", choices=("check", "download", "install"), default="check")
  59. parser.add_argument("--hwnd", type=int)
  60. args = parser.parse_args(argv)
  61. # The packaged interpreter receives its dependencies through PYTHONPATH.
  62. # Process their .pth files so pywin32 can find its extensions and DLLs.
  63. for directory in os.environ.get("PYTHONPATH", "").split(os.pathsep):
  64. if directory:
  65. site.addsitedir(directory)
  66. try:
  67. from winrt.runtime import ApartmentType, init_apartment, uninit_apartment
  68. init_apartment(ApartmentType.SINGLE_THREADED)
  69. except Exception as exc:
  70. print(json.dumps({"available": None, "ok": False, "error": str(exc)}), flush=True)
  71. return 1
  72. try:
  73. try:
  74. result = _execute(args.mode, args.hwnd)
  75. except Exception as exc:
  76. # Missing Store acquisition is not evidence that the app is current.
  77. result = {"available": None, "ok": False, "error": f"Microsoft Store request failed: {exc}"}
  78. finally:
  79. # _execute's COM objects must be released before apartment shutdown.
  80. uninit_apartment()
  81. print(json.dumps(result), flush=True)
  82. if not result["ok"]:
  83. return 1
  84. return 2 if args.mode == "check" and result["available"] else 0
  85. if __name__ == "__main__":
  86. sys.exit(main())