update_external_bangs.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. #!/usr/bin/env python
  2. # lint: pylint
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. """
  5. Update searx/data/external_bangs.json using the duckduckgo bangs.
  6. https://duckduckgo.com/newbang loads
  7. * a javascript which provides the bang version ( https://duckduckgo.com/bv1.js )
  8. * a JSON file which contains the bangs ( https://duckduckgo.com/bang.v260.js for example )
  9. This script loads the javascript, then the bangs.
  10. The javascript URL may change in the future ( for example https://duckduckgo.com/bv2.js ),
  11. but most probably it will requires to update RE_BANG_VERSION
  12. """
  13. # pylint: disable=C0116
  14. import json
  15. import re
  16. from os.path import join
  17. import httpx
  18. from searx import searx_dir # pylint: disable=E0401 C0413
  19. # from https://duckduckgo.com/newbang
  20. URL_BV1 = 'https://duckduckgo.com/bv1.js'
  21. RE_BANG_VERSION = re.compile(r'\/bang\.v([0-9]+)\.js')
  22. HTTPS_COLON = 'https:'
  23. HTTP_COLON = 'http:'
  24. def get_bang_url():
  25. response = httpx.get(URL_BV1)
  26. response.raise_for_status()
  27. r = RE_BANG_VERSION.findall(response.text)
  28. return f'https://duckduckgo.com/bang.v{r[0]}.js', r[0]
  29. def fetch_ddg_bangs(url):
  30. response = httpx.get(url)
  31. response.raise_for_status()
  32. return json.loads(response.content.decode())
  33. def merge_when_no_leaf(node):
  34. """Minimize the number of nodes
  35. A -> B -> C
  36. B is child of A
  37. C is child of B
  38. If there are no C equals to '*', then each C are merged into A
  39. For example:
  40. d -> d -> g -> * (ddg*)
  41. -> i -> g -> * (dig*)
  42. becomes
  43. d -> dg -> *
  44. -> ig -> *
  45. """
  46. restart = False
  47. if not isinstance(node, dict):
  48. return
  49. # create a copy of the keys so node can be modified
  50. keys = list(node.keys())
  51. for key in keys:
  52. if key == '*':
  53. continue
  54. value = node[key]
  55. value_keys = list(value.keys())
  56. if '*' not in value_keys:
  57. for value_key in value_keys:
  58. node[key + value_key] = value[value_key]
  59. merge_when_no_leaf(node[key + value_key])
  60. del node[key]
  61. restart = True
  62. else:
  63. merge_when_no_leaf(value)
  64. if restart:
  65. merge_when_no_leaf(node)
  66. def optimize_leaf(parent, parent_key, node):
  67. if not isinstance(node, dict):
  68. return
  69. if len(node) == 1 and '*' in node and parent is not None:
  70. parent[parent_key] = node['*']
  71. else:
  72. for key, value in node.items():
  73. optimize_leaf(node, key, value)
  74. def parse_ddg_bangs(ddg_bangs):
  75. bang_trie = {}
  76. bang_urls = {}
  77. for bang_definition in ddg_bangs:
  78. # bang_list
  79. bang_url = bang_definition['u']
  80. if '{{{s}}}' not in bang_url:
  81. # ignore invalid bang
  82. continue
  83. bang_url = bang_url.replace('{{{s}}}', chr(2))
  84. # only for the https protocol: "https://example.com" becomes "//example.com"
  85. if bang_url.startswith(HTTPS_COLON + '//'):
  86. bang_url = bang_url[len(HTTPS_COLON):]
  87. #
  88. if bang_url.startswith(HTTP_COLON + '//') and bang_url[len(HTTP_COLON):] in bang_urls:
  89. # if the bang_url uses the http:// protocol, and the same URL exists in https://
  90. # then reuse the https:// bang definition. (written //example.com)
  91. bang_def_output = bang_urls[bang_url[len(HTTP_COLON):]]
  92. else:
  93. # normal use case : new http:// URL or https:// URL (without "https:", see above)
  94. bang_rank = str(bang_definition['r'])
  95. bang_def_output = bang_url + chr(1) + bang_rank
  96. bang_def_output = bang_urls.setdefault(bang_url, bang_def_output)
  97. bang_urls[bang_url] = bang_def_output
  98. # bang name
  99. bang = bang_definition['t']
  100. # bang_trie
  101. t = bang_trie
  102. for bang_letter in bang:
  103. t = t.setdefault(bang_letter, {})
  104. t = t.setdefault('*', bang_def_output)
  105. # optimize the trie
  106. merge_when_no_leaf(bang_trie)
  107. optimize_leaf(None, None, bang_trie)
  108. return bang_trie
  109. def get_bangs_filename():
  110. return join(join(searx_dir, "data"), "external_bangs.json")
  111. if __name__ == '__main__':
  112. bangs_url, bangs_version = get_bang_url()
  113. print(f'fetch bangs from {bangs_url}')
  114. output = {
  115. 'version': bangs_version,
  116. 'trie': parse_ddg_bangs(fetch_ddg_bangs(bangs_url))
  117. }
  118. with open(get_bangs_filename(), 'w', encoding="utf8") as fp:
  119. json.dump(output, fp, ensure_ascii=False, indent=4)