update_external_bangs.py 4.6 KB

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