__init__.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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.path import abspath, basename, dirname, exists, join
  17. from shutil import copyfile
  18. from sys import exit, version_info
  19. from traceback import print_exc
  20. from searx import logger, settings, static_path
  21. if version_info[0] == 3:
  22. unicode = str
  23. logger = logger.getChild('plugins')
  24. from searx.plugins import (oa_doi_rewrite,
  25. https_rewrite,
  26. infinite_scroll,
  27. open_results_on_new_tab,
  28. self_info,
  29. search_on_category_select,
  30. tracker_url_remover,
  31. vim_hotkeys)
  32. required_attrs = (('name', (str, unicode)),
  33. ('description', (str, unicode)),
  34. ('default_on', bool))
  35. optional_attrs = (('js_dependencies', tuple),
  36. ('css_dependencies', tuple))
  37. class Plugin():
  38. default_on = False
  39. name = 'Default plugin'
  40. description = 'Default plugin description'
  41. class PluginStore():
  42. def __init__(self):
  43. self.plugins = []
  44. def __iter__(self):
  45. for plugin in self.plugins:
  46. yield plugin
  47. def register(self, *plugins, external=False):
  48. if external:
  49. plugins = load_external_plugins(plugins)
  50. for plugin in plugins:
  51. for plugin_attr, plugin_attr_type in required_attrs:
  52. if not hasattr(plugin, plugin_attr) or not isinstance(getattr(plugin, plugin_attr), plugin_attr_type):
  53. logger.critical('missing attribute "{0}", cannot load plugin: {1}'.format(plugin_attr, plugin))
  54. exit(3)
  55. for plugin_attr, plugin_attr_type in optional_attrs:
  56. if not hasattr(plugin, plugin_attr) or not isinstance(getattr(plugin, plugin_attr), plugin_attr_type):
  57. setattr(plugin, plugin_attr, plugin_attr_type())
  58. plugin.id = plugin.name.replace(' ', '_')
  59. self.plugins.append(plugin)
  60. def call(self, ordered_plugin_list, plugin_type, request, *args, **kwargs):
  61. ret = True
  62. for plugin in ordered_plugin_list:
  63. if hasattr(plugin, plugin_type):
  64. ret = getattr(plugin, plugin_type)(request, *args, **kwargs)
  65. if not ret:
  66. break
  67. return ret
  68. def load_external_plugins(plugin_names):
  69. plugins = []
  70. for name in plugin_names:
  71. logger.debug('loading plugin: {0}'.format(name))
  72. try:
  73. pkg = import_module(name)
  74. except Exception as e:
  75. logger.critical('failed to load plugin module {0}: {1}'.format(name, e))
  76. exit(3)
  77. pkg.__base_path = dirname(abspath(pkg.__file__))
  78. fix_package_resources(pkg, name)
  79. plugins.append(pkg)
  80. logger.debug('plugin "{0}" loaded'.format(name))
  81. return plugins
  82. def check_resource(base_path, resource_path, name, dir_prefix):
  83. dep_path = join(base_path, resource_path)
  84. file_name = basename(dep_path)
  85. resource_name = '{0}_{1}'.format('_'.join(name.split()), file_name)
  86. resource_path = join(static_path, 'plugins', dir_prefix, resource_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. except:
  91. logger.critical('failed to copy plugin resource {0} for plugin {1}'.format(resource_name, name))
  92. exit(3)
  93. # returning with the web path of the resource
  94. return join('plugins', dir_prefix, resource_name)
  95. def fix_package_resources(pkg, name):
  96. if hasattr(pkg, 'js_dependencies'):
  97. pkg.js_dependencies = tuple([
  98. check_resource(pkg.__base_path, x, name, 'js')
  99. for x in pkg.js_dependencies
  100. ])
  101. if hasattr(pkg, 'css_dependencies'):
  102. pkg.css_dependencies = tuple([
  103. check_resource(pkg.__base_path, x, name, 'css')
  104. for x in pkg.css_dependencies
  105. ])
  106. def sha_sum(filename):
  107. with open(filename,"rb") as f:
  108. bytes = f.read() # read entire file as bytes
  109. return sha256(bytes).hexdigest()
  110. plugins = PluginStore()
  111. plugins.register(oa_doi_rewrite)
  112. plugins.register(https_rewrite)
  113. plugins.register(infinite_scroll)
  114. plugins.register(open_results_on_new_tab)
  115. plugins.register(self_info)
  116. plugins.register(search_on_category_select)
  117. plugins.register(tracker_url_remover)
  118. plugins.register(vim_hotkeys)
  119. # load external plugins
  120. if 'plugins' in settings:
  121. plugins.register(*settings['plugins'], external=True)