__init__.py 7.4 KB

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