1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
"""Geolocation + sunrise/sunset lookup with a manual-refresh JSON cache."""
from __future__ import annotations
import json
import urllib.request
from datetime import datetime, tzinfo
from pathlib import Path
from typing import Optional
def to_local_hm(iso_utc: str, tz: Optional[tzinfo] = None) -> str:
"""Convert an ISO-8601 UTC timestamp to local HH:MM."""
dt = datetime.fromisoformat(iso_utc)
local = dt.astimezone(tz) # tz=None -> system local zone
return local.strftime("%H:%M")
def read_cache(path: Path) -> Optional[dict]:
path = Path(path)
if not path.exists():
return None
try:
return json.loads(path.read_text())
except (json.JSONDecodeError, OSError):
return None
def write_cache(payload: dict, path: Path) -> None:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2))
GEO_URL = "http://ip-api.com/json"
SUN_URL = "https://api.sunrise-sunset.org/json?lat={lat}&lng={lon}&formatted=0"
# sunrise-sunset.org is behind Cloudflare, which returns 403 (error 1010) for
# the default Python-urllib User-Agent. Send a normal UA so requests get through.
_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) hyprsunset-qt"
def _http_get(url: str, timeout: float = 10.0) -> str:
req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.read().decode()
def geolocate() -> tuple[str, str]:
"""Return (lat, lon) as strings from IP geolocation."""
data = json.loads(_http_get(GEO_URL))
return str(data["lat"]), str(data["lon"])
def fetch_sun(lat: str, lon: str) -> dict:
"""Fetch sunrise/sunset JSON for coords. Caller handles caching."""
url = SUN_URL.format(lat=lat, lon=lon)
return json.loads(_http_get(url))
|