__init__.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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(
  45. "failed to copy plugin resource {0} for plugin {1}".format(
  46. file_name, name
  47. )
  48. )
  49. sys.exit(3)
  50. # returning with the web path of the resource
  51. return join("plugins/external_plugins", plugin_dir, file_name)
  52. def prepare_package_resources(plugin, plugin_module_name):
  53. plugin_base_path = dirname(abspath(plugin.__file__))
  54. plugin_dir = plugin_module_name
  55. target_dir = join(
  56. settings["ui"]["static_path"], "plugins/external_plugins", plugin_dir
  57. )
  58. try:
  59. makedirs(target_dir, exist_ok=True)
  60. except IOError:
  61. logger.critical(
  62. "failed to create resource directory {0} for plugin {1}".format(
  63. target_dir, plugin_module_name
  64. )
  65. )
  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(
  72. plugin_base_path, x, plugin_module_name, target_dir, plugin_dir
  73. ) for x in plugin.js_dependencies
  74. ])
  75. if hasattr(plugin, "css_dependencies"):
  76. resources.extend(map(basename, plugin.css_dependencies))
  77. plugin.css_dependencies = ([
  78. sync_resource(
  79. plugin_base_path, x, plugin_module_name, target_dir, plugin_dir
  80. ) for x in plugin.css_dependencies
  81. ])
  82. for f in listdir(target_dir):
  83. if basename(f) not in resources:
  84. resource_path = join(target_dir, basename(f))
  85. try:
  86. remove(resource_path)
  87. except IOError:
  88. logger.critical(
  89. "failed to remove unused resource file {0} for plugin {1}".format(
  90. resource_path, plugin_module_name
  91. )
  92. )
  93. sys.exit(3)
  94. def load_plugin(plugin_module_name, external):
  95. # pylint: disable=too-many-branches
  96. try:
  97. plugin = import_module(plugin_module_name)
  98. except (
  99. SyntaxError,
  100. KeyboardInterrupt,
  101. SystemExit,
  102. SystemError,
  103. ImportError,
  104. RuntimeError,
  105. ) as e:
  106. logger.critical("%s: fatal exception", plugin_module_name, exc_info=e)
  107. sys.exit(3)
  108. except BaseException:
  109. logger.exception("%s: exception while loading, the plugin is disabled", plugin_module_name)
  110. return None
  111. # difference with searx: use module name instead of the user name
  112. plugin.id = plugin_module_name
  113. #
  114. plugin.logger = getLogger(plugin_module_name)
  115. for plugin_attr, plugin_attr_type in required_attrs:
  116. if not hasattr(plugin, plugin_attr):
  117. logger.critical(
  118. '%s: missing attribute "%s", cannot load plugin', plugin, plugin_attr
  119. )
  120. sys.exit(3)
  121. attr = getattr(plugin, plugin_attr)
  122. if not isinstance(attr, plugin_attr_type):
  123. type_attr = str(type(attr))
  124. logger.critical(
  125. '{1}: attribute "{0}" is of type {2}, must be of type {3}, cannot load plugin'.format(
  126. plugin, plugin_attr, type_attr, plugin_attr_type
  127. )
  128. )
  129. sys.exit(3)
  130. for plugin_attr, plugin_attr_type in optional_attrs:
  131. if not hasattr(plugin, plugin_attr) or not isinstance(
  132. getattr(plugin, plugin_attr), plugin_attr_type
  133. ):
  134. setattr(plugin, plugin_attr, plugin_attr_type())
  135. if not hasattr(plugin, "preference_section"):
  136. plugin.preference_section = "general"
  137. # query plugin
  138. if plugin.preference_section == "query":
  139. for plugin_attr in ("query_keywords", "query_examples"):
  140. if not hasattr(plugin, plugin_attr):
  141. logger.critical(
  142. 'missing attribute "{0}", cannot load plugin: {1}'.format(
  143. plugin_attr, plugin
  144. )
  145. )
  146. sys.exit(3)
  147. if settings.get("enabled_plugins"):
  148. # searx compatibility: plugin.name in settings['enabled_plugins']
  149. plugin.default_on = (
  150. plugin.name in settings["enabled_plugins"]
  151. or plugin.id in settings["enabled_plugins"]
  152. )
  153. # copy ressources if this is an external plugin
  154. if external:
  155. prepare_package_resources(plugin, plugin_module_name)
  156. logger.debug("%s: loaded", plugin_module_name)
  157. return plugin
  158. def load_and_initialize_plugin(plugin_module_name, external, init_args):
  159. plugin = load_plugin(plugin_module_name, external)
  160. if plugin and hasattr(plugin, 'init'):
  161. try:
  162. return plugin if plugin.init(*init_args) else None
  163. except Exception: # pylint: disable=broad-except
  164. plugin.logger.exception(
  165. "Exception while calling init, the plugin is disabled"
  166. )
  167. return None
  168. return plugin
  169. class PluginStore:
  170. def __init__(self):
  171. self.plugins = []
  172. def __iter__(self):
  173. for plugin in self.plugins:
  174. yield plugin
  175. def register(self, plugin):
  176. self.plugins.append(plugin)
  177. def call(self, ordered_plugin_list, plugin_type, *args, **kwargs):
  178. # pylint: disable=no-self-use
  179. ret = True
  180. for plugin in ordered_plugin_list:
  181. if hasattr(plugin, plugin_type):
  182. try:
  183. ret = getattr(plugin, plugin_type)(*args, **kwargs)
  184. if not ret:
  185. break
  186. except Exception: # pylint: disable=broad-except
  187. plugin.logger.exception("Exception while calling %s", plugin_type)
  188. return ret
  189. plugins = PluginStore()
  190. def plugin_module_names():
  191. yield_plugins = set()
  192. # embedded plugins
  193. for module in iter_modules(path=[dirname(__file__)]):
  194. yield (__name__ + "." + module.name, False)
  195. yield_plugins.add(module.name)
  196. # external plugins
  197. for module_name in settings['plugins']:
  198. if module_name not in yield_plugins:
  199. yield (module_name, True)
  200. yield_plugins.add(module_name)
  201. def initialize(app):
  202. for module_name, external in plugin_module_names():
  203. plugin = load_and_initialize_plugin(module_name, external, (app, settings))
  204. if plugin:
  205. plugins.register(plugin)