| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170 |
- 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,
- expected_sha256: 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. SHA256 校验(若提供)
- if expected_sha256:
- import hashlib
- with open(tmp_path, "rb") as f:
- computed_sha256 = hashlib.sha256(f.read()).hexdigest()
- if computed_sha256.lower() != expected_sha256.strip().lower():
- raise ValueError(f"SHA256 checksum mismatch for '{plugin_name}': expected {expected_sha256}, got {computed_sha256}")
- # 3. 语法预检(防止下载坏代码导致运行时崩溃)
- py_compile.compile(tmp_path, doraise=True)
- # 4. 原子覆盖替换到 plugins/ 目录
- os.replace(tmp_path, target_path)
- # 5. 重新触发内存动态扫描,更新内存中的版本数据(不落盘)
- 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}")
|