-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin_manager.py
More file actions
461 lines (378 loc) · 16.4 KB
/
Copy pathplugin_manager.py
File metadata and controls
461 lines (378 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
"""
插件管理器 — 动态发现、加载、管理插件
插件规范:
每个插件是一个独立的目录,放在 plugins/ 目录下。
目录名即插件标识,必须包含 config.json。
config.json 格式:
{
"name": "插件名称",
"version": "1.0.0",
"author": "作者",
"description": "描述",
"download_url": "",
"entry_point": "__init__.py",
"start_function": "initialize"
}
入口方式一(类继承,推荐):
从 plugin_base 继承 PluginBase,模块导出 PLUGIN_CLASS:
from plugin_base import PluginBase
class MyPlugin(PluginBase):
def on_initialize(self) -> bool:
self.api.register_hook('on_ui_ready', self._on_ui_ready)
return True
def on_shutdown(self):
pass
PLUGIN_CLASS = MyPlugin
入口方式二(函数导出,兼容):
__init__.py 导出:
initialize(api) — 插件入口函数,接收 PluginAPI 实例
shutdown() — 插件卸载时调用(可选)
插件目录内可以自由组织文件结构(.py、.ui、图片、数据模板等),
使用 api.plugin_dir 获取插件自身目录路径。
"""
import os
import sys
import json
import importlib
import importlib.util
from pathlib import Path
from typing import Dict, List, Optional
import logger
LOGGER = logger.LazyLogger('files/logs', 'plugin_manager.log')
class PluginInfo:
"""已加载插件的运行时信息"""
def __init__(self, metadata: dict, module, plugin_dir: str, instance=None):
basic = metadata.get('基本信息', {})
dl_list = metadata.get('下载信息', [])
dl_url = ''
if isinstance(dl_list, list) and dl_list:
first = dl_list[0]
if isinstance(first, dict):
dl_url = first.get(list(first.keys())[0], '') if first else ''
self.name: str = basic.get('名称', '未知插件')
self.version: str = basic.get('版本号', '0.0.0')
self.author: str = basic.get('作者', '未知')
self.description: str = basic.get('简介', '')
self.download_url: str = dl_url
self.plugin_dir: str = plugin_dir
self.module = module
self.instance = instance # PluginBase 实例(类继承方式)
self.enabled: bool = True
def to_dict(self) -> dict:
return {
'name': self.name,
'version': self.version,
'author': self.author,
'description': self.description,
'download_url': self.download_url,
'dir': os.path.basename(self.plugin_dir),
'enabled': self.enabled,
'class_based': self.instance is not None,
}
class PluginManager:
"""插件管理器 — 单例"""
_instance = None
@classmethod
def get_instance(cls) -> 'PluginManager':
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
if PluginManager._instance is not None:
raise RuntimeError("PluginManager是单例,请使用 get_instance()")
self._plugins: Dict[str, PluginInfo] = {}
self._api = None
self._plugins_dir: Optional[Path] = None
self._states_file: Optional[Path] = None
# ---- 初始化 ----
def initialize(self, plugin_api, plugins_dir: str = None, states_file: str = None):
"""
:param plugin_api: PluginAPI 实例
:param plugins_dir: 插件目录路径,默认为项目根目录下的 plugins/
:param states_file: 插件状态文件路径,默认为 files/configs/plugin_states.json
"""
self._api = plugin_api
if plugins_dir:
self._plugins_dir = Path(plugins_dir)
else:
self._plugins_dir = Path(__file__).parent / 'plugins'
import os as _os
_programdata_dir = _os.path.join('C:', _os.sep, 'ProgramData', 'SFS_Launcher')
if states_file:
self._states_file = Path(states_file)
else:
self._states_file = Path(_programdata_dir) / 'plugin_states.json'
# 从旧位置迁移到 ProgramData
_old_file = Path(__file__).parent / 'files' / 'configs' / 'plugin_states.json'
if _old_file.exists() and not self._states_file.exists():
try:
self._states_file.parent.mkdir(parents=True, exist_ok=True)
import shutil as _shutil
_shutil.copy2(_old_file, self._states_file)
LOGGER.info(f"插件状态已迁移: {_old_file} -> {self._states_file}")
except OSError as e:
LOGGER.warning(f"插件状态迁移失败: {e}")
LOGGER.info(f"插件目录: {self._plugins_dir}")
# ---- 发现与加载 ----
def discover(self) -> List[Path]:
"""扫描插件目录,返回所有包含 config.json 的插件目录路径"""
if not self._plugins_dir or not self._plugins_dir.exists():
LOGGER.warning(f"插件目录不存在: {self._plugins_dir}")
return []
candidates = []
for entry in sorted(self._plugins_dir.iterdir()):
if not entry.is_dir():
continue
if entry.name.startswith('_') or entry.name.startswith('.'):
continue
config_path = entry / 'config.json'
if not config_path.is_file():
LOGGER.debug(f"跳过非插件目录(无config.json): {entry.name}")
continue
config = self._read_config(config_path)
if not config:
continue
basic = self._get_basic(config)
if not basic.get('名称') or not basic.get('版本号'):
LOGGER.warning(f"插件 config.json 缺少基本信息.名称/版本号: {entry.name}")
continue
candidates.append(entry)
return candidates
def load_all(self) -> List[PluginInfo]:
"""发现并加载所有插件(跳过已禁用状态的插件),返回成功加载的插件列表"""
plugin_dirs = self.discover()
states = self._read_plugin_states()
loaded = []
for plugin_dir in plugin_dirs:
config = self._read_config(plugin_dir / 'config.json')
if not config:
continue
basic = self._get_basic(config)
name = basic.get('名称', plugin_dir.name)
if not states.get(name, True):
LOGGER.info(f"跳过已禁用的插件: {name}")
continue
info = self.load_plugin(plugin_dir)
if info:
loaded.append(info)
LOGGER.info(f"插件加载完成: {len(loaded)}/{len(plugin_dirs)} 成功")
return loaded
def load_plugin(self, plugin_dir: Path) -> Optional[PluginInfo]:
"""加载单个插件目录并注册到 _plugins。
支持两种入口方式:
1. 类继承:模块导出 PLUGIN_CLASS = MyPlugin(继承自 PluginBase)
2. 函数导出:模块导出 initialize(api) 和 shutdown()
"""
plugin_dir = Path(plugin_dir)
config_path = plugin_dir / 'config.json'
config = self._read_config(config_path)
if not config:
return None
basic = self._get_basic(config)
plugin_name = basic.get('名称', plugin_dir.name)
LOGGER.info(f"加载插件: {plugin_name} ({plugin_dir.name})")
try:
entry_point = config.get('entry_point', '__init__.py')
start_func_name = config.get('start_function', 'initialize')
entry_path = plugin_dir / entry_point
if not entry_path.is_file():
LOGGER.error(f"插件入口文件不存在: {entry_path}")
return None
module_name = f"_plugin_{plugin_dir.name}"
# 如果之前加载过同模块名,先清理
if module_name in sys.modules:
del sys.modules[module_name]
# 动态加载入口模块
spec = importlib.util.spec_from_file_location(
module_name, str(entry_path),
submodule_search_locations=[str(plugin_dir)]
)
if spec is None or spec.loader is None:
LOGGER.error(f"无法创建模块规格: {entry_path}")
return None
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
# 将插件目录加入模块的搜索路径,方便插件内部 import
if str(plugin_dir) not in sys.path:
sys.path.insert(0, str(plugin_dir))
spec.loader.exec_module(module)
# 设置当前加载插件的目录,供 api.plugin_dir 使用
if self._api:
self._api._current_plugin_dir.value = str(plugin_dir)
instance = None
try:
# 方式一:类继承入口(PLUGIN_CLASS)
plugin_class = getattr(module, 'PLUGIN_CLASS', None)
if plugin_class is not None and isinstance(plugin_class, type):
instance = plugin_class(self._api)
if not instance.initialize():
LOGGER.error(f"插件 on_initialize 返回失败: {plugin_name}")
return None
else:
# 方式二:函数入口
init_func = getattr(module, start_func_name, None)
if not callable(init_func):
LOGGER.error(f"插件缺少 {start_func_name}(api) 函数且未导出 PLUGIN_CLASS: {entry_path}")
return None
init_func(self._api)
finally:
if self._api:
self._api._current_plugin_dir.value = None
dl_list = config.get('下载信息', [])
dl_url = ''
if isinstance(dl_list, list) and dl_list:
first = dl_list[0]
if isinstance(first, dict):
dl_url = first.get(list(first.keys())[0], '') if first else ''
LOGGER.info(f"插件初始化成功: {plugin_name} v{basic.get('版本号')} "
f"by {basic.get('作者', '未知')}"
f"{' (class)' if instance else ''}")
info = PluginInfo(config, module, str(plugin_dir), instance)
self._plugins[plugin_name] = info
return info
except Exception as e:
if self._api:
self._api._current_plugin_dir.value = None
LOGGER.error(f"加载插件失败 {plugin_dir.name}: {e}", exc_info=True)
return None
# ---- 插件状态持久化 ----
def _read_plugin_states(self) -> dict:
"""读取插件启用/禁用状态文件,返回 {plugin_name: True/False}"""
if self._states_file is None:
return {}
try:
if not self._states_file.exists():
return {}
with open(self._states_file, 'r', encoding='utf-8') as f:
data = json.load(f)
if isinstance(data, dict):
return data
return {}
except (json.JSONDecodeError, OSError) as e:
LOGGER.warning(f"读取插件状态文件失败: {e}")
return {}
def _save_plugin_states(self, states: dict):
"""保存插件启用/禁用状态到文件"""
if self._states_file is None:
return
try:
self._states_file.parent.mkdir(parents=True, exist_ok=True)
with open(self._states_file, 'w', encoding='utf-8') as f:
json.dump(states, f, ensure_ascii=False, indent=2)
LOGGER.info(f"插件状态已保存: {len(states)} 条")
except OSError as e:
LOGGER.error(f"保存插件状态文件失败: {e}")
def set_plugin_loaded_state(self, name: str, load: bool) -> bool:
"""持久化插件的加载/卸载状态(供UI ExtenOper按钮调用)。
load=True 时启用(下次启动自动加载),load=False 时禁用。
返回是否操作成功。"""
states = self._read_plugin_states()
states[name] = load
self._save_plugin_states(states)
LOGGER.info(f"插件状态变更: {name} -> {'启用' if load else '禁用'}")
return True
def is_plugin_state_loaded(self, name: str) -> bool:
"""检查插件的持久化状态是否为启用(默认 True)"""
return self._read_plugin_states().get(name, True)
def reload_plugin(self, name: str) -> Optional[PluginInfo]:
"""重新加载指定插件"""
info = self._plugins.get(name)
if not info:
LOGGER.warning(f"插件未找到: {name}")
return None
self.unload_plugin(name)
# 重新从磁盘加载
plugin_dir = Path(info.plugin_dir)
return self.load_plugin(plugin_dir)
def enable_plugin(self, name: str) -> bool:
"""启用指定插件"""
info = self._plugins.get(name)
if not info:
LOGGER.warning(f"插件未找到: {name}")
return False
if info.enabled:
return True
if info.instance is not None:
if info.instance.enable():
info.enabled = True
LOGGER.info(f"插件已启用: {name}")
return True
return False
info.enabled = True
LOGGER.info(f"插件已启用: {name}")
return True
def disable_plugin(self, name: str):
"""禁用指定插件"""
info = self._plugins.get(name)
if not info:
LOGGER.warning(f"插件未找到: {name}")
return
if not info.enabled:
return
if info.instance is not None:
info.instance.disable()
info.enabled = False
LOGGER.info(f"插件已禁用: {name}")
def unload_plugin(self, name: str):
"""卸载指定插件"""
info = self._plugins.get(name)
if not info:
return
# 类继承方式:通过实例 shutdown
if info.instance is not None:
try:
info.instance.shutdown()
except Exception as e:
LOGGER.error(f"插件 {name} shutdown 失败: {e}")
else:
# 函数导出方式:调用模块级 shutdown
shutdown = getattr(info.module, 'shutdown', None)
if callable(shutdown):
try:
shutdown()
except Exception as e:
LOGGER.error(f"插件 {name} shutdown 失败: {e}")
module_name = f"_plugin_{os.path.basename(info.plugin_dir)}"
if module_name in sys.modules:
del sys.modules[module_name]
# 从搜索路径中移除插件目录
plugin_dir = info.plugin_dir
if plugin_dir in sys.path:
sys.path.remove(plugin_dir)
del self._plugins[name]
LOGGER.info(f"插件已卸载: {name}")
def shutdown_all(self):
"""卸载所有插件"""
for name in list(self._plugins.keys()):
self.unload_plugin(name)
# ---- 查询 ----
def get_plugin(self, name: str) -> Optional[PluginInfo]:
return self._plugins.get(name)
def get_plugin_dir(self, name: str) -> Optional[str]:
"""获取指定插件的目录路径"""
info = self._plugins.get(name)
return info.plugin_dir if info else None
def list_plugins(self) -> List[dict]:
return [p.to_dict() for p in self._plugins.values()]
def is_loaded(self, name: str) -> bool:
return name in self._plugins
@property
def plugin_count(self) -> int:
return len(self._plugins)
# ---- 内部工具 ----
@staticmethod
def _read_config(config_path: Path) -> Optional[dict]:
try:
with open(config_path, 'r', encoding='utf-8') as f:
data = json.load(f)
if not isinstance(data, dict):
LOGGER.error(f"config.json 格式无效: {config_path}")
return None
return data
except (json.JSONDecodeError, OSError) as e:
LOGGER.error(f"读取 config.json 失败 {config_path}: {e}")
return None
@staticmethod
def _get_basic(config: dict) -> dict:
"""获取基本信息字典"""
return config.get('基本信息', {})