Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

339 lines
14KB

  1. # encoding:utf-8
  2. import importlib
  3. import importlib.util
  4. import json
  5. import os
  6. import sys
  7. from common.log import logger
  8. from common.singleton import singleton
  9. from common.sorted_dict import SortedDict
  10. from config import conf, write_plugin_config
  11. from .event import *
  12. @singleton
  13. class PluginManager:
  14. def __init__(self):
  15. self.plugins = SortedDict(lambda k, v: v.priority, reverse=True)
  16. self.listening_plugins = {}
  17. self.instances = {}
  18. self.pconf = {}
  19. self.current_plugin_path = None
  20. self.loaded = {}
  21. def register(self, name: str, desire_priority: int = 0, **kwargs):
  22. def wrapper(plugincls):
  23. plugincls.name = name
  24. plugincls.priority = desire_priority
  25. plugincls.desc = kwargs.get("desc")
  26. plugincls.author = kwargs.get("author")
  27. plugincls.path = self.current_plugin_path
  28. plugincls.version = kwargs.get("version") if kwargs.get("version") != None else "1.0"
  29. plugincls.namecn = kwargs.get("namecn") if kwargs.get("namecn") != None else name
  30. plugincls.hidden = kwargs.get("hidden") if kwargs.get("hidden") != None else False
  31. plugincls.enabled = True
  32. if self.current_plugin_path == None:
  33. raise Exception("Plugin path not set")
  34. self.plugins[name.upper()] = plugincls
  35. logger.info("Plugin %s_v%s registered, path=%s" % (name, plugincls.version, plugincls.path))
  36. return wrapper
  37. def save_config(self):
  38. with open("./plugins/plugins.json", "w", encoding="utf-8") as f:
  39. json.dump(self.pconf, f, indent=4, ensure_ascii=False)
  40. def load_config(self):
  41. logger.info("Loading plugins config...")
  42. modified = False
  43. if os.path.exists("./plugins/plugins.json"):
  44. with open("./plugins/plugins.json", "r", encoding="utf-8") as f:
  45. pconf = json.load(f)
  46. pconf["plugins"] = SortedDict(lambda k, v: v["priority"], pconf["plugins"], reverse=True)
  47. else:
  48. modified = True
  49. pconf = {"plugins": SortedDict(lambda k, v: v["priority"], reverse=True)}
  50. self.pconf = pconf
  51. if modified:
  52. self.save_config()
  53. return pconf
  54. @staticmethod
  55. def _load_all_config():
  56. """
  57. 背景: 目前插件配置存放于每个插件目录的config.json下,docker运行时不方便进行映射,故增加统一管理的入口,优先
  58. 加载 plugins/config.json,原插件目录下的config.json 不受影响
  59. 从 plugins/config.json 中加载所有插件的配置并写入 config.py 的全局配置中,供插件中使用
  60. 插件实例中通过 config.pconf(plugin_name) 即可获取该插件的配置
  61. """
  62. all_config_path = "./plugins/config.json"
  63. try:
  64. if os.path.exists(all_config_path):
  65. # read from all plugins config
  66. with open(all_config_path, "r", encoding="utf-8") as f:
  67. all_conf = json.load(f)
  68. logger.info(f"load all config from plugins/config.json: {all_conf}")
  69. # write to global config
  70. write_plugin_config(all_conf)
  71. except Exception as e:
  72. logger.error(e)
  73. def scan_plugins(self):
  74. logger.info("Scaning plugins ...")
  75. plugins_dir = "./plugins"
  76. raws = [self.plugins[name] for name in self.plugins]
  77. for plugin_name in os.listdir(plugins_dir):
  78. plugin_path = os.path.join(plugins_dir, plugin_name)
  79. if os.path.isdir(plugin_path):
  80. # 判断插件是否包含同名__init__.py文件
  81. main_module_path = os.path.join(plugin_path, "__init__.py")
  82. if os.path.isfile(main_module_path):
  83. # 导入插件
  84. import_path = "plugins.{}".format(plugin_name)
  85. try:
  86. self.current_plugin_path = plugin_path
  87. if plugin_path in self.loaded:
  88. if self.loaded[plugin_path] == None:
  89. logger.info("reload module %s" % plugin_name)
  90. self.loaded[plugin_path] = importlib.reload(sys.modules[import_path])
  91. dependent_module_names = [name for name in sys.modules.keys() if name.startswith(import_path + ".")]
  92. for name in dependent_module_names:
  93. logger.info("reload module %s" % name)
  94. importlib.reload(sys.modules[name])
  95. else:
  96. self.loaded[plugin_path] = importlib.import_module(import_path)
  97. self.current_plugin_path = None
  98. except Exception as e:
  99. logger.warn("Failed to import plugin %s: %s" % (plugin_name, e))
  100. continue
  101. pconf = self.pconf
  102. news = [self.plugins[name] for name in self.plugins]
  103. new_plugins = list(set(news) - set(raws))
  104. modified = False
  105. for name, plugincls in self.plugins.items():
  106. rawname = plugincls.name
  107. if rawname not in pconf["plugins"]:
  108. modified = True
  109. logger.info("Plugin %s not found in pconfig, adding to pconfig..." % name)
  110. pconf["plugins"][rawname] = {
  111. "enabled": plugincls.enabled,
  112. "priority": plugincls.priority,
  113. }
  114. else:
  115. self.plugins[name].enabled = pconf["plugins"][rawname]["enabled"]
  116. self.plugins[name].priority = pconf["plugins"][rawname]["priority"]
  117. self.plugins._update_heap(name) # 更新下plugins中的顺序
  118. if modified:
  119. self.save_config()
  120. return new_plugins
  121. def refresh_order(self):
  122. for event in self.listening_plugins.keys():
  123. self.listening_plugins[event].sort(key=lambda name: self.plugins[name].priority, reverse=True)
  124. def activate_plugins(self): # 生成新开启的插件实例
  125. failed_plugins = []
  126. for name, plugincls in self.plugins.items():
  127. if plugincls.enabled:
  128. if name not in self.instances:
  129. try:
  130. instance = plugincls()
  131. except Exception as e:
  132. logger.warn("Failed to init %s, diabled. %s" % (name, e))
  133. self.disable_plugin(name)
  134. failed_plugins.append(name)
  135. continue
  136. self.instances[name] = instance
  137. for event in instance.handlers:
  138. if event not in self.listening_plugins:
  139. self.listening_plugins[event] = []
  140. self.listening_plugins[event].append(name)
  141. self.refresh_order()
  142. return failed_plugins
  143. def reload_plugin(self, name: str):
  144. name = name.upper()
  145. if name in self.instances:
  146. for event in self.listening_plugins:
  147. if name in self.listening_plugins[event]:
  148. self.listening_plugins[event].remove(name)
  149. del self.instances[name]
  150. self.activate_plugins()
  151. return True
  152. return False
  153. def load_plugins(self):
  154. self.load_config()
  155. self.scan_plugins()
  156. # 加载全量插件配置
  157. self._load_all_config()
  158. pconf = self.pconf
  159. logger.debug("plugins.json config={}".format(pconf))
  160. for name, plugin in pconf["plugins"].items():
  161. if name.upper() not in self.plugins:
  162. logger.error("Plugin %s not found, but found in plugins.json" % name)
  163. self.activate_plugins()
  164. def emit_event(self, e_context: EventContext, *args, **kwargs):
  165. if e_context.event in self.listening_plugins:
  166. for name in self.listening_plugins[e_context.event]:
  167. if self.plugins[name].enabled and e_context.action == EventAction.CONTINUE:
  168. logger.debug("Plugin %s triggered by event %s" % (name, e_context.event))
  169. instance = self.instances[name]
  170. instance.handlers[e_context.event](e_context, *args, **kwargs)
  171. if e_context.is_break():
  172. e_context["breaked_by"] = name
  173. logger.debug("Plugin %s breaked event %s" % (name, e_context.event))
  174. return e_context
  175. def set_plugin_priority(self, name: str, priority: int):
  176. name = name.upper()
  177. if name not in self.plugins:
  178. return False
  179. if self.plugins[name].priority == priority:
  180. return True
  181. self.plugins[name].priority = priority
  182. self.plugins._update_heap(name)
  183. rawname = self.plugins[name].name
  184. self.pconf["plugins"][rawname]["priority"] = priority
  185. self.pconf["plugins"]._update_heap(rawname)
  186. self.save_config()
  187. self.refresh_order()
  188. return True
  189. def enable_plugin(self, name: str):
  190. name = name.upper()
  191. if name not in self.plugins:
  192. return False, "插件不存在"
  193. if not self.plugins[name].enabled:
  194. self.plugins[name].enabled = True
  195. rawname = self.plugins[name].name
  196. self.pconf["plugins"][rawname]["enabled"] = True
  197. self.save_config()
  198. failed_plugins = self.activate_plugins()
  199. if name in failed_plugins:
  200. return False, "插件开启失败"
  201. return True, "插件已开启"
  202. return True, "插件已开启"
  203. def disable_plugin(self, name: str):
  204. name = name.upper()
  205. if name not in self.plugins:
  206. return False
  207. if self.plugins[name].enabled:
  208. self.plugins[name].enabled = False
  209. rawname = self.plugins[name].name
  210. self.pconf["plugins"][rawname]["enabled"] = False
  211. self.save_config()
  212. return True
  213. return True
  214. def list_plugins(self):
  215. return self.plugins
  216. def install_plugin(self, repo: str):
  217. try:
  218. import common.package_manager as pkgmgr
  219. pkgmgr.check_dulwich()
  220. except Exception as e:
  221. logger.error("Failed to install plugin, {}".format(e))
  222. return False, "无法导入dulwich,安装插件失败"
  223. import re
  224. from dulwich import porcelain
  225. logger.info("clone git repo: {}".format(repo))
  226. match = re.match(r"^(https?:\/\/|git@)([^\/:]+)[\/:]([^\/:]+)\/(.+).git$", repo)
  227. if not match:
  228. try:
  229. with open("./plugins/source.json", "r", encoding="utf-8") as f:
  230. source = json.load(f)
  231. if repo in source["repo"]:
  232. repo = source["repo"][repo]["url"]
  233. match = re.match(r"^(https?:\/\/|git@)([^\/:]+)[\/:]([^\/:]+)\/(.+).git$", repo)
  234. if not match:
  235. return False, "安装插件失败,source中的仓库地址不合法"
  236. else:
  237. return False, "安装插件失败,仓库地址不合法"
  238. except Exception as e:
  239. logger.error("Failed to install plugin, {}".format(e))
  240. return False, "安装插件失败,请检查仓库地址是否正确"
  241. dirname = os.path.join("./plugins", match.group(4))
  242. try:
  243. repo = porcelain.clone(repo, dirname, checkout=True)
  244. if os.path.exists(os.path.join(dirname, "requirements.txt")):
  245. logger.info("detect requirements.txt,installing...")
  246. pkgmgr.install_requirements(os.path.join(dirname, "requirements.txt"))
  247. return True, "安装插件成功,请使用 #scanp 命令扫描插件或重启程序,开启前请检查插件是否需要配置"
  248. except Exception as e:
  249. logger.error("Failed to install plugin, {}".format(e))
  250. return False, "安装插件失败," + str(e)
  251. def update_plugin(self, name: str):
  252. try:
  253. import common.package_manager as pkgmgr
  254. pkgmgr.check_dulwich()
  255. except Exception as e:
  256. logger.error("Failed to install plugin, {}".format(e))
  257. return False, "无法导入dulwich,更新插件失败"
  258. from dulwich import porcelain
  259. name = name.upper()
  260. if name not in self.plugins:
  261. return False, "插件不存在"
  262. if name in [
  263. "HELLO",
  264. "GODCMD",
  265. "ROLE",
  266. "TOOL",
  267. "BDUNIT",
  268. "BANWORDS",
  269. "FINISH",
  270. "DUNGEON",
  271. ]:
  272. return False, "预置插件无法更新,请更新主程序仓库"
  273. dirname = self.plugins[name].path
  274. try:
  275. porcelain.pull(dirname, "origin")
  276. if os.path.exists(os.path.join(dirname, "requirements.txt")):
  277. logger.info("detect requirements.txt,installing...")
  278. pkgmgr.install_requirements(os.path.join(dirname, "requirements.txt"))
  279. return True, "更新插件成功,请重新运行程序"
  280. except Exception as e:
  281. logger.error("Failed to update plugin, {}".format(e))
  282. return False, "更新插件失败," + str(e)
  283. def uninstall_plugin(self, name: str):
  284. name = name.upper()
  285. if name not in self.plugins:
  286. return False, "插件不存在"
  287. if name in self.instances:
  288. self.disable_plugin(name)
  289. dirname = self.plugins[name].path
  290. try:
  291. import shutil
  292. shutil.rmtree(dirname)
  293. rawname = self.plugins[name].name
  294. for event in self.listening_plugins:
  295. if name in self.listening_plugins[event]:
  296. self.listening_plugins[event].remove(name)
  297. del self.plugins[name]
  298. del self.pconf["plugins"][rawname]
  299. self.loaded[dirname] = None
  300. self.save_config()
  301. return True, "卸载插件成功"
  302. except Exception as e:
  303. logger.error("Failed to uninstall plugin, {}".format(e))
  304. return False, "卸载插件失败,请手动删除文件夹完成卸载," + str(e)