Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

plugin_manager.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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
  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. def scan_plugins(self):
  55. logger.info("Scaning plugins ...")
  56. plugins_dir = "./plugins"
  57. raws = [self.plugins[name] for name in self.plugins]
  58. for plugin_name in os.listdir(plugins_dir):
  59. plugin_path = os.path.join(plugins_dir, plugin_name)
  60. if os.path.isdir(plugin_path):
  61. # 判断插件是否包含同名__init__.py文件
  62. main_module_path = os.path.join(plugin_path, "__init__.py")
  63. if os.path.isfile(main_module_path):
  64. # 导入插件
  65. import_path = "plugins.{}".format(plugin_name)
  66. try:
  67. self.current_plugin_path = plugin_path
  68. if plugin_path in self.loaded:
  69. if self.loaded[plugin_path] == None:
  70. logger.info("reload module %s" % plugin_name)
  71. self.loaded[plugin_path] = importlib.reload(sys.modules[import_path])
  72. dependent_module_names = [name for name in sys.modules.keys() if name.startswith(import_path + ".")]
  73. for name in dependent_module_names:
  74. logger.info("reload module %s" % name)
  75. importlib.reload(sys.modules[name])
  76. else:
  77. self.loaded[plugin_path] = importlib.import_module(import_path)
  78. self.current_plugin_path = None
  79. except Exception as e:
  80. logger.exception("Failed to import plugin %s: %s" % (plugin_name, e))
  81. continue
  82. pconf = self.pconf
  83. news = [self.plugins[name] for name in self.plugins]
  84. new_plugins = list(set(news) - set(raws))
  85. modified = False
  86. for name, plugincls in self.plugins.items():
  87. rawname = plugincls.name
  88. if rawname not in pconf["plugins"]:
  89. modified = True
  90. logger.info("Plugin %s not found in pconfig, adding to pconfig..." % name)
  91. pconf["plugins"][rawname] = {
  92. "enabled": plugincls.enabled,
  93. "priority": plugincls.priority,
  94. }
  95. else:
  96. self.plugins[name].enabled = pconf["plugins"][rawname]["enabled"]
  97. self.plugins[name].priority = pconf["plugins"][rawname]["priority"]
  98. self.plugins._update_heap(name) # 更新下plugins中的顺序
  99. if modified:
  100. self.save_config()
  101. return new_plugins
  102. def refresh_order(self):
  103. for event in self.listening_plugins.keys():
  104. self.listening_plugins[event].sort(key=lambda name: self.plugins[name].priority, reverse=True)
  105. def activate_plugins(self): # 生成新开启的插件实例
  106. failed_plugins = []
  107. for name, plugincls in self.plugins.items():
  108. if plugincls.enabled:
  109. if name not in self.instances:
  110. try:
  111. instance = plugincls()
  112. except Exception as e:
  113. logger.exception("Failed to init %s, diabled. %s" % (name, e))
  114. self.disable_plugin(name)
  115. failed_plugins.append(name)
  116. continue
  117. self.instances[name] = instance
  118. for event in instance.handlers:
  119. if event not in self.listening_plugins:
  120. self.listening_plugins[event] = []
  121. self.listening_plugins[event].append(name)
  122. self.refresh_order()
  123. return failed_plugins
  124. def reload_plugin(self, name: str):
  125. name = name.upper()
  126. if name in self.instances:
  127. for event in self.listening_plugins:
  128. if name in self.listening_plugins[event]:
  129. self.listening_plugins[event].remove(name)
  130. del self.instances[name]
  131. self.activate_plugins()
  132. return True
  133. return False
  134. def load_plugins(self):
  135. self.load_config()
  136. self.scan_plugins()
  137. pconf = self.pconf
  138. logger.debug("plugins.json config={}".format(pconf))
  139. for name, plugin in pconf["plugins"].items():
  140. if name.upper() not in self.plugins:
  141. logger.error("Plugin %s not found, but found in plugins.json" % name)
  142. self.activate_plugins()
  143. def emit_event(self, e_context: EventContext, *args, **kwargs):
  144. if e_context.event in self.listening_plugins:
  145. for name in self.listening_plugins[e_context.event]:
  146. if self.plugins[name].enabled and e_context.action == EventAction.CONTINUE:
  147. logger.debug("Plugin %s triggered by event %s" % (name, e_context.event))
  148. instance = self.instances[name]
  149. instance.handlers[e_context.event](e_context, *args, **kwargs)
  150. if e_context.is_break():
  151. e_context["breaked_by"] = name
  152. logger.debug("Plugin %s breaked event %s" % (name, e_context.event))
  153. return e_context
  154. def set_plugin_priority(self, name: str, priority: int):
  155. name = name.upper()
  156. if name not in self.plugins:
  157. return False
  158. if self.plugins[name].priority == priority:
  159. return True
  160. self.plugins[name].priority = priority
  161. self.plugins._update_heap(name)
  162. rawname = self.plugins[name].name
  163. self.pconf["plugins"][rawname]["priority"] = priority
  164. self.pconf["plugins"]._update_heap(rawname)
  165. self.save_config()
  166. self.refresh_order()
  167. return True
  168. def enable_plugin(self, name: str):
  169. name = name.upper()
  170. if name not in self.plugins:
  171. return False, "插件不存在"
  172. if not self.plugins[name].enabled:
  173. self.plugins[name].enabled = True
  174. rawname = self.plugins[name].name
  175. self.pconf["plugins"][rawname]["enabled"] = True
  176. self.save_config()
  177. failed_plugins = self.activate_plugins()
  178. if name in failed_plugins:
  179. return False, "插件开启失败"
  180. return True, "插件已开启"
  181. return True, "插件已开启"
  182. def disable_plugin(self, name: str):
  183. name = name.upper()
  184. if name not in self.plugins:
  185. return False
  186. if self.plugins[name].enabled:
  187. self.plugins[name].enabled = False
  188. rawname = self.plugins[name].name
  189. self.pconf["plugins"][rawname]["enabled"] = False
  190. self.save_config()
  191. return True
  192. return True
  193. def list_plugins(self):
  194. return self.plugins
  195. def install_plugin(self, repo: str):
  196. try:
  197. import common.package_manager as pkgmgr
  198. pkgmgr.check_dulwich()
  199. except Exception as e:
  200. logger.error("Failed to install plugin, {}".format(e))
  201. return False, "无法导入dulwich,安装插件失败"
  202. import re
  203. from dulwich import porcelain
  204. logger.info("clone git repo: {}".format(repo))
  205. match = re.match(r"^(https?:\/\/|git@)([^\/:]+)[\/:]([^\/:]+)\/(.+).git$", repo)
  206. if not match:
  207. try:
  208. with open("./plugins/source.json", "r", encoding="utf-8") as f:
  209. source = json.load(f)
  210. if repo in source["repo"]:
  211. repo = source["repo"][repo]["url"]
  212. match = re.match(r"^(https?:\/\/|git@)([^\/:]+)[\/:]([^\/:]+)\/(.+).git$", repo)
  213. if not match:
  214. return False, "安装插件失败,source中的仓库地址不合法"
  215. else:
  216. return False, "安装插件失败,仓库地址不合法"
  217. except Exception as e:
  218. logger.error("Failed to install plugin, {}".format(e))
  219. return False, "安装插件失败,请检查仓库地址是否正确"
  220. dirname = os.path.join("./plugins", match.group(4))
  221. try:
  222. repo = porcelain.clone(repo, dirname, checkout=True)
  223. if os.path.exists(os.path.join(dirname, "requirements.txt")):
  224. logger.info("detect requirements.txt,installing...")
  225. pkgmgr.install_requirements(os.path.join(dirname, "requirements.txt"))
  226. return True, "安装插件成功,请使用 #scanp 命令扫描插件或重启程序,开启前请检查插件是否需要配置"
  227. except Exception as e:
  228. logger.error("Failed to install plugin, {}".format(e))
  229. return False, "安装插件失败," + str(e)
  230. def update_plugin(self, name: str):
  231. try:
  232. import common.package_manager as pkgmgr
  233. pkgmgr.check_dulwich()
  234. except Exception as e:
  235. logger.error("Failed to install plugin, {}".format(e))
  236. return False, "无法导入dulwich,更新插件失败"
  237. from dulwich import porcelain
  238. name = name.upper()
  239. if name not in self.plugins:
  240. return False, "插件不存在"
  241. if name in [
  242. "HELLO",
  243. "GODCMD",
  244. "ROLE",
  245. "TOOL",
  246. "BDUNIT",
  247. "BANWORDS",
  248. "FINISH",
  249. "DUNGEON",
  250. ]:
  251. return False, "预置插件无法更新,请更新主程序仓库"
  252. dirname = self.plugins[name].path
  253. try:
  254. porcelain.pull(dirname, "origin")
  255. if os.path.exists(os.path.join(dirname, "requirements.txt")):
  256. logger.info("detect requirements.txt,installing...")
  257. pkgmgr.install_requirements(os.path.join(dirname, "requirements.txt"))
  258. return True, "更新插件成功,请重新运行程序"
  259. except Exception as e:
  260. logger.error("Failed to update plugin, {}".format(e))
  261. return False, "更新插件失败," + str(e)
  262. def uninstall_plugin(self, name: str):
  263. name = name.upper()
  264. if name not in self.plugins:
  265. return False, "插件不存在"
  266. if name in self.instances:
  267. self.disable_plugin(name)
  268. dirname = self.plugins[name].path
  269. try:
  270. import shutil
  271. shutil.rmtree(dirname)
  272. rawname = self.plugins[name].name
  273. for event in self.listening_plugins:
  274. if name in self.listening_plugins[event]:
  275. self.listening_plugins[event].remove(name)
  276. del self.plugins[name]
  277. del self.pconf["plugins"][rawname]
  278. self.loaded[dirname] = None
  279. self.save_config()
  280. return True, "卸载插件成功"
  281. except Exception as e:
  282. logger.error("Failed to uninstall plugin, {}".format(e))
  283. return False, "卸载插件失败,请手动删除文件夹完成卸载," + str(e)