You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

312 lines
13KB

  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. return e_context
  151. def set_plugin_priority(self, name: str, priority: int):
  152. name = name.upper()
  153. if name not in self.plugins:
  154. return False
  155. if self.plugins[name].priority == priority:
  156. return True
  157. self.plugins[name].priority = priority
  158. self.plugins._update_heap(name)
  159. rawname = self.plugins[name].name
  160. self.pconf["plugins"][rawname]["priority"] = priority
  161. self.pconf["plugins"]._update_heap(rawname)
  162. self.save_config()
  163. self.refresh_order()
  164. return True
  165. def enable_plugin(self, name: str):
  166. name = name.upper()
  167. if name not in self.plugins:
  168. return False, "插件不存在"
  169. if not self.plugins[name].enabled:
  170. self.plugins[name].enabled = True
  171. rawname = self.plugins[name].name
  172. self.pconf["plugins"][rawname]["enabled"] = True
  173. self.save_config()
  174. failed_plugins = self.activate_plugins()
  175. if name in failed_plugins:
  176. return False, "插件开启失败"
  177. return True, "插件已开启"
  178. return True, "插件已开启"
  179. def disable_plugin(self, name: str):
  180. name = name.upper()
  181. if name not in self.plugins:
  182. return False
  183. if self.plugins[name].enabled:
  184. self.plugins[name].enabled = False
  185. rawname = self.plugins[name].name
  186. self.pconf["plugins"][rawname]["enabled"] = False
  187. self.save_config()
  188. return True
  189. return True
  190. def list_plugins(self):
  191. return self.plugins
  192. def install_plugin(self, repo: str):
  193. try:
  194. import common.package_manager as pkgmgr
  195. pkgmgr.check_dulwich()
  196. except Exception as e:
  197. logger.error("Failed to install plugin, {}".format(e))
  198. return False, "无法导入dulwich,安装插件失败"
  199. import re
  200. from dulwich import porcelain
  201. logger.info("clone git repo: {}".format(repo))
  202. match = re.match(r"^(https?:\/\/|git@)([^\/:]+)[\/:]([^\/:]+)\/(.+).git$", repo)
  203. if not match:
  204. try:
  205. with open("./plugins/source.json", "r", encoding="utf-8") as f:
  206. source = json.load(f)
  207. if repo in source["repo"]:
  208. repo = source["repo"][repo]["url"]
  209. match = re.match(r"^(https?:\/\/|git@)([^\/:]+)[\/:]([^\/:]+)\/(.+).git$", repo)
  210. if not match:
  211. return False, "安装插件失败,source中的仓库地址不合法"
  212. else:
  213. return False, "安装插件失败,仓库地址不合法"
  214. except Exception as e:
  215. logger.error("Failed to install plugin, {}".format(e))
  216. return False, "安装插件失败,请检查仓库地址是否正确"
  217. dirname = os.path.join("./plugins", match.group(4))
  218. try:
  219. repo = porcelain.clone(repo, dirname, checkout=True)
  220. if os.path.exists(os.path.join(dirname, "requirements.txt")):
  221. logger.info("detect requirements.txt,installing...")
  222. pkgmgr.install_requirements(os.path.join(dirname, "requirements.txt"))
  223. return True, "安装插件成功,请使用 #scanp 命令扫描插件或重启程序,开启前请检查插件是否需要配置"
  224. except Exception as e:
  225. logger.error("Failed to install plugin, {}".format(e))
  226. return False, "安装插件失败," + str(e)
  227. def update_plugin(self, name: str):
  228. try:
  229. import common.package_manager as pkgmgr
  230. pkgmgr.check_dulwich()
  231. except Exception as e:
  232. logger.error("Failed to install plugin, {}".format(e))
  233. return False, "无法导入dulwich,更新插件失败"
  234. from dulwich import porcelain
  235. name = name.upper()
  236. if name not in self.plugins:
  237. return False, "插件不存在"
  238. if name in [
  239. "HELLO",
  240. "GODCMD",
  241. "ROLE",
  242. "TOOL",
  243. "BDUNIT",
  244. "BANWORDS",
  245. "FINISH",
  246. "DUNGEON",
  247. ]:
  248. return False, "预置插件无法更新,请更新主程序仓库"
  249. dirname = self.plugins[name].path
  250. try:
  251. porcelain.pull(dirname, "origin")
  252. if os.path.exists(os.path.join(dirname, "requirements.txt")):
  253. logger.info("detect requirements.txt,installing...")
  254. pkgmgr.install_requirements(os.path.join(dirname, "requirements.txt"))
  255. return True, "更新插件成功,请重新运行程序"
  256. except Exception as e:
  257. logger.error("Failed to update plugin, {}".format(e))
  258. return False, "更新插件失败," + str(e)
  259. def uninstall_plugin(self, name: str):
  260. name = name.upper()
  261. if name not in self.plugins:
  262. return False, "插件不存在"
  263. if name in self.instances:
  264. self.disable_plugin(name)
  265. dirname = self.plugins[name].path
  266. try:
  267. import shutil
  268. shutil.rmtree(dirname)
  269. rawname = self.plugins[name].name
  270. for event in self.listening_plugins:
  271. if name in self.listening_plugins[event]:
  272. self.listening_plugins[event].remove(name)
  273. del self.plugins[name]
  274. del self.pconf["plugins"][rawname]
  275. self.loaded[dirname] = None
  276. self.save_config()
  277. return True, "卸载插件成功"
  278. except Exception as e:
  279. logger.error("Failed to uninstall plugin, {}".format(e))
  280. return False, "卸载插件失败,请手动删除文件夹完成卸载," + str(e)