__init__.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pylint: disable=missing-module-docstring, missing-class-docstring
  4. import sys
  5. from hashlib import sha256
  6. from importlib import import_module
  7. from os import listdir, makedirs, remove, stat, utime
  8. from os.path import abspath, basename, dirname, exists, join
  9. from shutil import copyfile
  10. from pkgutil import iter_modules
  11. from logging import getLogger
  12. from searx import logger, settings
  13. logger = logger.getChild("plugins")
  14. required_attrs = (
  15. ("name", str),
  16. ("description", str),
  17. ("default_on", bool)
  18. )
  19. optional_attrs = (
  20. ("js_dependencies", tuple),
  21. ("css_dependencies", tuple),
  22. ("preference_section", str),
  23. )
  24. def sha_sum(filename):
  25. with open(filename, "rb") as f:
  26. file_content_bytes = f.read()
  27. return sha256(file_content_bytes).hexdigest()
  28. def sync_resource(base_path, resource_path, name, target_dir, plugin_dir):
  29. dep_path = join(base_path, resource_path)
  30. file_name = basename(dep_path)
  31. resource_path = join(target_dir, file_name)
  32. if not exists(resource_path) or sha_sum(dep_path) != sha_sum(resource_path):
  33. try:
  34. copyfile(dep_path, resource_path)
  35. # copy atime_ns and mtime_ns, so the weak ETags (generated by
  36. # the HTTP server) do not change
  37. dep_stat = stat(dep_path)
  38. utime(resource_path, ns=(dep_stat.st_atime_ns, dep_stat.st_mtime_ns))
  39. except IOError:
  40. logger.critical(
  41. "failed to copy plugin resource {0} for plugin {1}".format(
  42. file_name, name
  43. )
  44. )
  45. sys.exit(3)
  46. # returning with the web path of the resource
  47. return join("plugins/external_plugins", plugin_dir, file_name)
  48. def prepare_package_resources(plugin, plugin_module_name):
  49. # pylint: disable=consider-using-generator
  50. plugin_base_path = dirname(abspath(plugin.__file__))
  51. plugin_dir = plugin_module_name
  52. target_dir = join(
  53. settings["ui"]["static_path"], "plugins/external_plugins", plugin_dir
  54. )
  55. try:
  56. makedirs(target_dir, exist_ok=True)
  57. except IOError:
  58. logger.critical(
  59. "failed to create resource directory {0} for plugin {1}".format(
  60. target_dir, plugin_module_name
  61. )
  62. )
  63. sys.exit(3)
  64. resources = []
  65. if hasattr(plugin, "js_dependencies"):
  66. resources.extend(map(basename, plugin.js_dependencies))
  67. plugin.js_dependencies = tuple(
  68. [
  69. sync_resource(
  70. plugin_base_path, x, plugin_module_name, target_dir, plugin_dir
  71. )
  72. for x in plugin.js_dependencies
  73. ]
  74. )
  75. if hasattr(plugin, "css_dependencies"):
  76. resources.extend(map(basename, plugin.css_dependencies))
  77. plugin.css_dependencies = tuple(
  78. [
  79. sync_resource(
  80. plugin_base_path, x, plugin_module_name, target_dir, plugin_dir
  81. )
  82. for x in plugin.css_dependencies
  83. ]
  84. )
  85. for f in listdir(target_dir):
  86. if basename(f) not in resources:
  87. resource_path = join(target_dir, basename(f))
  88. try:
  89. remove(resource_path)
  90. except IOError:
  91. logger.critical(
  92. "failed to remove unused resource file {0} for plugin {1}".format(
  93. resource_path, plugin_module_name
  94. )
  95. )
  96. sys.exit(3)
  97. def load_plugin(plugin_module_name, external):
  98. # pylint: disable=too-many-branches
  99. try:
  100. plugin = import_module(plugin_module_name)
  101. except (
  102. SyntaxError,
  103. KeyboardInterrupt,
  104. SystemExit,
  105. SystemError,
  106. ImportError,
  107. RuntimeError,
  108. ) as e:
  109. logger.critical("%s: fatal exception", plugin_module_name, exc_info=e)
  110. sys.exit(3)
  111. except BaseException:
  112. logger.exception("%s: exception while loading, the plugin is disabled", plugin_module_name)
  113. return None
  114. # difference with searx: use module name instead of the user name
  115. plugin.id = plugin_module_name
  116. #
  117. plugin.logger = getLogger(plugin_module_name)
  118. for plugin_attr, plugin_attr_type in required_attrs:
  119. if not hasattr(plugin, plugin_attr):
  120. logger.critical(
  121. '%s: missing attribute "%s", cannot load plugin', plugin, plugin_attr
  122. )
  123. sys.exit(3)
  124. attr = getattr(plugin, plugin_attr)
  125. if not isinstance(attr, plugin_attr_type):
  126. type_attr = str(type(attr))
  127. logger.critical(
  128. '{1}: attribute "{0}" is of type {2}, must be of type {3}, cannot load plugin'.format(
  129. plugin, plugin_attr, type_attr, plugin_attr_type
  130. )
  131. )
  132. sys.exit(3)
  133. for plugin_attr, plugin_attr_type in optional_attrs:
  134. if not hasattr(plugin, plugin_attr) or not isinstance(
  135. getattr(plugin, plugin_attr), plugin_attr_type
  136. ):
  137. setattr(plugin, plugin_attr, plugin_attr_type())
  138. if not hasattr(plugin, "preference_section"):
  139. plugin.preference_section = "general"
  140. # query plugin
  141. if plugin.preference_section == "query":
  142. for plugin_attr in ("query_keywords", "query_examples"):
  143. if not hasattr(plugin, plugin_attr):
  144. logger.critical(
  145. 'missing attribute "{0}", cannot load plugin: {1}'.format(
  146. plugin_attr, plugin
  147. )
  148. )
  149. sys.exit(3)
  150. if settings.get("enabled_plugins"):
  151. # searx compatibility: plugin.name in settings['enabled_plugins']
  152. plugin.default_on = (
  153. plugin.name in settings["enabled_plugins"]
  154. or plugin.id in settings["enabled_plugins"]
  155. )
  156. # copy ressources if this is an external plugin
  157. if external:
  158. prepare_package_resources(plugin, plugin_module_name)
  159. logger.debug("%s: loaded", plugin_module_name)
  160. return plugin
  161. def load_and_initialize_plugin(plugin_module_name, external, init_args):
  162. plugin = load_plugin(plugin_module_name, external)
  163. if plugin and hasattr(plugin, 'init'):
  164. try:
  165. return plugin if plugin.init(*init_args) else None
  166. except Exception: # pylint: disable=broad-except
  167. plugin.logger.exception(
  168. "Exception while calling init, the plugin is disabled"
  169. )
  170. return None
  171. return plugin
  172. class PluginStore:
  173. def __init__(self):
  174. self.plugins = []
  175. def __iter__(self):
  176. for plugin in self.plugins:
  177. yield plugin
  178. def register(self, plugin):
  179. self.plugins.append(plugin)
  180. def call(self, ordered_plugin_list, plugin_type, *args, **kwargs):
  181. # pylint: disable=no-self-use
  182. ret = True
  183. for plugin in ordered_plugin_list:
  184. if hasattr(plugin, plugin_type):
  185. try:
  186. ret = getattr(plugin, plugin_type)(*args, **kwargs)
  187. if not ret:
  188. break
  189. except Exception: # pylint: disable=broad-except
  190. plugin.logger.exception("Exception while calling %s", plugin_type)
  191. return ret
  192. plugins = PluginStore()
  193. def plugin_module_names():
  194. yield_plugins = set()
  195. # embedded plugins
  196. for module_name in iter_modules(path=[dirname(__file__)]):
  197. yield (module_name, False)
  198. yield_plugins.add(module_name)
  199. # external plugins
  200. for module_name in settings['plugins']:
  201. if module_name not in yield_plugins:
  202. yield (module_name, True)
  203. yield_plugins.add(module_name)
  204. def initialize(app):
  205. for module_name, external in plugin_module_names():
  206. plugin = load_and_initialize_plugin(__name__ + "." + module_name.name, external, (app, settings))
  207. if plugin:
  208. plugins.register(plugin)