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