From 0719a71ec1f6dfd459aa43dec7144ca1d2a2b6f8 Mon Sep 17 00:00:00 2001 From: Hamza Tariq Date: Sat, 3 Oct 2026 06:49:18 +0300 Subject: [PATCH] fix(ui): eliminate live mode screen flicker and resolve table border padding overflow (v1.0.2) --- 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 -> 10047 bytes src/__pycache__/config.cpython-313.pyc | Bin 0 -> 3121 bytes src/__pycache__/timeline.cpython-313.pyc | Bin 0 -> 9619 bytes src/api.py | 138 +++++++++++++++++ src/catalog.py | 45 ++++++ src/cli.py | 183 +++++++++++++++++++++++ src/config.py | 44 ++++++ src/timeline.py | 160 ++++++++++++++++++++ 14 files changed, 702 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..da0a2fc --- /dev/null +++ b/manifest.json @@ -0,0 +1,13 @@ +{ + "id": "athan", + "name": "Athan", + "version": "1.0.2", + "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?nK1FE4KEY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?}3x2RlFLxg>wvcIZ;$oiJ)WxYdBv?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..3bc4653e2fcd9dcd10449a464ff806a669a8d62d GIT binary patch literal 10047 zcmcIKTWlNGl{0(}pW;Ij^{}MTBa&!|k|o))EnBuF*_JKEcFi#zdnJb$lOvK5HKgxQ zw#62SyIWxGtO3hTHdgzwP>KRoy1`aK`ypeoNY}eq8mGo|NGFxmLBT+?wbXq>gq@Q;xMAge7Atq86qOnkfXTwfXG!2D^{6Ur<35Pg71`S#t8)L(f z06-gtVz?*5PlW=at*CO2<=Fs-q~RFE&GCK?aY)o4E;fsJAD&N6S|}*t_u{e&^KF8Z zJ0=uz$qhYQQxov_Kn~UnJS_>WEI{|=%XHCv2Xa#sx0S@IlCjEp@#sGbqguu!=fxNq zO-YKh@;Ecmr;y8=a8M<2=;U$Vh(lizhoK}6V@VvQk~qvIag>$9@n`LlMaC-Un>cJO zNtI0=_l+F3m&8$C5=TWz9F-+;I7;HEDv6`IB#xSrIBHAc*t0W^0O71VAE(%8w2NnF zxVV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D6Ob*bHgNU@&6A{czI|c;qVmUwleU-EAqGoYm+gO)a*2fh E2Tu}(ApigX literal 0 HcmV?d00001 diff --git a/src/__pycache__/config.cpython-313.pyc b/src/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d4084569ede152f99a366e14364df0cdbb3bd11 GIT binary patch literal 3121 zcmaJ@U2Gf25#Iadk(4aa5e11fElO78(y7!xxiDQvHZ3QyrABCVQW1az4kz+RQKs(L zy<-{~C?ND9RnYXTF)+z0S@6f$_F^XX#UkkbmRC8?a_$ZwaP#q7s#xCKP9Wnw#P&KP6Bh zj%#6BoRX--cyU^u@=@QELX|kl2z_LTs8WQe@>#y=?rd`+)X#K2&?%md1`1rlzk?Pt z3Eq`;J6Fs)u0N+cdbXt7c7k)opXkmaD20@{;)+*5pKW<$lh9i1%>c7bGK6v}p}fjb z;YBz(6*E#sR)y1`RYmG!D~YXSs$~42^Rbme1DPPK{A?AV9fe?`!wsgKMctgV%zUx1 z;{zYAa?N&hbD>gl#ca`8apk!Ry>6_yzN}R-9lEm9iB|Hm;VfFYIakpuj-?e0>l3(P zr>kh1sV^Iv<_0uv*~(Q)$aiSk&ntSVrRmbNe39Btsc0IerD?PSJqor%T~O(!X*s%6 zv`iaR$3R89nZ5}BJ%pUNU|A(MtZ8sirs=%(m*FEdXYScvWF?^PI|!1_7Ns(s@#9+s~6(FA@hf&tja93{`-inB?QI|7m+v zspY%vuRs#=%#FZUJKL^^MK=e9<}2$ILSeg#@fJiyv##F=vBYbwq%YZ)nSlC-L%8Ci zwQRV7rbf#ZsVgmC$0^tn<%=Z)oQk$l%Desw08Ya#Hr_HGr!jN_RZ%pH4pc()|8q6w zDG|E%Yd}^>qo?oYwRf-mVS3G9kDS^lRU_Zu`dKydqc!n&U3I17_g%l~+E!v!CAN{< zntOoU`FeEVql@ofd@y>c8ojh8{!Qs);B#eaI2CFh$|V*Y%jLfy!|NDR5F8z|XmMnC 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..b87acef94d630459c30ea055ae3a52a558dcf2e7 GIT binary patch literal 9619 zcmd6tTWlLwdVq)b`$ZRux>(jIvMfuMWJQuCTfQi=tgCg2HJaFt=&&?7mgq=B<;=*o zXgfCg5YR}`$XO?*ivp(G0A|nvOBY3>zO-6&f%QJ^3|Lg^tQQr$`=U1`%65T$Y5y}r zQY4phTQN2SjB1gV#C4i;x=}sS%X#fN!>AD%Nur#1i=cFs1f@T!Re87`(~Mw=6Q~D&yyyNgu=Ua||E!lYLbG$OyS8n~3CnSLPY6ndE~D z%zTh#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Fn9!e;k2Ih1(#BB+`(9k2uZrO^OnBke@ zsUx8m$!?+M*s6K0`)9pB=@qE=#r_%Lj7RVU1ZIAn;YEfQmck-)O9htQ~;pCF~TP1H&>h8q`3ERS)5$ zd{`5)=1}0_r1fBy8#SBp6c4N7ZB^W>N?wu4cwPY-8`3DKG`Y9kRvG^)3*jHam-|Fx zk!19GSsys!y^`4ryEm{jkMmZq_oF4>e5%Fa^lg}YzUeSUT+}e_j=`5SF&Qa zebB$a@N=O6n!|6L2ET>)m6t63c^}86+73Vs!hTHT!O?Xb-GfMSdEvdqO1wUvhaX+w zdzJ(Bc#^WqResYD_HxP*CP(gHAo_&(PpyB`S$uC~Q&+UD*6O-rb=w3a@wy$H>}Uvm zv0T4xCGcW{ytf!y|-B2o(?E!zYntNlATkwtdYkW(HFKUJeyJ})Ibzq|;) zz hrTQh|_%EVCBpQB2)c%U7`JMifT19?G;8>p1{{jbDc2)oY 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..6ffc494 --- /dev/null +++ b/src/cli.py @@ -0,0 +1,183 @@ +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.2", 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: + # Clear screen once and hide cursor + sys.stdout.write("\033[?25l\033[2J") + 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) + + # Overwrite in-place at top-left without clearing screen + sys.stdout.write(f"\033[H{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..ee7dd34 --- /dev/null +++ b/src/timeline.py @@ -0,0 +1,160 @@ +import datetime +from typing import Dict, List, Optional +from src.api import PrayerTimings +from src.catalog import catalog + + +class AthanRenderer: + """Renders pixel-perfect, aesthetic ASCII prayer tables, timeline graphs, and live monitors.""" + + BOX_WIDTH = 70 + + @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 _pad_line(cls, content: str, width: int = BOX_WIDTH) -> str: + """Pads a line so that left and right borders are always perfectly aligned.""" + inner_space = width - 4 + if len(content) > inner_space: + content = content[:inner_space - 3] + "..." + padding = " " * (inner_space - len(content)) + return f"│ {content}{padding} │" + + @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) + + # Header border calculation + top_dashes = max(0, cls.BOX_WIDTH - len(title) - 5) + top_border = f"┌─ {title} {'─' * top_dashes}┐" + if len(top_border) > cls.BOX_WIDTH: + top_border = top_border[:cls.BOX_WIDTH - 1] + "┐" + elif len(top_border) < cls.BOX_WIDTH: + top_border = top_border[:-1] + ("─" * (cls.BOX_WIDTH - len(top_border))) + "┐" + + mid_border = "├" + ("─" * (cls.BOX_WIDTH - 2)) + "┤" + bottom_border = "└" + ("─" * (cls.BOX_WIDTH - 2)) + "┘" + + date_line = f"{timings.date_gregorian} | {timings.date_hijri}" + header_row = f"{'Prayer':<22} {'Time':<10} {'Status':<30}" + + lines = [ + top_border, + cls._pad_line(date_line), + mid_border, + cls._pad_line(header_row), + mid_border, + ] + + 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 = "" + + row_text = f"{p_label:<22} {time_val:<10} {status_str:<30}" + lines.append(cls._pad_line(row_text)) + + lines.append(bottom_border) + 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(now) + + title = f"24-HOUR PRAYER TIMELINE ({timings.city})" + top_dashes = max(0, cls.BOX_WIDTH - len(title) - 5) + top_border = f"┌─ {title} {'─' * top_dashes}┐" + if len(top_border) > cls.BOX_WIDTH: + top_border = top_border[:cls.BOX_WIDTH - 1] + "┐" + elif len(top_border) < cls.BOX_WIDTH: + top_border = top_border[:-1] + ("─" * (cls.BOX_WIDTH - len(top_border))) + "┐" + + bottom_border = "└" + ("─" * (cls.BOX_WIDTH - 2)) + "┘" + + # 24-hour bar: 52 characters (1 char = ~27.7 minutes) + chart_len = 54 + bar = ["─"] * chart_len + + # Place prayer marks + order = ["Fajr", "Sunrise", "Dhuhr", "Asr", "Maghrib", "Isha"] + for p in order: + m = timings.get_minutes(timings.timings[p]) + idx = min(chart_len - 1, int((m / (24 * 60)) * chart_len)) + bar[idx] = "◆" + + # Place current time mark + cur_idx = min(chart_len - 1, int((cur_min / (24 * 60)) * chart_len)) + bar[cur_idx] = "█" + + bar_str = "".join(bar) + time_labels = "00:00 06:00 12:00 18:00 24:00" + + cur_label = catalog.get(f"prayers.{current_p}", current_p) + next_label = catalog.get(f"prayers.{next_p}", next_p) + + cur_time_info = f"[█] Current Time : {now.strftime('%H:%M:%S')} (Active: {cur_label})" + next_time_info = f"[◆] Next Prayer : {next_label} at {timings.timings[next_p]} ({cls.format_countdown(sec_rem)})" + + lines = [ + top_border, + cls._pad_line(""), + cls._pad_line(f" {time_labels}"), + cls._pad_line(f" {bar_str}"), + cls._pad_line(""), + cls._pad_line(cur_time_info), + cls._pad_line(next_time_info), + cls._pad_line(""), + bottom_border, + ] + 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) + next_label = catalog.get(f"prayers.{next_p}", next_p).upper() + + top_border = "┌─ ATHAN LIVE PRAYER MONITOR & ALARM ──────────────────────── [LIVE] ─┐" + if len(top_border) < cls.BOX_WIDTH: + top_border = top_border[:-1] + ("─" * (cls.BOX_WIDTH - len(top_border))) + "┐" + + mid_border = "├" + ("─" * (cls.BOX_WIDTH - 2)) + "┤" + bottom_hint = f"└─────────────────────────────────── [ Press 'q' or ESC to Exit ] ───┘" + if len(bottom_hint) < cls.BOX_WIDTH: + bottom_hint = bottom_hint[:-1] + ("─" * (cls.BOX_WIDTH - len(bottom_hint))) + "┘" + + header_info = f"Location: {timings.city}, {timings.country} | Time: {now.strftime('%H:%M:%S')}" + next_info = f" NEXT PRAYER : {next_label:<25} AT {timings.timings[next_p]}" + count_info = f" COUNTDOWN : {countdown_str:<40}" + summary_info = f"Fajr: {timings.timings['Fajr']} | Dhuhr: {timings.timings['Dhuhr']} | Asr: {timings.timings['Asr']} | Maghrib: {timings.timings['Maghrib']} | Isha: {timings.timings['Isha']}" + + lines = [ + top_border, + cls._pad_line(header_info), + mid_border, + cls._pad_line(""), + cls._pad_line(next_info), + cls._pad_line(count_info), + cls._pad_line(""), + mid_border, + cls._pad_line(summary_info), + cls._pad_line(""), + bottom_hint, + ] + return "\n".join(lines)