mediawiki.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. General mediawiki-engine (Web)
  4. """
  5. from json import loads
  6. from string import Formatter
  7. from urllib.parse import urlencode, quote
  8. # about
  9. about = {
  10. "website": None,
  11. "wikidata_id": None,
  12. "official_api_documentation": 'http://www.mediawiki.org/wiki/API:Search',
  13. "use_official_api": True,
  14. "require_api_key": False,
  15. "results": 'JSON',
  16. }
  17. # engine dependent config
  18. categories = ['general']
  19. paging = True
  20. number_of_results = 1
  21. search_type = 'nearmatch' # possible values: title, text, nearmatch
  22. # search-url
  23. base_url = 'https://{language}.wikipedia.org/'
  24. search_postfix = 'w/api.php?action=query'\
  25. '&list=search'\
  26. '&{query}'\
  27. '&format=json'\
  28. '&sroffset={offset}'\
  29. '&srlimit={limit}'\
  30. '&srwhat={searchtype}'
  31. # do search-request
  32. def request(query, params):
  33. offset = (params['pageno'] - 1) * number_of_results
  34. string_args = dict(query=urlencode({'srsearch': query}),
  35. offset=offset,
  36. limit=number_of_results,
  37. searchtype=search_type)
  38. format_strings = list(Formatter().parse(base_url))
  39. if params['language'] == 'all':
  40. language = 'en'
  41. else:
  42. language = params['language'].split('-')[0]
  43. # format_string [('https://', 'language', '', None), ('.wikipedia.org/', None, None, None)]
  44. if any(x[1] == 'language' for x in format_strings):
  45. string_args['language'] = language
  46. # write search-language back to params, required in response
  47. params['language'] = language
  48. search_url = base_url + search_postfix
  49. params['url'] = search_url.format(**string_args)
  50. return params
  51. # get response from search-request
  52. def response(resp):
  53. results = []
  54. search_results = loads(resp.text)
  55. # return empty array if there are no results
  56. if not search_results.get('query', {}).get('search'):
  57. return []
  58. # parse results
  59. for result in search_results['query']['search']:
  60. if result.get('snippet', '').startswith('#REDIRECT'):
  61. continue
  62. url = base_url.format(language=resp.search_params['language']) +\
  63. 'wiki/' + quote(result['title'].replace(' ', '_').encode())
  64. # append result
  65. results.append({'url': url,
  66. 'title': result['title'],
  67. 'content': ''})
  68. # return results
  69. return results