wps_plugin_contorl.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import base64
  2. import json
  3. import os
  4. import subprocess
  5. import winreg
  6. from typing import Optional, Literal
  7. import pythoncom
  8. import win32com
  9. from win32com.client import Dispatch
  10. from tools.logger_handle import logger
  11. WPSComponent = Literal['wps', 'et', 'wpp'] # wps=文字, et=表格, wpp=演示
  12. def get_wps_exe_path(component: WPSComponent = 'wps') -> Optional[str]:
  13. """
  14. 获取 WPS 各组件的 exe 路径
  15. :param component: 'wps' 文字, 'et' 表格, 'wpp' 演示
  16. :return: 组件的绝对路径,未找到则返回 None
  17. """
  18. # 组件对应的可执行文件名
  19. exe_map = {
  20. 'wps': 'wps.exe',
  21. 'et': 'et.exe',
  22. 'wpp': 'wpp.exe'
  23. }
  24. exe_name = exe_map.get(component)
  25. if not exe_name:
  26. return None
  27. # WPS 在注册表中的可能路径(与之前相同)
  28. wps_reg_paths = [
  29. (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Kingsoft\Office\6.0\common"),
  30. (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Kingsoft\Office\6.0\common"),
  31. (winreg.HKEY_CURRENT_USER, r"SOFTWARE\Kingsoft\Office\6.0\common")
  32. ]
  33. for hkey, subkey in wps_reg_paths:
  34. try:
  35. key = winreg.OpenKey(hkey, subkey, 0, winreg.KEY_READ)
  36. install_root, _ = winreg.QueryValueEx(key, "InstallRoot")
  37. winreg.CloseKey(key)
  38. # 拼接 office6 目录下的组件 exe
  39. component_path = os.path.join(install_root, "office6", exe_name)
  40. if os.path.isfile(component_path):
  41. return component_path
  42. except (FileNotFoundError, OSError, WindowsError):
  43. continue
  44. return None
  45. def get_ms_office_exe_path(application: str) -> Optional[str]:
  46. """
  47. 获取 Microsoft Office 组件路径
  48. :param application: 'Word', 'Excel', 'PowerPoint'
  49. """
  50. app_map = {'Word': 'WINWORD.EXE', 'Excel': 'EXCEL.EXE', 'PowerPoint': 'POWERPNT.EXE'}
  51. exe_name = app_map.get(application)
  52. if not exe_name:
  53. return None
  54. # 遍历常见的 Office 版本号
  55. office_versions = ['16.0', '15.0', '14.0', '12.0']
  56. for version in office_versions:
  57. reg_path = rf"SOFTWARE\Microsoft\Office\{version}\{application}\InstallRoot"
  58. for hkey in [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER]:
  59. try:
  60. key = winreg.OpenKey(hkey, reg_path, 0, winreg.KEY_READ)
  61. install_path, _ = winreg.QueryValueEx(key, "Path")
  62. winreg.CloseKey(key)
  63. exe_path = os.path.join(install_path, exe_name)
  64. if os.path.isfile(exe_path):
  65. return exe_path
  66. except (FileNotFoundError, OSError, WindowsError):
  67. continue
  68. return None
  69. def find_wps_via_registry():
  70. """通过Windows注册表查找WPS的安装路径"""
  71. possible_paths = [
  72. (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Kingsoft\Office\6.0\common"),
  73. (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Kingsoft\Office\6.0\common"),
  74. (winreg.HKEY_CURRENT_USER, r"SOFTWARE\Kingsoft\Office\6.0\common")
  75. ]
  76. for hkey, subkey in possible_paths:
  77. try:
  78. key = winreg.OpenKey(hkey, subkey, 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
  79. install_path, _ = winreg.QueryValueEx(key, "InstallRoot")
  80. winreg.CloseKey(key)
  81. # 尝试找到主要的可执行文件
  82. for exe in ["wps.exe", "WPSOffice.exe", "ksolaunch.exe"]:
  83. full_path = os.path.join(install_path, "office6", exe)
  84. if os.path.isfile(full_path):
  85. return full_path
  86. except FileNotFoundError:
  87. continue
  88. except Exception:
  89. continue
  90. return None
  91. def encode_payload(payload):
  92. payload['data'] = base64.b64encode(json.dumps(payload['data']).encode('utf-8')).decode('utf-8')
  93. return json.dumps(payload)
  94. def is_wps_available():
  95. """检测当前系统是否安装了可用的 WPS Office (COM 接口)"""
  96. progids_to_try = [
  97. 'KWPS.Application', # WPS Office 2019+ 常用
  98. 'WPS.Application', # 旧版本可能用
  99. 'Kingsoft.Application'
  100. ]
  101. for progid in progids_to_try:
  102. try:
  103. pythoncom.CoInitialize()
  104. app = win32com.client.Dispatch(progid)
  105. app.Quit()
  106. del app
  107. pythoncom.CoUninitialize()
  108. logger.info(f"检测到可用的 WPS: {progid}")
  109. return True
  110. except Exception:
  111. continue
  112. finally:
  113. try:
  114. pythoncom.CoUninitialize()
  115. except:
  116. pass
  117. logger.warning("未检测到可用的 WPS Office,请确认已安装并注册 COM 接口")
  118. return False
  119. if __name__ == '__main__':
  120. print(get_wps_exe_path('wps'))
  121. print(get_wps_exe_path('et'))
  122. print(get_wps_exe_path('wpp'))
  123. print(subprocess.Popen([get_wps_exe_path('wps'), r"C:\Users\Lenovo\Desktop\dify本地部署.txt"]))
  124. # payload = {'data': {"cmd": "enable", "name": "wpsPlugin", "url": "http://172.10.3.110:3000/", "addonType": "wps",
  125. # "online": "true"},
  126. # 'serverId': '524ef80e-7ccd-43af-9fcb-69f3b0269730'}
  127. #
  128. # payload['data'] = base64.b64encode(json.dumps(payload['data']).encode('utf-8')).decode('utf-8')
  129. #
  130. # print(payload)