oa_doi_rewrite.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring
  3. import re
  4. from urllib.parse import urlparse, parse_qsl
  5. from flask_babel import gettext
  6. from searx import settings
  7. regex = re.compile(r'10\.\d{4,9}/[^\s]+')
  8. name = gettext('Open Access DOI rewrite')
  9. description = gettext('Avoid paywalls by redirecting to open-access versions of publications when available')
  10. default_on = False
  11. preference_section = 'general'
  12. def extract_doi(url):
  13. match = regex.search(url.path)
  14. if match:
  15. return match.group(0)
  16. for _, v in parse_qsl(url.query):
  17. match = regex.search(v)
  18. if match:
  19. return match.group(0)
  20. return None
  21. def get_doi_resolver(preferences):
  22. doi_resolvers = settings['doi_resolvers']
  23. selected_resolver = preferences.get_value('doi_resolver')[0]
  24. if selected_resolver not in doi_resolvers:
  25. selected_resolver = settings['default_doi_resolver']
  26. return doi_resolvers[selected_resolver]
  27. def on_result(request, _search, result):
  28. if 'parsed_url' not in result:
  29. return True
  30. doi = extract_doi(result['parsed_url'])
  31. if doi and len(doi) < 50:
  32. for suffix in ('/', '.pdf', '.xml', '/full', '/meta', '/abstract'):
  33. if doi.endswith(suffix):
  34. doi = doi[: -len(suffix)]
  35. result['url'] = get_doi_resolver(request.preferences) + doi
  36. result['parsed_url'] = urlparse(result['url'])
  37. if 'doi' not in result:
  38. result['doi'] = doi
  39. return True