duckduckgo_weather.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. DuckDuckGo Weather
  4. ~~~~~~~~~~~~~~~~~~
  5. """
  6. from typing import TYPE_CHECKING
  7. from json import loads
  8. from urllib.parse import quote
  9. from dateutil import parser as date_parser
  10. from flask_babel import gettext
  11. from searx.engines.duckduckgo import fetch_traits # pylint: disable=unused-import
  12. from searx.engines.duckduckgo import get_ddg_lang
  13. from searx.enginelib.traits import EngineTraits
  14. if TYPE_CHECKING:
  15. import logging
  16. logger: logging.Logger
  17. traits: EngineTraits
  18. about = {
  19. "website": 'https://duckduckgo.com/',
  20. "wikidata_id": 'Q12805',
  21. "official_api_documentation": None,
  22. "use_official_api": True,
  23. "require_api_key": False,
  24. "results": "JSON",
  25. }
  26. send_accept_language_header = True
  27. # engine dependent config
  28. categories = ["weather"]
  29. URL = "https://duckduckgo.com/js/spice/forecast/{query}/{lang}"
  30. def generate_condition_table(condition):
  31. res = ""
  32. res += f"<tr><td><b>{gettext('Condition')}</b></td>" f"<td><b>{condition['conditionCode']}</b></td></tr>"
  33. res += (
  34. f"<tr><td><b>{gettext('Temperature')}</b></td>"
  35. f"<td><b>{condition['temperature']}°C / {c_to_f(condition['temperature'])}°F</b></td></tr>"
  36. )
  37. res += (
  38. f"<tr><td>{gettext('Feels like')}</td><td>{condition['temperatureApparent']}°C / "
  39. f"{c_to_f(condition['temperatureApparent'])}°F</td></tr>"
  40. )
  41. res += (
  42. f"<tr><td>{gettext('Wind')}</td><td>{condition['windDirection']}° — "
  43. f"{(condition['windSpeed'] * 1.6093440006147):.2f} km/h / {condition['windSpeed']} mph</td></tr>"
  44. )
  45. res += f"<tr><td>{gettext('Visibility')}</td><td>{condition['visibility']} m</td>"
  46. res += f"<tr><td>{gettext('Humidity')}</td><td>{(condition['humidity'] * 100):.1f}%</td></tr>"
  47. return res
  48. def generate_day_table(day):
  49. res = ""
  50. res += (
  51. f"<tr><td>{gettext('Min temp.')}</td><td>{day['temperatureMin']}°C / "
  52. f"{c_to_f(day['temperatureMin'])}°F</td></tr>"
  53. )
  54. res += (
  55. f"<tr><td>{gettext('Max temp.')}</td><td>{day['temperatureMax']}°C / "
  56. f"{c_to_f(day['temperatureMax'])}°F</td></tr>"
  57. )
  58. res += f"<tr><td>{gettext('UV index')}</td><td>{day['maxUvIndex']}</td></tr>"
  59. res += f"<tr><td>{gettext('Sunrise')}</td><td>{date_parser.parse(day['sunrise']).strftime('%H:%M')}</td></tr>"
  60. res += f"<tr><td>{gettext('Sunset')}</td><td>{date_parser.parse(day['sunset']).strftime('%H:%M')}</td></tr>"
  61. return res
  62. def request(query, params):
  63. eng_region = traits.get_region(params['searxng_locale'], traits.all_locale)
  64. eng_lang = get_ddg_lang(traits, params['searxng_locale'])
  65. # !ddw paris :es-AR --> {'ad': 'es_AR', 'ah': 'ar-es', 'l': 'ar-es'}
  66. params['cookies']['ad'] = eng_lang
  67. params['cookies']['ah'] = eng_region
  68. params['cookies']['l'] = eng_region
  69. logger.debug("cookies: %s", params['cookies'])
  70. params["url"] = URL.format(query=quote(query), lang=eng_lang.split('_')[0])
  71. return params
  72. def c_to_f(temperature):
  73. return "%.2f" % ((temperature * 1.8) + 32)
  74. def response(resp):
  75. results = []
  76. if resp.text.strip() == "ddg_spice_forecast();":
  77. return []
  78. result = loads(resp.text[resp.text.find('\n') + 1 : resp.text.rfind('\n') - 2])
  79. current = result["currentWeather"]
  80. title = result['location']
  81. infobox = f"<h3>{gettext('Current condition')}</h3><table><tbody>"
  82. infobox += generate_condition_table(current)
  83. infobox += "</tbody></table>"
  84. last_date = None
  85. for time in result['forecastHourly']['hours']:
  86. current_time = date_parser.parse(time['forecastStart'])
  87. if last_date != current_time.date():
  88. if last_date is not None:
  89. infobox += "</tbody></table>"
  90. infobox += f"<h3>{current_time.strftime('%Y-%m-%d')}</h3>"
  91. infobox += "<table><tbody>"
  92. for day in result['forecastDaily']['days']:
  93. if date_parser.parse(day['forecastStart']).date() == current_time.date():
  94. infobox += generate_day_table(day)
  95. infobox += "</tbody></table><table><tbody>"
  96. last_date = current_time.date()
  97. infobox += f"<tr><td rowspan=\"7\"><b>{current_time.strftime('%H:%M')}</b></td></tr>"
  98. infobox += generate_condition_table(time)
  99. infobox += "</tbody></table>"
  100. results.append(
  101. {
  102. "infobox": title,
  103. "content": infobox,
  104. }
  105. )
  106. return results