import os import ast import py_compile import requests from typing import Dict, Any, List, Optional from vs_types import PluginMeta PLUGINS_DIR = "plugins" # 纯内存缓存,无需落盘 _IN_MEMORY_PLUGIN_INFO: Dict[str, Dict[str, str]] = {} def _parse_version(v_str: str) -> tuple: """将版本字符串解析为数字元组进行比较,如 '1.2.3' -> (1, 2, 3)""" try: clean_v = str(v_str).strip().lstrip("v") return tuple(int(part) for part in clean_v.split(".") if part.isdigit()) except Exception: return (0,) def is_newer_version(cloud_version: str, local_version: str) -> bool: """判断云端版本是否高于本地版本""" return _parse_version(cloud_version) > _parse_version(local_version) def _extract_plugin_meta_from_ast(filepath: str) -> Dict[str, str]: """ 通过 AST 静态分析插件代码中的 IVSPlg 子类元数据(name, version, description), 避免直接 import 产生网络请求或浏览器启动等副作用。 """ info = {"version": "1.0.0", "name": "", "description": ""} try: with open(filepath, "r", encoding="utf-8") as f: tree = ast.parse(f.read(), filename=filepath) for node in tree.body: # 1. 检查模块级变量 (如 __version__ = "1.0.0") if isinstance(node, ast.Assign): for target in node.targets: if isinstance(target, ast.Name): if target.id == "__version__" and isinstance(node.value, ast.Constant): info["version"] = str(node.value.value) elif target.id == "__description__" and isinstance(node.value, ast.Constant): info["description"] = str(node.value.value) # 2. 检查类定义 (如 class TlsPlugin(IVSPlg): version = "1.0.0") elif isinstance(node, ast.ClassDef): for item in node.body: if isinstance(item, ast.Assign): for target in item.targets: if isinstance(target, ast.Name) and isinstance(item.value, ast.Constant): if target.id == "version": info["version"] = str(item.value.value) elif target.id == "name": info["name"] = str(item.value.value) elif target.id == "description": info["description"] = str(item.value.value) except Exception as e: print(f"[PluginUpdater] AST parse error for {filepath}: {e}") return info def scan_plugins(plugins_dir: str = PLUGINS_DIR) -> Dict[str, Dict[str, str]]: """ 运行时动态扫描 plugins 目录,读取所有插件的基本元数据到内存中(不写文件) """ global _IN_MEMORY_PLUGIN_INFO scanned_info: Dict[str, Dict[str, str]] = {} if os.path.isdir(plugins_dir): for fname in sorted(os.listdir(plugins_dir)): if fname.endswith(".py") and not fname.startswith("__"): plugin_name = fname[:-3] filepath = os.path.join(plugins_dir, fname) meta = _extract_plugin_meta_from_ast(filepath) meta["filename"] = fname if not meta["name"]: meta["name"] = plugin_name scanned_info[plugin_name] = meta _IN_MEMORY_PLUGIN_INFO = scanned_info return _IN_MEMORY_PLUGIN_INFO def get_installed_plugins(plugins_dir: str = PLUGINS_DIR) -> Dict[str, str]: """ 获取本地已安装插件名与版本的映射字典 返回格式: {"tls_plugin": "1.0.0", "vfs_plugin": "1.0.0"} """ all_info = scan_plugins(plugins_dir) return {k: v.get("version", "1.0.0") for k, v in all_info.items()} def get_installed_plugin_metas(plugins_dir: str = PLUGINS_DIR) -> List[PluginMeta]: """ 获取本地已安装插件的完整元数据对象列表(含 name, version, description, filename) """ all_info = scan_plugins(plugins_dir) metas = [] for k, v in all_info.items(): metas.append( PluginMeta( name=v.get("name", k), version=v.get("version", "1.0.0"), description=v.get("description", ""), filename=v.get("filename", f"{k}.py"), ) ) return metas def download_and_install_plugin( plugin_name: str, version: str, download_url: Optional[str] = None, code_content: Optional[str] = None, filename: Optional[str] = None, plugins_dir: str = PLUGINS_DIR, ) -> bool: """ 下载/写入新版本插件文件,预检语法并原子替换,随后刷新内存中的插件版本信息 """ target_filename = filename or f"{plugin_name}.py" target_path = os.path.join(plugins_dir, target_filename) tmp_path = target_path + ".tmp" try: # 1. 获取代码内容(支持 URL 下载或直接传 code_content) if code_content is not None: with open(tmp_path, "w", encoding="utf-8") as f: f.write(code_content) elif download_url: resp = requests.get(download_url, timeout=30) resp.raise_for_status() with open(tmp_path, "wb") as f: f.write(resp.content) else: raise ValueError(f"Neither download_url nor code_content provided for '{plugin_name}'") # 2. 语法预检(防止下载坏代码导致运行时崩溃) py_compile.compile(tmp_path, doraise=True) # 3. 原子覆盖替换到 plugins/ 目录 os.replace(tmp_path, target_path) # 4. 重新触发内存动态扫描,更新内存中的版本数据(不落盘) scan_plugins(plugins_dir) return True except Exception as e: if os.path.exists(tmp_path): try: os.remove(tmp_path) except Exception: pass raise RuntimeError(f"Failed to upgrade plugin '{plugin_name}' to {version}: {e}")