選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

171 行
6.6KB

  1. # encoding:utf-8
  2. import importlib
  3. import json
  4. import os
  5. from common.singleton import singleton
  6. from common.sorted_dict import SortedDict
  7. from .event import *
  8. from .plugin import *
  9. from common.log import logger
  10. @singleton
  11. class PluginManager:
  12. def __init__(self):
  13. self.plugins = SortedDict(lambda k,v: v.priority,reverse=True)
  14. self.listening_plugins = {}
  15. self.instances = {}
  16. self.pconf = {}
  17. def register(self, name: str, desc: str, version: str, author: str, desire_priority: int = 0):
  18. def wrapper(plugincls):
  19. plugincls.name = name
  20. plugincls.desc = desc
  21. plugincls.version = version
  22. plugincls.author = author
  23. plugincls.priority = desire_priority
  24. plugincls.enabled = True
  25. self.plugins[name.upper()] = plugincls
  26. logger.info("Plugin %s_v%s registered" % (name, version))
  27. return plugincls
  28. return wrapper
  29. def save_config(self):
  30. with open("plugins/plugins.json", "w", encoding="utf-8") as f:
  31. json.dump(self.pconf, f, indent=4, ensure_ascii=False)
  32. def load_config(self):
  33. logger.info("Loading plugins config...")
  34. modified = False
  35. if os.path.exists("plugins/plugins.json"):
  36. with open("plugins/plugins.json", "r", encoding="utf-8") as f:
  37. pconf = json.load(f)
  38. pconf['plugins'] = SortedDict(lambda k,v: v["priority"],pconf['plugins'],reverse=True)
  39. else:
  40. modified = True
  41. pconf = {"plugins": SortedDict(lambda k,v: v["priority"],reverse=True)}
  42. self.pconf = pconf
  43. if modified:
  44. self.save_config()
  45. return pconf
  46. def scan_plugins(self):
  47. logger.info("Scaning plugins ...")
  48. plugins_dir = "plugins"
  49. for plugin_name in os.listdir(plugins_dir):
  50. plugin_path = os.path.join(plugins_dir, plugin_name)
  51. if os.path.isdir(plugin_path):
  52. # 判断插件是否包含同名.py文件
  53. main_module_path = os.path.join(plugin_path, plugin_name+".py")
  54. if os.path.isfile(main_module_path):
  55. # 导入插件
  56. import_path = "{}.{}.{}".format(plugins_dir, plugin_name, plugin_name)
  57. main_module = importlib.import_module(import_path)
  58. pconf = self.pconf
  59. new_plugins = []
  60. modified = False
  61. for name, plugincls in self.plugins.items():
  62. rawname = plugincls.name
  63. if rawname not in pconf["plugins"]:
  64. new_plugins.append(plugincls)
  65. modified = True
  66. logger.info("Plugin %s not found in pconfig, adding to pconfig..." % name)
  67. pconf["plugins"][rawname] = {"enabled": plugincls.enabled, "priority": plugincls.priority}
  68. else:
  69. self.plugins[name].enabled = pconf["plugins"][rawname]["enabled"]
  70. self.plugins[name].priority = pconf["plugins"][rawname]["priority"]
  71. self.plugins._update_heap(name) # 更新下plugins中的顺序
  72. if modified:
  73. self.save_config()
  74. return new_plugins
  75. def refresh_order(self):
  76. for event in self.listening_plugins.keys():
  77. self.listening_plugins[event].sort(key=lambda name: self.plugins[name].priority, reverse=True)
  78. def activate_plugins(self): # 生成新开启的插件实例
  79. for name, plugincls in self.plugins.items():
  80. if plugincls.enabled:
  81. if name not in self.instances:
  82. instance = plugincls()
  83. self.instances[name] = instance
  84. for event in instance.handlers:
  85. if event not in self.listening_plugins:
  86. self.listening_plugins[event] = []
  87. self.listening_plugins[event].append(name)
  88. self.refresh_order()
  89. def reload_plugin(self, name:str):
  90. name = name.upper()
  91. if name in self.instances:
  92. for event in self.listening_plugins:
  93. if name in self.listening_plugins[event]:
  94. self.listening_plugins[event].remove(name)
  95. del self.instances[name]
  96. self.activate_plugins()
  97. return True
  98. return False
  99. def load_plugins(self):
  100. self.load_config()
  101. self.scan_plugins()
  102. pconf = self.pconf
  103. logger.debug("plugins.json config={}".format(pconf))
  104. for name,plugin in pconf["plugins"].items():
  105. if name.upper() not in self.plugins:
  106. logger.error("Plugin %s not found, but found in plugins.json" % name)
  107. self.activate_plugins()
  108. def emit_event(self, e_context: EventContext, *args, **kwargs):
  109. if e_context.event in self.listening_plugins:
  110. for name in self.listening_plugins[e_context.event]:
  111. if self.plugins[name].enabled and e_context.action == EventAction.CONTINUE:
  112. logger.debug("Plugin %s triggered by event %s" % (name,e_context.event))
  113. instance = self.instances[name]
  114. instance.handlers[e_context.event](e_context, *args, **kwargs)
  115. return e_context
  116. def set_plugin_priority(self, name:str, priority:int):
  117. name = name.upper()
  118. if name not in self.plugins:
  119. return False
  120. if self.plugins[name].priority == priority:
  121. return True
  122. self.plugins[name].priority = priority
  123. self.plugins._update_heap(name)
  124. rawname = self.plugins[name].name
  125. self.pconf["plugins"][rawname]["priority"] = priority
  126. self.pconf["plugins"]._update_heap(rawname)
  127. self.save_config()
  128. self.refresh_order()
  129. return True
  130. def enable_plugin(self, name:str):
  131. name = name.upper()
  132. if name not in self.plugins:
  133. return False
  134. if not self.plugins[name].enabled :
  135. self.plugins[name].enabled = True
  136. rawname = self.plugins[name].name
  137. self.pconf["plugins"][rawname]["enabled"] = True
  138. self.save_config()
  139. self.activate_plugins()
  140. return True
  141. return True
  142. def disable_plugin(self, name:str):
  143. name = name.upper()
  144. if name not in self.plugins:
  145. return False
  146. if self.plugins[name].enabled :
  147. self.plugins[name].enabled = False
  148. rawname = self.plugins[name].name
  149. self.pconf["plugins"][rawname]["enabled"] = False
  150. self.save_config()
  151. return True
  152. return True
  153. def list_plugins(self):
  154. return self.plugins