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

153 行
5.9KB

  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] = 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. if name not in pconf["plugins"]:
  63. new_plugins.append(plugincls)
  64. modified = True
  65. logger.info("Plugin %s not found in pconfig, adding to pconfig..." % name)
  66. pconf["plugins"][name] = {"enabled": plugincls.enabled, "priority": plugincls.priority}
  67. else:
  68. self.plugins[name].enabled = pconf["plugins"][name]["enabled"]
  69. self.plugins[name].priority = pconf["plugins"][name]["priority"]
  70. self.plugins._update_heap(name) # 更新下plugins中的顺序
  71. if modified:
  72. self.save_config()
  73. return new_plugins
  74. def refresh_order(self):
  75. for event in self.listening_plugins.keys():
  76. self.listening_plugins[event].sort(key=lambda name: self.plugins[name].priority, reverse=True)
  77. def activate_plugins(self): # 生成新开启的插件实例
  78. for name, plugincls in self.plugins.items():
  79. if plugincls.enabled:
  80. if name not in self.instances:
  81. instance = plugincls()
  82. self.instances[name] = instance
  83. for event in instance.handlers:
  84. if event not in self.listening_plugins:
  85. self.listening_plugins[event] = []
  86. self.listening_plugins[event].append(name)
  87. self.refresh_order()
  88. def load_plugins(self):
  89. self.load_config()
  90. self.scan_plugins()
  91. pconf = self.pconf
  92. logger.debug("plugins.json config={}".format(pconf))
  93. for name,plugin in pconf["plugins"].items():
  94. if name not in self.plugins:
  95. logger.error("Plugin %s not found, but found in plugins.json" % name)
  96. self.activate_plugins()
  97. def emit_event(self, e_context: EventContext, *args, **kwargs):
  98. if e_context.event in self.listening_plugins:
  99. for name in self.listening_plugins[e_context.event]:
  100. if self.plugins[name].enabled and e_context.action == EventAction.CONTINUE:
  101. logger.debug("Plugin %s triggered by event %s" % (name,e_context.event))
  102. instance = self.instances[name]
  103. instance.handlers[e_context.event](e_context, *args, **kwargs)
  104. return e_context
  105. def set_plugin_priority(self,name,priority):
  106. if name not in self.plugins:
  107. return False
  108. if self.plugins[name].priority == priority:
  109. return True
  110. self.plugins[name].priority = priority
  111. self.plugins._update_heap(name)
  112. self.pconf["plugins"][name]["priority"] = priority
  113. self.pconf["plugins"]._update_heap(name)
  114. self.save_config()
  115. self.refresh_order()
  116. return True
  117. def enable_plugin(self,name):
  118. if name not in self.plugins:
  119. return False
  120. if not self.plugins[name].enabled :
  121. self.plugins[name].enabled = True
  122. self.pconf["plugins"][name]["enabled"] = True
  123. self.save_config()
  124. self.activate_plugins()
  125. return True
  126. return True
  127. def disable_plugin(self,name):
  128. if name not in self.plugins:
  129. return False
  130. if self.plugins[name].enabled :
  131. self.plugins[name].enabled = False
  132. self.pconf["plugins"][name]["enabled"] = False
  133. self.save_config()
  134. return True
  135. return True
  136. def list_plugins(self):
  137. return self.plugins