__init__.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. '''
  2. searx is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU Affero General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. searx is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU Affero General Public License for more details.
  10. You should have received a copy of the GNU Affero General Public License
  11. along with searx. If not, see < http://www.gnu.org/licenses/ >.
  12. (C) 2015 by Adam Tauber, <asciimoo@gmail.com>
  13. '''
  14. from hashlib import sha256
  15. from importlib import import_module
  16. from os import listdir, makedirs, remove, stat, utime
  17. from os.path import abspath, basename, dirname, exists, join
  18. from shutil import copyfile
  19. from sys import version_info
  20. from traceback import print_exc
  21. from searx import logger, settings, static_path
  22. if version_info[0] == 3:
  23. unicode = str
  24. logger = logger.getChild('plugins')
  25. from searx.plugins import (oa_doi_rewrite,
  26. https_rewrite,
  27. infinite_scroll,
  28. open_results_on_new_tab,
  29. self_info,
  30. search_on_category_select,
  31. tracker_url_remover,
  32. vim_hotkeys)
  33. required_attrs = (('name', (str, unicode)),
  34. ('description', (str, unicode)),
  35. ('default_on', bool))
  36. optional_attrs = (('js_dependencies', tuple),
  37. ('css_dependencies', tuple))
  38. class Plugin():
  39. default_on = False
  40. name = 'Default plugin'
  41. description = 'Default plugin description'
  42. class PluginStore():
  43. def __init__(self):
  44. self.plugins = []
  45. def __iter__(self):
  46. for plugin in self.plugins:
  47. yield plugin
  48. def register(self, *plugins, external=False):
  49. if external:
  50. plugins = load_external_plugins(plugins)
  51. for plugin in plugins:
  52. for plugin_attr, plugin_attr_type in required_attrs:
  53. if not hasattr(plugin, plugin_attr) or not isinstance(getattr(plugin, plugin_attr), plugin_attr_type):
  54. logger.critical('missing attribute "{0}", cannot load plugin: {1}'.format(plugin_attr, plugin))
  55. exit(3)
  56. for plugin_attr, plugin_attr_type in optional_attrs:
  57. if not hasattr(plugin, plugin_attr) or not isinstance(getattr(plugin, plugin_attr), plugin_attr_type):
  58. setattr(plugin, plugin_attr, plugin_attr_type())
  59. plugin.id = plugin.name.replace(' ', '_')
  60. self.plugins.append(plugin)
  61. def call(self, ordered_plugin_list, plugin_type, request, *args, **kwargs):
  62. ret = True
  63. for plugin in ordered_plugin_list:
  64. if hasattr(plugin, plugin_type):
  65. ret = getattr(plugin, plugin_type)(request, *args, **kwargs)
  66. if not ret:
  67. break
  68. return ret
  69. def load_external_plugins(plugin_names):
  70. plugins = []
  71. for name in plugin_names:
  72. logger.debug('loading plugin: {0}'.format(name))
  73. try:
  74. pkg = import_module(name)
  75. except Exception as e:
  76. logger.critical('failed to load plugin module {0}: {1}'.format(name, e))
  77. exit(3)
  78. pkg.__base_path = dirname(abspath(pkg.__file__))
  79. prepare_package_resources(pkg, name)
  80. plugins.append(pkg)
  81. logger.debug('plugin "{0}" loaded'.format(name))
  82. return plugins
  83. def sync_resource(base_path, resource_path, name, target_dir, plugin_dir):
  84. dep_path = join(base_path, resource_path)
  85. file_name = basename(dep_path)
  86. resource_path = join(target_dir, file_name)
  87. if not exists(resource_path) or sha_sum(dep_path) != sha_sum(resource_path):
  88. try:
  89. copyfile(dep_path, resource_path)
  90. # copy atime_ns and mtime_ns, so the weak ETags (generated by
  91. # the HTTP server) do not change
  92. dep_stat = stat(dep_path)
  93. utime(resource_path, ns=(dep_stat.st_atime_ns, dep_stat.st_mtime_ns))
  94. except:
  95. logger.critical('failed to copy plugin resource {0} for plugin {1}'.format(file_name, name))
  96. exit(3)
  97. # returning with the web path of the resource
  98. return join('plugins/external_plugins', plugin_dir, file_name)
  99. def prepare_package_resources(pkg, name):
  100. plugin_dir = 'plugin_' + name
  101. target_dir = join(static_path, 'plugins/external_plugins', plugin_dir)
  102. try:
  103. makedirs(target_dir, exist_ok=True)
  104. except:
  105. logger.critical('failed to create resource directory {0} for plugin {1}'.format(target_dir, name))
  106. exit(3)
  107. resources = []
  108. if hasattr(pkg, 'js_dependencies'):
  109. resources.extend(map(basename, pkg.js_dependencies))
  110. pkg.js_dependencies = tuple([
  111. sync_resource(pkg.__base_path, x, name, target_dir, plugin_dir)
  112. for x in pkg.js_dependencies
  113. ])
  114. if hasattr(pkg, 'css_dependencies'):
  115. resources.extend(map(basename, pkg.css_dependencies))
  116. pkg.css_dependencies = tuple([
  117. sync_resource(pkg.__base_path, x, name, target_dir, plugin_dir)
  118. for x in pkg.css_dependencies
  119. ])
  120. for f in listdir(target_dir):
  121. if basename(f) not in resources:
  122. resource_path = join(target_dir, basename(f))
  123. try:
  124. remove(resource_path)
  125. except:
  126. logger.critical('failed to remove unused resource file {0} for plugin {1}'.format(resource_path, name))
  127. exit(3)
  128. def sha_sum(filename):
  129. with open(filename, "rb") as f:
  130. bytes = f.read()
  131. return sha256(bytes).hexdigest()
  132. plugins = PluginStore()
  133. plugins.register(oa_doi_rewrite)
  134. plugins.register(https_rewrite)
  135. plugins.register(infinite_scroll)
  136. plugins.register(open_results_on_new_tab)
  137. plugins.register(self_info)
  138. plugins.register(search_on_category_select)
  139. plugins.register(tracker_url_remover)
  140. plugins.register(vim_hotkeys)
  141. # load external plugins
  142. if 'plugins' in settings:
  143. plugins.register(*settings['plugins'], external=True)