hash_plugin.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring, missing-class-docstring
  3. from __future__ import annotations
  4. import typing
  5. import re
  6. import hashlib
  7. from flask_babel import gettext
  8. from searx.plugins import Plugin, PluginInfo
  9. from searx.result_types import EngineResults
  10. if typing.TYPE_CHECKING:
  11. from searx.search import SearchWithPlugins
  12. from searx.extended_types import SXNG_Request
  13. from searx.plugins import PluginCfg
  14. class SXNGPlugin(Plugin):
  15. """Plugin converts strings to different hash digests. The results are
  16. displayed in area for the "answers".
  17. """
  18. id = "hash_plugin"
  19. keywords = ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"]
  20. def __init__(self, plg_cfg: "PluginCfg") -> None:
  21. super().__init__(plg_cfg)
  22. self.parser_re = re.compile(f"({'|'.join(self.keywords)}) (.*)", re.I)
  23. self.info = PluginInfo(
  24. id=self.id,
  25. name=gettext("Hash plugin"),
  26. description=gettext(
  27. "Converts strings to different hash digests. Available functions: md5, sha1, sha224, sha256, sha384, sha512." # pylint:disable=line-too-long
  28. ),
  29. examples=["sha512 The quick brown fox jumps over the lazy dog"],
  30. preference_section="query",
  31. )
  32. def post_search(self, request: "SXNG_Request", search: "SearchWithPlugins") -> EngineResults:
  33. """Returns a result list only for the first page."""
  34. results = EngineResults()
  35. if search.search_query.pageno > 1:
  36. return results
  37. m = self.parser_re.match(search.search_query.query)
  38. if not m:
  39. # wrong query
  40. return results
  41. function, string = m.groups()
  42. if not string.strip():
  43. # end if the string is empty
  44. return results
  45. # select hash function
  46. f = hashlib.new(function.lower())
  47. # make digest from the given string
  48. f.update(string.encode("utf-8").strip())
  49. answer = function + " " + gettext("hash digest") + ": " + f.hexdigest()
  50. results.add(results.types.Answer(answer=answer))
  51. return results