search_operators.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import shlex
  2. import string
  3. from flask_babel import gettext
  4. name = gettext("Search operators")
  5. description = gettext("""Filter results using hyphen, site: and -site:.
  6. Please note that you might get less results with the additional filtering.""")
  7. default_on = False
  8. def on_result(request, search, result):
  9. q = search.search_query.query
  10. # WARN: shlex.quote is designed only for Unix shells and may be vulnerable
  11. # to command injection on non-POSIX compliant shells (Windows)
  12. # https://docs.python.org/3/library/shlex.html#shlex.quote
  13. squote = shlex.quote(q)
  14. qs = shlex.split(squote)
  15. spitems = [x.lower() for x in qs if ' ' in x]
  16. mitems = [x.lower() for x in qs if x.startswith('-')]
  17. siteitems = [x.lower() for x in qs if x.startswith('site:')]
  18. msiteitems = [x.lower() for x in qs if x.startswith('-site:')]
  19. url, title, content = (
  20. result["url"].lower(),
  21. result["title"].lower(),
  22. (result.get("content").lower() if result.get("content") else '')
  23. )
  24. if all((x not in title or x not in content) for x in spitems):
  25. return False
  26. if all((x in title or x in content) for x in mitems):
  27. return False
  28. if all(x not in url for x in siteitems):
  29. return False
  30. if all(x in url for x in msiteitems):
  31. return False
  32. return True