__init__.py 7.7 KB

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