__init__.py 7.7 KB

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