plugin_updater.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import os
  2. import ast
  3. import py_compile
  4. import requests
  5. from typing import Dict, Any, List, Optional
  6. from vs_types import PluginMeta
  7. PLUGINS_DIR = "plugins"
  8. # 纯内存缓存,无需落盘
  9. _IN_MEMORY_PLUGIN_INFO: Dict[str, Dict[str, str]] = {}
  10. def _parse_version(v_str: str) -> tuple:
  11. """将版本字符串解析为数字元组进行比较,如 '1.2.3' -> (1, 2, 3)"""
  12. try:
  13. clean_v = str(v_str).strip().lstrip("v")
  14. return tuple(int(part) for part in clean_v.split(".") if part.isdigit())
  15. except Exception:
  16. return (0,)
  17. def is_newer_version(cloud_version: str, local_version: str) -> bool:
  18. """判断云端版本是否高于本地版本"""
  19. return _parse_version(cloud_version) > _parse_version(local_version)
  20. def _extract_plugin_meta_from_ast(filepath: str) -> Dict[str, str]:
  21. """
  22. 通过 AST 静态分析插件代码中的 IVSPlg 子类元数据(name, version, description),
  23. 避免直接 import 产生网络请求或浏览器启动等副作用。
  24. """
  25. info = {"version": "1.0.0", "name": "", "description": ""}
  26. try:
  27. with open(filepath, "r", encoding="utf-8") as f:
  28. tree = ast.parse(f.read(), filename=filepath)
  29. for node in tree.body:
  30. # 1. 检查模块级变量 (如 __version__ = "1.0.0")
  31. if isinstance(node, ast.Assign):
  32. for target in node.targets:
  33. if isinstance(target, ast.Name):
  34. if target.id == "__version__" and isinstance(node.value, ast.Constant):
  35. info["version"] = str(node.value.value)
  36. elif target.id == "__description__" and isinstance(node.value, ast.Constant):
  37. info["description"] = str(node.value.value)
  38. # 2. 检查类定义 (如 class TlsPlugin(IVSPlg): version = "1.0.0")
  39. elif isinstance(node, ast.ClassDef):
  40. for item in node.body:
  41. if isinstance(item, ast.Assign):
  42. for target in item.targets:
  43. if isinstance(target, ast.Name) and isinstance(item.value, ast.Constant):
  44. if target.id == "version":
  45. info["version"] = str(item.value.value)
  46. elif target.id == "name":
  47. info["name"] = str(item.value.value)
  48. elif target.id == "description":
  49. info["description"] = str(item.value.value)
  50. except Exception as e:
  51. print(f"[PluginUpdater] AST parse error for {filepath}: {e}")
  52. return info
  53. def scan_plugins(plugins_dir: str = PLUGINS_DIR) -> Dict[str, Dict[str, str]]:
  54. """
  55. 运行时动态扫描 plugins 目录,读取所有插件的基本元数据到内存中(不写文件)
  56. """
  57. global _IN_MEMORY_PLUGIN_INFO
  58. scanned_info: Dict[str, Dict[str, str]] = {}
  59. if os.path.isdir(plugins_dir):
  60. for fname in sorted(os.listdir(plugins_dir)):
  61. if fname.endswith(".py") and not fname.startswith("__"):
  62. plugin_name = fname[:-3]
  63. filepath = os.path.join(plugins_dir, fname)
  64. meta = _extract_plugin_meta_from_ast(filepath)
  65. meta["filename"] = fname
  66. if not meta["name"]:
  67. meta["name"] = plugin_name
  68. scanned_info[plugin_name] = meta
  69. _IN_MEMORY_PLUGIN_INFO = scanned_info
  70. return _IN_MEMORY_PLUGIN_INFO
  71. def get_installed_plugins(plugins_dir: str = PLUGINS_DIR) -> Dict[str, str]:
  72. """
  73. 获取本地已安装插件名与版本的映射字典
  74. 返回格式: {"tls_plugin": "1.0.0", "vfs_plugin": "1.0.0"}
  75. """
  76. all_info = scan_plugins(plugins_dir)
  77. return {k: v.get("version", "1.0.0") for k, v in all_info.items()}
  78. def get_installed_plugin_metas(plugins_dir: str = PLUGINS_DIR) -> List[PluginMeta]:
  79. """
  80. 获取本地已安装插件的完整元数据对象列表(含 name, version, description, filename)
  81. """
  82. all_info = scan_plugins(plugins_dir)
  83. metas = []
  84. for k, v in all_info.items():
  85. metas.append(
  86. PluginMeta(
  87. name=v.get("name", k),
  88. version=v.get("version", "1.0.0"),
  89. description=v.get("description", ""),
  90. filename=v.get("filename", f"{k}.py"),
  91. )
  92. )
  93. return metas
  94. def download_and_install_plugin(
  95. plugin_name: str,
  96. version: str,
  97. download_url: Optional[str] = None,
  98. code_content: Optional[str] = None,
  99. filename: Optional[str] = None,
  100. plugins_dir: str = PLUGINS_DIR,
  101. ) -> bool:
  102. """
  103. 下载/写入新版本插件文件,预检语法并原子替换,随后刷新内存中的插件版本信息
  104. """
  105. target_filename = filename or f"{plugin_name}.py"
  106. target_path = os.path.join(plugins_dir, target_filename)
  107. tmp_path = target_path + ".tmp"
  108. try:
  109. # 1. 获取代码内容(支持 URL 下载或直接传 code_content)
  110. if code_content is not None:
  111. with open(tmp_path, "w", encoding="utf-8") as f:
  112. f.write(code_content)
  113. elif download_url:
  114. resp = requests.get(download_url, timeout=30)
  115. resp.raise_for_status()
  116. with open(tmp_path, "wb") as f:
  117. f.write(resp.content)
  118. else:
  119. raise ValueError(f"Neither download_url nor code_content provided for '{plugin_name}'")
  120. # 2. 语法预检(防止下载坏代码导致运行时崩溃)
  121. py_compile.compile(tmp_path, doraise=True)
  122. # 3. 原子覆盖替换到 plugins/ 目录
  123. os.replace(tmp_path, target_path)
  124. # 4. 重新触发内存动态扫描,更新内存中的版本数据(不落盘)
  125. scan_plugins(plugins_dir)
  126. return True
  127. except Exception as e:
  128. if os.path.exists(tmp_path):
  129. try:
  130. os.remove(tmp_path)
  131. except Exception:
  132. pass
  133. raise RuntimeError(f"Failed to upgrade plugin '{plugin_name}' to {version}: {e}")