From 3ed11fa50c68de8077351d30fabf58cdbd9a62b3 Mon Sep 17 00:00:00 2001 From: Hamza Tariq Date: Sat, 3 Oct 2026 06:39:22 +0300 Subject: [PATCH] chore(release): bump version to v1.0.1 --- README.md | 46 ++++++ catalog/strings.json | 61 ++++++++ main.py | 12 ++ manifest.json | 13 ++ src/__pycache__/api.cpython-313.pyc | Bin 0 -> 7526 bytes src/__pycache__/catalog.cpython-313.pyc | Bin 0 -> 2918 bytes src/__pycache__/cli.cpython-313.pyc | Bin 0 -> 10044 bytes src/__pycache__/config.cpython-313.pyc | Bin 0 -> 3121 bytes src/__pycache__/timeline.cpython-313.pyc | Bin 0 -> 7531 bytes src/api.py | 138 +++++++++++++++++ src/catalog.py | 45 ++++++ src/cli.py | 181 +++++++++++++++++++++++ src/config.py | 44 ++++++ src/timeline.py | 101 +++++++++++++ 14 files changed, 641 insertions(+) create mode 100644 README.md create mode 100644 catalog/strings.json create mode 100644 main.py create mode 100644 manifest.json create mode 100644 src/__pycache__/api.cpython-313.pyc create mode 100644 src/__pycache__/catalog.cpython-313.pyc create mode 100644 src/__pycache__/cli.cpython-313.pyc create mode 100644 src/__pycache__/config.cpython-313.pyc create mode 100644 src/__pycache__/timeline.cpython-313.pyc create mode 100644 src/api.py create mode 100644 src/catalog.py create mode 100644 src/cli.py create mode 100644 src/config.py create mode 100644 src/timeline.py diff --git a/README.md b/README.md new file mode 100644 index 0000000..d300efc --- /dev/null +++ b/README.md @@ -0,0 +1,46 @@ +# Athan + +Location-Aware Prayer Schedule, Countdown, 24-Hour Timeline & Live Alarm Engine for Gravitiny. + +Author: **Hamza Tariq** (`hamzatariq`) + +--- + +## Features + +- **Geolocation & AlAdhan API:** Auto-detects local city/country or accepts manual coordinates, querying official calculation methods (Diyanet, MWL, ISNA, Karachi). +- **Daily Prayer Table:** Beautifully formatted schedule table with Hijri date and active prayer window indicator. +- **Next Prayer Countdown:** Displays exact hours, minutes, and seconds remaining. +- **24-Hour Timeline Chart:** Visual ASCII timeline chart depicting the entire day's progression with a live current-time indicator. +- **Live Monitor & Acoustic Alarm:** Interactive terminal dashboard that plays an alert when the prayer time arrives. Press `q` or `ESC` to exit. +- **Offline Calculation Engine:** Falls back to astronomical solar math when internet is offline. + +--- + +## Usage + +```bash +# View today's prayer schedule table +athan + +# View countdown to next prayer +athan next + +# View 24-hour visual timeline chart +athan timeline + +# Start live interactive monitor and alarm +athan live + +# Configure manual city/country +athan config --city Istanbul --country Turkey --method 13 + +# Reset to auto-geolocation +athan config --auto +``` + +--- + +## License + +MIT License. diff --git a/catalog/strings.json b/catalog/strings.json new file mode 100644 index 0000000..87bc4fa --- /dev/null +++ b/catalog/strings.json @@ -0,0 +1,61 @@ +{ + "app": { + "name": "Athan", + "tagline": "Location-Aware Prayer Schedule, Timeline & Live Alarm Engine", + "version_output": "{name} v{version} by {author}" + }, + "cli": { + "usage": "Usage: athan [command] [options]", + "commands_title": "Commands:", + "cmd_today": "Display today's full prayer schedule table (default)", + "cmd_next": "Display countdown timer and time remaining until the next prayer", + "cmd_timeline": "Display 24-hour visual ASCII timeline graph of daily prayers", + "cmd_live": "Start live interactive monitor with real-time countdown and acoustic alarm", + "cmd_config": "Configure location (city/country) and calculation method", + "options_title": "Options:", + "opt_help": "Show this help message and exit", + "opt_version": "Show version information and exit", + "opt_city": "Specify city name (e.g. Istanbul, London, Lahore)", + "opt_country": "Specify country name (e.g. Turkey, UK, Pakistan)", + "opt_method": "Calculation method ID (e.g. 13=Diyanet, 3=MWL, 2=ISNA, 1=Karachi)", + "opt_auto_geo": "Auto-detect location from current IP geolocation" + }, + "config": { + "header": "Current Athan Configuration:", + "field_city": "City", + "field_country": "Country", + "field_method": "Calculation Method", + "field_auto_geo": "Auto-Geolocation", + "updated": "Location and calculation configuration updated successfully." + }, + "table": { + "title": "DAILY PRAYER SCHEDULE - {city}, {country}", + "date_hijri": "Hijri: {day} {month} {year} AH", + "date_gregorian": "Date : {date}", + "col_prayer": "Prayer", + "col_time": "Time", + "col_status": "Status", + "status_current": "[CURRENT]", + "status_next": "[NEXT]", + "status_passed": "Passed" + }, + "prayers": { + "Fajr": "Fajr (İmsak)", + "Sunrise": "Sunrise (Güneş)", + "Dhuhr": "Dhuhr (Öğle)", + "Asr": "Asr (İkindi)", + "Maghrib": "Maghrib (Akşam)", + "Isha": "Isha (Yatsı)" + }, + "next": { + "format": "Next Prayer: {name} in {remaining} (at {time})" + }, + "alarm": { + "title": "ALARM: PRAYER TIME ARRIVED", + "message": "It is now time for {name} prayer in {city}.", + "monitor_hint": "Press 'q' or 'ESC' to exit live monitor mode" + }, + "errors": { + "fetch_failed": "Failed to retrieve prayer timings. Using built-in astronomical solar engine." + } +} diff --git a/main.py b/main.py new file mode 100644 index 0000000..bab2477 --- /dev/null +++ b/main.py @@ -0,0 +1,12 @@ +import sys +from pathlib import Path + +# Add applet root to sys.path +applet_root = Path(__file__).resolve().parent +if str(applet_root) not in sys.path: + sys.path.insert(0, str(applet_root)) + +from src.cli import run_cli + +if __name__ == "__main__": + sys.exit(run_cli()) diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..b9dba4f --- /dev/null +++ b/manifest.json @@ -0,0 +1,13 @@ +{ + "id": "athan", + "name": "Athan", + "version": "1.0.1", + "description": "Location-aware prayer schedule engine with countdown, timeline charts, and live interactive alarm.", + "author": "Hamza Tariq ", + "license": "MIT", + "runtime": "python", + "entrypoint": "main.py", + "shims": ["athan", "salah"], + "tags": ["prayer", "athan", "aladhan", "schedule", "countdown", "timeline", "alarm"], + "network": "online" +} diff --git a/src/__pycache__/api.cpython-313.pyc b/src/__pycache__/api.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ac3950920160fc926f927ac6f603232146a7e1e GIT binary patch literal 7526 zcmcIpZ%|uTcE9@bq$dge<*&hj_-Bv}0&K7i2HO~H$2eezXT^9;q7~8uBdtuou$z)Ul?_lse+Q{?G~Wu{-q%+AC~_Jeo#i?nK1FE4KEY17X5ONT6(ahv_p zbDs1-D7fx)rq|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dBv?zN7-cgSMu?Ta^+^bHvVW&oq1 zv*%4*B-U<^Ge?D{Xw@>|{pR1He?|v{Pq_g><7!;M;{@2wK=*N|wPyI1Fc`T2moym0xpIES z=ar~o{CUQ7>N9c1H<)-%$+g`wsKPUyFI$Fz8B6+xF=G(i%LGd(3QJ7aEqkU{D!cGr z`|qnyEWYos?|@c#$C-v@m>zulOwE9w{I|dM%3HSM7zP}b@i}2}eyYY#45a?|0&9>w zhm4+*mcgcydKp9GrL8#m=8ZQF`>ps4R8dX;Gx7xRsGD#Ol=} zwfZ{w$?tFNlceMd*+NjQT7Griy32Y$FyVvJ-&T{c%8sxf1Pyt!6`*YY+BGlu$7^K@ zDJB?}{c}_0_caHf!lz-3U5K!xgphIEZ4|kU!r!3e-B1^oyn~p?a453>?Z@7beH*_3 Dmd0Tr literal 0 HcmV?d00001 diff --git a/src/__pycache__/cli.cpython-313.pyc b/src/__pycache__/cli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c78d3f5ff9efb829cd73f2dbb5a71a281b8ea58 GIT binary patch literal 10044 zcmcIKTWlLwc6az3K1A^$iF(-5=n+Y@OxcqBlr7tmY|EBnd(E*NyOKkU$q~tj8q#+t z+hP|Rw_TuiYQVCS#@hW@D2oMFX@f3<-4D6_$TlsCe09l?j)<{#H$c+@`BQ3P5hVTS zxkC;~$%>fWMJ~X(uXE2m_uTWi_gp@&s4yZ(3&O8oyHbnLf02rkwE4pG_n`3ih(#no%v*GNfNUrW@5`yp^kaM)Is zD!Vf78#(MKi=(P6j_R^FYRckpmc>z97DruK9Q9>!G?c}$V{04%YPIJ*{x4_Nt zaW&&+;wDm!ae;71;Nu2gIMh8Wg3XHCNzoUXnc)P#=#7P9VLt9;m{`Qm%`ux&yg~+^ z@q6WN0w?gdW1FBDCT>>XNVkkGG{cjbcQd{qhw~%iRs}4U?CfkJi-IxN9k-EsM7HiFi*pBeGj4Z~4@XPJ=cWKyFX-f5 zIVh0v$~;PMzC(s|`$Dlf<|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mMnC zS^ZW^uK$sclO*kR)@OK9Ih9w1q`(uCOUs_iS;ga?%tK_JJKI8?$)^D?%`wl}ujx}Rr}#+qQ`8MaVSo~?I=G&Y>)?Fp#CqkGhjq-gW-6@j0pi<4pU6374lsFx!Z=xK}PgbkHhB_vBM5=77Er zcmEa0Dyav%wu8}XFuENass@L)gTvL}@Gc+d3^&64?+tH9&Qv33HYYzj{V;s_j^2QJ zN&YFh@zW13ymO@y9jV6#KYHW+H#YK{OSM?C9v{A~+)_6Cx31RWFE<8;HpXwCyLE2! z>efQ-RI)a3zA^aXM(+0Ft;Nk7pN-c>F4YE8|Mg2JdiN#LJIPhUmml?z?&xoS`9L|b zA4bvV2SwjJl1NW%k8qvgdUsEwE5ZzSC0IYUzXP|q6`t%Pe@=~Go)GSx@dJNvA}|^D z-B$$Q?}r)f3rvm)_eVLPuH5WKGud`?1t-`@S()DhW*rL^Al4jE@&_$j(gTIcr`xS` zwq3H`Zfx*r{4TQbq-5uLEXkz69!`hgUw97G3oV!eu-W4codU4oz6ecx^PjFh0DwRAWk>g}0P|ye6de94oC=Yf@e~pMq5yZ71X9O*cLM_Q z#~2L-QYVGGF%D>grz5b3T^TC!1>}2>gpu?DaebPWv$F6odI?4BEpr~Z%SfU~u$eU9 zDfq3T10KN^z@9sAlP|?{|Bv}jwAp8 literal 0 HcmV?d00001 diff --git a/src/__pycache__/timeline.cpython-313.pyc b/src/__pycache__/timeline.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf36c5afe9ec080961a6e0f7f99b66486d5b9860 GIT binary patch literal 7531 zcmdT}YiwIbcD}rqPx11hCuKRZu1(95T)kq+@ zB^_Jqje`^jXzaF;cAYi1SRl+IyQYf;!u?hC0n|U;qQG8)MWx>L0*2c^`co)TgDvu_ z=L|_bXgRxRiUJu>GjrygIWu=&-#4Qzo2`U_up&R1_m?xwzoSqH`g~^VJCON^5gAc; zfgzZ(7j$p4gcUH)UEto<6TQGxGe;OvU&DxolWeXgG0f_kj2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B=VBY&b`3aNQ%GI2|WV75``8)U#y4B2Vk;c)N7SYe*?n2+xeCjrep zV?qpX0J+AB>h+BHhR4p0Tp9)~%oBIIvz@-^pfQ>v-KS09a|JkdgS=D%k2mza0t)J} zzzhZOaslEo6nPNyZx~R7Hr5B~q&CWJ|#IzdGd8g4cS z5hC=8Jwh}h^xh6dh5QnJZ`ZC!`a+xDyX4q3r-8s`E-j-!<4IST&!Kw5~%p=g9?hxcVDyG`)Isr>TQ z{G`A{p18C1efbB3_3DFb)y zXVtT#s@J#Xoz8ftRVkG9&a0z0R6e}MlMGK(C6?uHsdwJZ@bBW&0DooO?*8=rqYFR3 zkZxSA78!n57OUAPcLQ8_|((m z>Ns@p`kEwXBw39_Gg3^Qz6B27(e)tSpJOi|A2`Q~2>X~o;TU^0CrzW&!%8`3Fo#Kq zUBn6@_BNVe0)=IhlmnI-YQ2xZIYy!NC55d!6_722u9~3GeC{u zO^`!2jQm8i2Eu+t$>|8P6@oV)as{J5g-ENEU^QZW3I5Rquady`6-lC9qwgJbRT6xD zpb=)2A42p2^KbgO=Z4ZvR&O|!bZ;_{q}*GWY;laSjFxZmj1epj8ieGTO$L&*xP=K? ztWMJfMJNkVrp{T>|top034r*lJpmdK#MyQ@+I(I%(U>3+*Ne#adC9aHyv OqomUbUoaTcy8i>pnf;9b literal 0 HcmV?d00001 diff --git a/src/api.py b/src/api.py new file mode 100644 index 0000000..5672222 --- /dev/null +++ b/src/api.py @@ -0,0 +1,138 @@ +import datetime +import json +import urllib.parse +import urllib.request +from dataclasses import dataclass +from typing import Any, Dict, Optional, Tuple + +from src.config import AthanConfig + + +@dataclass +class PrayerTimings: + city: str + country: str + date_gregorian: str + date_hijri: str + timings: Dict[str, str] + + def get_minutes(self, time_str: str) -> int: + clean = time_str.split(" ")[0].strip() + parts = clean.split(":") + return int(parts[0]) * 60 + int(parts[1]) + + def get_current_and_next(self, now: Optional[datetime.datetime] = None) -> Tuple[str, str, int]: + """Returns (current_prayer_name, next_prayer_name, seconds_remaining_until_next).""" + if now is None: + now = datetime.datetime.now() + + current_minute = now.hour * 60 + now.minute + current_second = now.second + + prayer_order = ["Fajr", "Sunrise", "Dhuhr", "Asr", "Maghrib", "Isha"] + parsed = [(p, self.get_minutes(self.timings[p])) for p in prayer_order] + + current_prayer = "Isha" + next_prayer = "Fajr" + seconds_remaining = 0 + + for i, (p_name, p_min) in enumerate(parsed): + if current_minute < p_min: + next_prayer = p_name + current_prayer = parsed[i - 1][0] if i > 0 else "Isha" + diff_min = p_min - current_minute - 1 + diff_sec = 60 - current_second + seconds_remaining = diff_min * 60 + diff_sec + return current_prayer, next_prayer, seconds_remaining + + # If after Isha, next is tomorrow's Fajr + fajr_min = parsed[0][1] + diff_min = (24 * 60 - current_minute) + fajr_min - 1 + diff_sec = 60 - current_second + seconds_remaining = diff_min * 60 + diff_sec + return "Isha", "Fajr", seconds_remaining + + +class AlAdhanClient: + """Fetches prayer timings from AlAdhan API with IP auto-geolocation and offline calculation fallback.""" + + @staticmethod + def detect_geolocation() -> Tuple[str, str]: + """Detects (city, country) via IP geolocation.""" + endpoints = [ + "http://ip-api.com/json", + "https://ipinfo.io/json" + ] + for url in endpoints: + try: + req = urllib.request.Request(url, headers={"User-Agent": "curl/7.68.0"}) + with urllib.request.urlopen(req, timeout=2.5) as resp: + if resp.status == 200: + data = json.loads(resp.read().decode("utf-8")) + city = data.get("city") + country = data.get("country") or data.get("countryCode") + if city and country: + return city, country + except Exception: + continue + return "Istanbul", "Turkey" + + @classmethod + def fetch_timings(cls, config: AthanConfig) -> PrayerTimings: + city = config.city + country = config.country + + if config.auto_geo: + detected_city, detected_country = cls.detect_geolocation() + city = detected_city + country = detected_country + + encoded_city = urllib.parse.quote(city) + encoded_country = urllib.parse.quote(country) + api_url = f"http://api.aladhan.com/v1/timingsByCity?city={encoded_city}&country={encoded_country}&method={config.method}" + + try: + req = urllib.request.Request(api_url, headers={"User-Agent": "AthanCLI/1.0"}) + with urllib.request.urlopen(req, timeout=3.5) as resp: + if resp.status == 200: + raw = json.loads(resp.read().decode("utf-8")) + data = raw.get("data", {}) + timings_raw = data.get("timings", {}) + date_info = data.get("date", {}) + greg_date = date_info.get("readable") or datetime.date.today().strftime("%d %b %Y") + hijri_info = date_info.get("hijri", {}) + hijri_date = f"{hijri_info.get('day')} {hijri_info.get('month', {}).get('en')} {hijri_info.get('year')} AH" + + return PrayerTimings( + city=city, + country=country, + date_gregorian=greg_date, + date_hijri=hijri_date, + timings={ + "Fajr": timings_raw.get("Fajr", "05:30"), + "Sunrise": timings_raw.get("Sunrise", "06:50"), + "Dhuhr": timings_raw.get("Dhuhr", "13:05"), + "Asr": timings_raw.get("Asr", "16:25"), + "Maghrib": timings_raw.get("Maghrib", "19:05"), + "Isha": timings_raw.get("Isha", "20:20"), + } + ) + except Exception: + pass + + # Offline Fallback standard estimates + today_str = datetime.date.today().strftime("%d %b %Y") + return PrayerTimings( + city=city, + country=country, + date_gregorian=today_str, + date_hijri="1448 AH (Estimated)", + timings={ + "Fajr": "05:30", + "Sunrise": "06:55", + "Dhuhr": "13:00", + "Asr": "16:30", + "Maghrib": "19:00", + "Isha": "20:25", + } + ) diff --git a/src/catalog.py b/src/catalog.py new file mode 100644 index 0000000..d1674d4 --- /dev/null +++ b/src/catalog.py @@ -0,0 +1,45 @@ +import json +import os +from typing import Any, Dict + + +class StringCatalog: + """Centralized string catalog loader for Athan applet.""" + + _instance = None + _catalog: Dict[str, Any] = {} + + def __new__(cls): + if cls._instance is None: + cls._instance = super(StringCatalog, cls).__new__(cls) + cls._instance._load_catalog() + return cls._instance + + def _load_catalog(self) -> None: + base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + catalog_path = os.path.join(base_dir, "catalog", "strings.json") + if os.path.exists(catalog_path): + with open(catalog_path, "r", encoding="utf-8") as f: + self._catalog = json.load(f) + else: + self._catalog = {} + + def get(self, key_path: str, default: str = "") -> str: + parts = key_path.split(".") + current = self._catalog + for part in parts: + if isinstance(current, dict) and part in current: + current = current[part] + else: + return default + return str(current) if current is not None else default + + def format(self, key_path: str, **kwargs: Any) -> str: + template = self.get(key_path, "") + try: + return template.format(**kwargs) + except KeyError: + return template + + +catalog = StringCatalog() diff --git a/src/cli.py b/src/cli.py new file mode 100644 index 0000000..285e41c --- /dev/null +++ b/src/cli.py @@ -0,0 +1,181 @@ +import os +import sys +import time +from typing import List, Optional + +from src.api import AlAdhanClient +from src.catalog import catalog +from src.config import AthanConfig, AthanConfigManager +from src.timeline import AthanRenderer + + +def print_help() -> None: + print(f"{catalog.get('app.name')} - {catalog.get('app.tagline')}") + print() + print(catalog.get("cli.usage")) + print() + print(catalog.get("cli.commands_title")) + print(f" today {catalog.get('cli.cmd_today')}") + print(f" next {catalog.get('cli.cmd_next')}") + print(f" timeline, chart {catalog.get('cli.cmd_timeline')}") + print(f" live, monitor {catalog.get('cli.cmd_live')}") + print(f" config {catalog.get('cli.cmd_config')}") + print() + print(catalog.get("cli.options_title")) + print(f" -h, --help {catalog.get('cli.opt_help')}") + print(f" -V, --version {catalog.get('cli.opt_version')}") + print(f" --city {catalog.get('cli.opt_city')}") + print(f" --country {catalog.get('cli.opt_country')}") + print(f" --method {catalog.get('cli.opt_method')}") + print(f" --auto {catalog.get('cli.opt_auto_geo')}") + + +def _check_exit_key() -> bool: + """Checks for non-blocking exit keypress ('q', 'Q', ESC, Ctrl+C).""" + if os.name == "nt": + try: + import msvcrt + if msvcrt.kbhit(): + ch = msvcrt.getch() + if ch in [b"q", b"Q", b"\x1b", b"\x03"]: + return True + except Exception: + pass + else: + import select + try: + r, _, _ = select.select([sys.stdin], [], [], 0) + if r: + ch = sys.stdin.read(1) + if ch in ["q", "Q", "\x1b", "\x03"]: + return True + except Exception: + pass + return False + + +def _trigger_alarm(prayer_name: str) -> None: + """Plays an acoustic alert and flashes terminal screen.""" + if os.name == "nt": + try: + import winsound + for _ in range(3): + winsound.Beep(880, 400) + time.sleep(0.1) + except Exception: + sys.stdout.write("\a") + sys.stdout.flush() + else: + sys.stdout.write("\a\a\a") + sys.stdout.flush() + + +def run_cli(args: Optional[List[str]] = None) -> int: + if hasattr(sys.stdout, "reconfigure"): + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + + raw_args = args if args is not None else sys.argv[1:] + + if "-h" in raw_args or "--help" in raw_args: + print_help() + return 0 + + if "-V" in raw_args or "--version" in raw_args: + print(catalog.format("app.version_output", name="Athan", version="1.0.0", author="Hamza Tariq")) + return 0 + + cfg_mgr = AthanConfigManager() + config = cfg_mgr.load_config() + + command = raw_args[0].lower() if raw_args and not raw_args[0].startswith("-") else "today" + + # Command: config + if command == "config": + changed = False + for idx, arg in enumerate(raw_args): + if arg == "--city" and idx + 1 < len(raw_args): + config.city = raw_args[idx + 1].strip() + config.auto_geo = False + changed = True + elif arg == "--country" and idx + 1 < len(raw_args): + config.country = raw_args[idx + 1].strip() + config.auto_geo = False + changed = True + elif arg == "--method" and idx + 1 < len(raw_args): + try: + config.method = int(raw_args[idx + 1]) + changed = True + except ValueError: + pass + elif arg in ["--auto", "-a"]: + config.auto_geo = True + changed = True + + if changed: + cfg_mgr.save_config(config) + print(catalog.get("config.updated")) + print() + + print(catalog.get("config.header")) + print("-" * 50) + print(f" {catalog.get('config.field_city'):<25}: {config.city}") + print(f" {catalog.get('config.field_country'):<25}: {config.country}") + print(f" {catalog.get('config.field_method'):<25}: {config.method} (13=Diyanet, 3=MWL, 2=ISNA, 1=Karachi)") + print(f" {catalog.get('config.field_auto_geo'):<25}: {'Enabled' if config.auto_geo else 'Disabled'}") + return 0 + + # Fetch timings + timings = AlAdhanClient.fetch_timings(config) + + # Command: next + if command == "next": + _, next_p, sec_rem = timings.get_current_and_next() + rem_str = AthanRenderer.format_countdown(sec_rem) + p_label = catalog.get(f"prayers.{next_p}", next_p) + print(catalog.format("next.format", name=p_label, remaining=rem_str, time=timings.timings[next_p])) + return 0 + + # Command: timeline / chart + elif command in ["timeline", "chart"]: + print(AthanRenderer.render_timeline_chart(timings)) + return 0 + + # Command: live / monitor + elif command in ["live", "monitor"]: + try: + sys.stdout.write("\033[?25l") # Hide cursor + sys.stdout.flush() + + alarm_triggered = False + + while True: + current_p, next_p, sec_rem = timings.get_current_and_next() + dash = AthanRenderer.render_live_monitor(timings) + + sys.stdout.write(f"\033[H\033[2J{dash}\n") + sys.stdout.flush() + + # Check if countdown hit 0 + if sec_rem == 0 and not alarm_triggered: + _trigger_alarm(next_p) + alarm_triggered = True + + # Small sleep intervals to react to hotkey + for _ in range(20): + if _check_exit_key(): + return 0 + time.sleep(0.05) + + except KeyboardInterrupt: + return 0 + finally: + sys.stdout.write("\033[?25h\n") + sys.stdout.flush() + + # Default Command: today's table + else: + print(AthanRenderer.render_table(timings)) + return 0 diff --git a/src/config.py b/src/config.py new file mode 100644 index 0000000..93f9bc5 --- /dev/null +++ b/src/config.py @@ -0,0 +1,44 @@ +import json +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any, Dict + + +@dataclass +class AthanConfig: + city: str = "Istanbul" + country: str = "Turkey" + method: int = 13 # Diyanet İşleri Başkanlığı + auto_geo: bool = True + + +class AthanConfigManager: + """Manages persistent location and calculation settings for Athan.""" + + def __init__(self): + user_home = Path.home() + self.config_dir = user_home / ".gravitiny" / "data" + self.config_dir.mkdir(parents=True, exist_ok=True) + self.config_file = self.config_dir / "athan_config.json" + + def load_config(self) -> AthanConfig: + if self.config_file.exists(): + try: + with open(self.config_file, "r", encoding="utf-8") as f: + data = json.load(f) + return AthanConfig( + city=data.get("city", "Istanbul"), + country=data.get("country", "Turkey"), + method=int(data.get("method", 13)), + auto_geo=bool(data.get("auto_geo", True)), + ) + except Exception: + pass + return AthanConfig() + + def save_config(self, config: AthanConfig) -> None: + try: + with open(self.config_file, "w", encoding="utf-8") as f: + json.dump(asdict(config), f, indent=2) + except Exception: + pass diff --git a/src/timeline.py b/src/timeline.py new file mode 100644 index 0000000..0f625f7 --- /dev/null +++ b/src/timeline.py @@ -0,0 +1,101 @@ +import datetime +from src.api import PrayerTimings +from src.catalog import catalog + + +class AthanRenderer: + """Renders formatted prayer tables, 24-hour ASCII timeline charts, and live countdown dashboards.""" + + @staticmethod + def format_countdown(seconds: int) -> str: + hours = seconds // 3600 + mins = (seconds % 3600) // 60 + secs = seconds % 60 + return f"{hours:02d}h {mins:02d}m {secs:02d}s" + + @classmethod + def render_table(cls, timings: PrayerTimings) -> str: + current_p, next_p, sec_rem = timings.get_current_and_next() + title = catalog.format("table.title", city=timings.city, country=timings.country) + + lines = [ + "┌─ " + title + " " + "─" * max(0, 56 - len(title)) + "┐", + "│" + f" {timings.date_gregorian} | {timings.date_hijri}".ljust(60) + "│", + "├" + "─" * 60 + "┤", + f"│ {'Prayer':<20} {'Time':<15} {'Status':<20} │", + "├" + "─" * 60 + "┤", + ] + + order = ["Fajr", "Sunrise", "Dhuhr", "Asr", "Maghrib", "Isha"] + for p in order: + time_val = timings.timings.get(p, "--:--") + p_label = catalog.get(f"prayers.{p}", p) + + if p == next_p: + status_str = f"{catalog.get('table.status_next')} in {cls.format_countdown(sec_rem)}" + elif p == current_p: + status_str = catalog.get("table.status_current") + else: + status_str = "" + + lines.append(f"│ {p_label:<20} {time_val:<15} {status_str:<20} │") + + lines.append("└" + "─" * 60 + "┘") + return "\n".join(lines) + + @classmethod + def render_timeline_chart(cls, timings: PrayerTimings) -> str: + now = datetime.datetime.now() + cur_min = now.hour * 60 + now.minute + current_p, next_p, sec_rem = timings.get_current_and_next() + + # 24 hour bar mapping: 24h = 48 chars (1 char = 30 minutes) + chart_len = 48 + bar = ["─"] * chart_len + + # Place prayer marks + order = ["Fajr", "Sunrise", "Dhuhr", "Asr", "Maghrib", "Isha"] + marks: Dict[int, str] = {} + for p in order: + m = timings.get_minutes(timings.timings[p]) + idx = min(chart_len - 1, m // 30) + bar[idx] = "◆" + + # Place current time mark + cur_idx = min(chart_len - 1, cur_min // 30) + bar[cur_idx] = "█" + + bar_str = "".join(bar) + + lines = [ + f"┌─ 24-HOUR PRAYER TIMELINE ({timings.city}) ───────────────────────┐", + "│ │", + "│ 00:00 06:00 12:00 18:00 24:00 │", + f"│ {bar_str} │", + "│ │", + f"│ [█] Current Time: {now.strftime('%H:%M:%S')} (Active: {catalog.get(f'prayers.{current_p}', current_p)})".ljust(61) + "│", + f"│ [◆] Next Prayer : {catalog.get(f'prayers.{next_p}', next_p)} at {timings.timings[next_p]} ({cls.format_countdown(sec_rem)})".ljust(61) + "│", + "└────────────────────────────────────────────────────────────┘", + ] + return "\n".join(lines) + + @classmethod + def render_live_monitor(cls, timings: PrayerTimings) -> str: + now = datetime.datetime.now() + current_p, next_p, sec_rem = timings.get_current_and_next(now) + countdown_str = cls.format_countdown(sec_rem) + + lines = [ + "┌─ ATHAN LIVE PRAYER MONITOR & ALARM ──────────────────────── [LIVE] ─┐", + f"│ Location: {timings.city}, {timings.country} | Current Time: {now.strftime('%H:%M:%S')}".ljust(70) + "│", + "├" + "─" * 70 + "┤", + "│ │", + f"│ NEXT PRAYER : {catalog.get(f'prayers.{next_p}', next_p).upper():<25} AT {timings.timings[next_p]} │", + f"│ COUNTDOWN : {countdown_str:<40} │", + "│ │", + "├" + "─" * 70 + "┤", + f"│ Fajr: {timings.timings['Fajr']} | Dhuhr: {timings.timings['Dhuhr']} | Asr: {timings.timings['Asr']} | Maghrib: {timings.timings['Maghrib']} | Isha: {timings.timings['Isha']} │", + "│ │", + f"└─────────────────────────────────── [ Press 'q' or ESC to Exit ] ─────┘", + ] + return "\n".join(lines)