This commit is contained in:
mjallen18
2025-11-25 10:16:26 -06:00
parent b62f49b362
commit 34181aa0c9
4 changed files with 231 additions and 21 deletions

View File

@@ -16,9 +16,15 @@ let
import json
import shutil
from datetime import datetime, timedelta
import argparse
import requests
parser = argparse.ArgumentParser(prog='waybar-weather')
parser.add_argument('--waybar', action='store_true')
parser.add_argument('--hyprlock', action='store_true')
args = parser.parse_args()
WWO_CODE = {
"113": "Sunny",
"116": "PartlyCloudy",
@@ -281,6 +287,12 @@ let
WEATHER_CODES_WEGO = {key: WEATHER_SYMBOL_WEGO[value] for key, value in WWO_CODE.items()}
CACHE_DIR = os.path.join(os.environ.get("XDG_CACHE_HOME", os.path.expanduser("~/.cache")), "waybar-weather")
CACHE_FILE = os.path.join(CACHE_DIR, "wttr.json")
CACHE_MOON_FILE = os.path.join(CACHE_DIR, "moon.json")
CACHE_MOON_ICON_FILE = os.path.join(CACHE_DIR, "moon-icon")
CACHE_TTL = timedelta(minutes=10)
data = {}
data["text"] = ""
@@ -415,31 +427,93 @@ let
after_sunset = time_24_hr > sunset_hour
return after_sunset or before_sunrise
def get_wttr_json():
def load_cache(path, ttl):
"""Load cached file if it is not too old."""
try:
if not os.path.exists(path):
return None
mtime = datetime.fromtimestamp(os.path.getmtime(path))
if datetime.now() - mtime > ttl:
return None
with open(path, "r") as f:
if path.endswith(".json"):
return json.load(f)
return f.read().strip()
except Exception:
return None
def save_cache(path, data):
"""Write cache file safely."""
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
try:
with open(tmp, "w") as f:
if isinstance(data, dict):
json.dump(data, f)
else:
f.write(str(data))
shutil.move(tmp, path)
except Exception:
pass
def get_wttr_json(hyprlock=False):
"""get the weather json"""
weather = requests.get("https://wttr.in/?u&format=j1", timeout=30).json()
moon = requests.get("https://wttr.in/?format=%m", timeout=30)
moon_icon = moon.text
current_condition = weather["current_condition"][0]
astronomy = weather["weather"][0]['astronomy'][0]
# Try loading cached JSON
cached = load_cache(CACHE_FILE, CACHE_TTL)
cached_moon = load_cache(CACHE_MOON_FILE, CACHE_TTL)
cached_moon_icon = load_cache(CACHE_MOON_ICON_FILE, CACHE_TTL)
text = build_text(current_condition)
if cached and cached_moon and cached_moon_icon:
current_condition = cached
astronomy = cached_moon
moon_icon = cached_moon_icon
else:
weather = requests.get("https://wttr.in/?u&format=j1", timeout=30).json()
moon = requests.get("https://wttr.in/?format=%m", timeout=30)
moon_icon = moon.text
tooltip = build_tooltip(current_condition, astronomy, moon_icon) + build_forecast(weather["weather"])
current_condition = weather["current_condition"][0]
astronomy = weather["weather"][0]['astronomy'][0]
data["text"] = text
data["tooltip"] = tooltip
# Save cache
save_cache(CACHE_FILE, current_condition)
save_cache(CACHE_MOON_FILE, astronomy)
save_cache(CACHE_MOON_ICON_FILE, moon_icon)
return json.dumps(data)
if hyprlock:
return build_tooltip(current_condition, astronomy, moon_icon)
else:
text = build_text(current_condition)
tooltip = build_tooltip(current_condition, astronomy, moon_icon) + build_forecast(weather["weather"])
data["text"] = text
data["tooltip"] = tooltip
return json.dumps(data)
def main():
"""main"""
try:
print(get_wttr_json())
except Exception as e:
print("error")
print(e)
if args.hyprlock:
try:
print(get_wttr_json(hyprlock=True))
except Exception as e:
print("error")
print(e)
else:
try:
print(get_wttr_json())
except Exception as e:
print("error")
print(e)
main()
'';