aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--hyprsunset_qt/sun.py31
-rw-r--r--tests/test_sun.py21
2 files changed, 52 insertions, 0 deletions
diff --git a/hyprsunset_qt/sun.py b/hyprsunset_qt/sun.py
new file mode 100644
index 0000000..bc611f9
--- /dev/null
+++ b/hyprsunset_qt/sun.py
@@ -0,0 +1,31 @@
+"""Geolocation + sunrise/sunset lookup with a manual-refresh JSON cache."""
+
+from __future__ import annotations
+
+import json
+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))
diff --git a/tests/test_sun.py b/tests/test_sun.py
new file mode 100644
index 0000000..2a64632
--- /dev/null
+++ b/tests/test_sun.py
@@ -0,0 +1,21 @@
+import json
+from datetime import timezone
+from zoneinfo import ZoneInfo
+from hyprsunset_qt.sun import to_local_hm, read_cache, write_cache
+
+
+def test_utc_to_local_hm():
+ # 2026-07-17T17:40:00+00:00 -> 19:40 in Europe/Rome (UTC+2 summer)
+ tz = ZoneInfo("Europe/Rome")
+ assert to_local_hm("2026-07-17T17:40:00+00:00", tz) == "19:40"
+
+
+def test_cache_roundtrip(tmp_path):
+ path = tmp_path / "sun.json"
+ payload = {"lat": "45.07", "lon": "7.68", "results": {"sunset": "x"}}
+ write_cache(payload, path)
+ assert read_cache(path) == payload
+
+
+def test_read_cache_missing(tmp_path):
+ assert read_cache(tmp_path / "nope.json") is None