hash_plugin.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. class SXNGPlugin(Plugin):
  14. """Plugin converts strings to different hash digests. The results are
  15. displayed in area for the "answers".
  16. """
  17. id = "hash_plugin"
  18. default_on = True
  19. keywords = ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"]
  20. def __init__(self):
  21. super().__init__()
  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("Converts strings to different hash digests."),
  27. examples=["sha512 The quick brown fox jumps over the lazy dog"],
  28. preference_section="query",
  29. )
  30. def post_search(self, request: "SXNG_Request", search: "SearchWithPlugins") -> EngineResults:
  31. """Returns a result list only for the first page."""
  32. results = EngineResults()
  33. if search.search_query.pageno > 1:
  34. return results
  35. m = self.parser_re.match(search.search_query.query)
  36. if not m:
  37. # wrong query
  38. return results
  39. function, string = m.groups()
  40. if not string.strip():
  41. # end if the string is empty
  42. return results
  43. # select hash function
  44. f = hashlib.new(function.lower())
  45. # make digest from the given string
  46. f.update(string.encode("utf-8").strip())
  47. answer = function + " " + gettext("hash digest") + ": " + f.hexdigest()
  48. results.add(results.types.Answer(answer=answer))
  49. return results