Spaces:
Running on Zero
Running on Zero
Commit ·
71c5d23
1
Parent(s): a50f869
feat: superadmin VIP offers, daily progress tracking, Sunni tafsir & R2 endpoints
Browse files- app/auth.py +265 -9
- app/database.py +9 -8
- app/payment_routes.py +4 -0
- app/r2_config.py +130 -53
- app/r2_routes.py +145 -26
- app/superadmin_routes.py +438 -2
- app/tafsir_routes.py +347 -149
app/auth.py
CHANGED
|
@@ -31,6 +31,7 @@ from app.database import (
|
|
| 31 |
pending_approvals_collection,
|
| 32 |
daily_progress_collection,
|
| 33 |
qaza_collection,
|
|
|
|
| 34 |
)
|
| 35 |
from app.limiter import limiter
|
| 36 |
from app.auth_deps import (
|
|
@@ -459,6 +460,10 @@ async def get_profile(uid: str, current_user: dict = Depends(get_current_user)):
|
|
| 459 |
user["is_pro"] = bool(user.get("is_pro") or user.get("subscription", {}).get("is_pro"))
|
| 460 |
user["has_password"] = bool(user.get("has_password"))
|
| 461 |
user["deleted_notification_ids"] = user.get("deleted_notification_ids") or []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
|
| 463 |
# Look up co-admin masjids dynamically so role changes take effect in real-time
|
| 464 |
co_masjids = await masjid_collection.find({"co_admins": uid}, {"masjid_id": 1, "name": 1, "_id": 0}).to_list(length=20)
|
|
@@ -1268,7 +1273,8 @@ async def get_surah_details(request: Request, surah_no: int):
|
|
| 1268 |
# The streak is computed by walking these docs backwards from today.
|
| 1269 |
PROGRESS_PRAYERS = ["Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"]
|
| 1270 |
PROGRESS_GOAL_SECONDS = 600 # 10 minutes to earn Quran / Hadith
|
| 1271 |
-
|
|
|
|
| 1272 |
|
| 1273 |
|
| 1274 |
class ProgressPrayerReq(BaseModel):
|
|
@@ -1321,19 +1327,20 @@ def _progress_prayer_streak_day_complete(doc: dict) -> bool:
|
|
| 1321 |
|
| 1322 |
|
| 1323 |
def _progress_golden_streak_day_complete(doc: dict) -> bool:
|
| 1324 |
-
"""A day counts toward golden streak if all 5 prayers are marked AND 10 min Quran AND 10 min Hadith."""
|
| 1325 |
raw = doc.get("prayers", []) or []
|
| 1326 |
prayers = set(_normalize_progress_prayer_name(p) for p in raw if _normalize_progress_prayer_name(p))
|
| 1327 |
all_prayers = all(p in prayers for p in PROGRESS_PRAYERS)
|
| 1328 |
quran_done = int(doc.get("quran_secs", 0) or 0) >= PROGRESS_GOAL_SECONDS
|
| 1329 |
hadith_done = int(doc.get("hadith_secs", 0) or 0) >= PROGRESS_GOAL_SECONDS
|
| 1330 |
-
|
|
|
|
| 1331 |
|
| 1332 |
|
| 1333 |
async def _progress_streaks(uid: str, today: datetime.date) -> tuple[int, int]:
|
| 1334 |
"""Calculate both normal prayer streak and golden streak.
|
| 1335 |
- Normal streak: consecutive days with all 5 prayers marked.
|
| 1336 |
-
- Golden streak: consecutive days with all 5 prayers + 10m Quran + 10m Hadith."""
|
| 1337 |
start = (today - datetime.timedelta(days=366)).isoformat()
|
| 1338 |
docs = await daily_progress_collection.find(
|
| 1339 |
{"uid": uid, "date": {"$gte": start}}, {"_id": 0}
|
|
@@ -1367,9 +1374,11 @@ def _progress_payload(doc: dict, date_str: str, streak: int, golden_streak: int
|
|
| 1367 |
"prayers": norm_prayers,
|
| 1368 |
"quran_secs": int(doc.get("quran_secs", 0) or 0),
|
| 1369 |
"hadith_secs": int(doc.get("hadith_secs", 0) or 0),
|
|
|
|
| 1370 |
"streak": streak,
|
| 1371 |
"golden_streak": golden_streak,
|
| 1372 |
"goal_seconds": PROGRESS_GOAL_SECONDS,
|
|
|
|
| 1373 |
"total_goals": PROGRESS_TOTAL_GOALS,
|
| 1374 |
}
|
| 1375 |
|
|
@@ -1381,6 +1390,21 @@ async def get_progress(request: Request, tz: float = 0.0, user: dict = Depends(g
|
|
| 1381 |
today = _progress_local_date(tz)
|
| 1382 |
date_str = today.isoformat()
|
| 1383 |
doc = await daily_progress_collection.find_one({"uid": uid, "date": date_str}, {"_id": 0}) or {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1384 |
streak, golden_streak = await _progress_streaks(uid, today)
|
| 1385 |
return _progress_payload(doc, date_str, streak, golden_streak)
|
| 1386 |
|
|
@@ -1448,19 +1472,28 @@ async def add_progress_time(payload: ProgressTimeReq, request: Request, user: di
|
|
| 1448 |
field = "quran_secs" if payload.category == "quran" else "hadith_secs"
|
| 1449 |
|
| 1450 |
doc = await daily_progress_collection.find_one(
|
| 1451 |
-
{"uid": uid, "date": date_str}, {"_id": 0
|
| 1452 |
) or {}
|
| 1453 |
current = int(doc.get(field, 0) or 0)
|
| 1454 |
if current >= PROGRESS_GOAL_SECONDS:
|
| 1455 |
-
|
|
|
|
| 1456 |
|
| 1457 |
nxt = min(current + payload.seconds, PROGRESS_GOAL_SECONDS)
|
| 1458 |
await daily_progress_collection.update_one(
|
| 1459 |
{"uid": uid, "date": date_str},
|
| 1460 |
-
{"$set": {field: nxt}, "$setOnInsert": {"uid": uid, "date": date_str}},
|
| 1461 |
upsert=True,
|
| 1462 |
)
|
| 1463 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1464 |
|
| 1465 |
|
| 1466 |
# =========================================================
|
|
@@ -1585,6 +1618,16 @@ async def get_progress_monthly(
|
|
| 1585 |
{"uid": uid, "date": {"$gte": start_date, "$lte": end_date}}, {"_id": 0}
|
| 1586 |
).sort("date", 1).to_list(length=100)
|
| 1587 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1588 |
docs_by_date = {d["date"]: d for d in docs}
|
| 1589 |
days_list = []
|
| 1590 |
prayer_counts = {"Fajr": 0, "Dhuhr": 0, "Asr": 0, "Maghrib": 0, "Isha": 0}
|
|
@@ -1599,7 +1642,8 @@ async def get_progress_monthly(
|
|
| 1599 |
is_full = len(prayers) == 5
|
| 1600 |
q_secs = int(item.get("quran_secs", 0) or 0)
|
| 1601 |
h_secs = int(item.get("hadith_secs", 0) or 0)
|
| 1602 |
-
|
|
|
|
| 1603 |
|
| 1604 |
if is_full:
|
| 1605 |
full_days += 1
|
|
@@ -1618,6 +1662,7 @@ async def get_progress_monthly(
|
|
| 1618 |
"is_golden": is_golden,
|
| 1619 |
"quran_secs": q_secs,
|
| 1620 |
"hadith_secs": h_secs,
|
|
|
|
| 1621 |
})
|
| 1622 |
|
| 1623 |
# Elapsed days calculation (so future unelapsed days don't falsely register as missed)
|
|
@@ -1668,6 +1713,217 @@ async def get_progress_monthly(
|
|
| 1668 |
}
|
| 1669 |
|
| 1670 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1671 |
class RequestEmailChangeReq(BaseModel):
|
| 1672 |
new_email: str = Field(..., min_length=5, max_length=150)
|
| 1673 |
|
|
|
|
| 31 |
pending_approvals_collection,
|
| 32 |
daily_progress_collection,
|
| 33 |
qaza_collection,
|
| 34 |
+
tasbeeh_collection,
|
| 35 |
)
|
| 36 |
from app.limiter import limiter
|
| 37 |
from app.auth_deps import (
|
|
|
|
| 460 |
user["is_pro"] = bool(user.get("is_pro") or user.get("subscription", {}).get("is_pro"))
|
| 461 |
user["has_password"] = bool(user.get("has_password"))
|
| 462 |
user["deleted_notification_ids"] = user.get("deleted_notification_ids") or []
|
| 463 |
+
|
| 464 |
+
# Add superadmin status at root level for superadmin app compatibility
|
| 465 |
+
auth_domain = user.get("auth", {}) or {}
|
| 466 |
+
user["superadmin"] = auth_domain.get("is_superadmin") or auth_domain.get("superadmin") or user.get("superadmin") or False
|
| 467 |
|
| 468 |
# Look up co-admin masjids dynamically so role changes take effect in real-time
|
| 469 |
co_masjids = await masjid_collection.find({"co_admins": uid}, {"masjid_id": 1, "name": 1, "_id": 0}).to_list(length=20)
|
|
|
|
| 1273 |
# The streak is computed by walking these docs backwards from today.
|
| 1274 |
PROGRESS_PRAYERS = ["Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"]
|
| 1275 |
PROGRESS_GOAL_SECONDS = 600 # 10 minutes to earn Quran / Hadith
|
| 1276 |
+
PROGRESS_TASBEEH_GOAL = 99 # 99 beads to satisfy the 7th deed option
|
| 1277 |
+
PROGRESS_TOTAL_GOALS = 7 # 5 prayers + quran + (hadith OR 99 tasbeeh)
|
| 1278 |
|
| 1279 |
|
| 1280 |
class ProgressPrayerReq(BaseModel):
|
|
|
|
| 1327 |
|
| 1328 |
|
| 1329 |
def _progress_golden_streak_day_complete(doc: dict) -> bool:
|
| 1330 |
+
"""A day counts toward golden streak if all 5 prayers are marked AND 10 min Quran AND (10 min Hadith OR 99 Tasbeeh)."""
|
| 1331 |
raw = doc.get("prayers", []) or []
|
| 1332 |
prayers = set(_normalize_progress_prayer_name(p) for p in raw if _normalize_progress_prayer_name(p))
|
| 1333 |
all_prayers = all(p in prayers for p in PROGRESS_PRAYERS)
|
| 1334 |
quran_done = int(doc.get("quran_secs", 0) or 0) >= PROGRESS_GOAL_SECONDS
|
| 1335 |
hadith_done = int(doc.get("hadith_secs", 0) or 0) >= PROGRESS_GOAL_SECONDS
|
| 1336 |
+
tasbeeh_done = int(doc.get("tasbeeh_count", 0) or 0) >= PROGRESS_TASBEEH_GOAL
|
| 1337 |
+
return all_prayers and quran_done and (hadith_done or tasbeeh_done)
|
| 1338 |
|
| 1339 |
|
| 1340 |
async def _progress_streaks(uid: str, today: datetime.date) -> tuple[int, int]:
|
| 1341 |
"""Calculate both normal prayer streak and golden streak.
|
| 1342 |
- Normal streak: consecutive days with all 5 prayers marked.
|
| 1343 |
+
- Golden streak: consecutive days with all 5 prayers + 10m Quran + (10m Hadith OR 99 Tasbeeh)."""
|
| 1344 |
start = (today - datetime.timedelta(days=366)).isoformat()
|
| 1345 |
docs = await daily_progress_collection.find(
|
| 1346 |
{"uid": uid, "date": {"$gte": start}}, {"_id": 0}
|
|
|
|
| 1374 |
"prayers": norm_prayers,
|
| 1375 |
"quran_secs": int(doc.get("quran_secs", 0) or 0),
|
| 1376 |
"hadith_secs": int(doc.get("hadith_secs", 0) or 0),
|
| 1377 |
+
"tasbeeh_count": int(doc.get("tasbeeh_count", 0) or 0),
|
| 1378 |
"streak": streak,
|
| 1379 |
"golden_streak": golden_streak,
|
| 1380 |
"goal_seconds": PROGRESS_GOAL_SECONDS,
|
| 1381 |
+
"goal_tasbeeh": PROGRESS_TASBEEH_GOAL,
|
| 1382 |
"total_goals": PROGRESS_TOTAL_GOALS,
|
| 1383 |
}
|
| 1384 |
|
|
|
|
| 1390 |
today = _progress_local_date(tz)
|
| 1391 |
date_str = today.isoformat()
|
| 1392 |
doc = await daily_progress_collection.find_one({"uid": uid, "date": date_str}, {"_id": 0}) or {}
|
| 1393 |
+
|
| 1394 |
+
# Self-healing fallback: check tasbeeh_collection so tasbeeh deeds never reset to zero
|
| 1395 |
+
t_count = int(doc.get("tasbeeh_count", 0) or 0)
|
| 1396 |
+
sessions = await tasbeeh_collection.find({"uid": uid, "date": date_str}, {"_id": 0, "count": 1}).to_list(length=300)
|
| 1397 |
+
if sessions:
|
| 1398 |
+
sum_sessions = sum(int(s.get("count", 0) or 0) for s in sessions)
|
| 1399 |
+
if sum_sessions > t_count:
|
| 1400 |
+
t_count = sum_sessions
|
| 1401 |
+
doc["tasbeeh_count"] = t_count
|
| 1402 |
+
await daily_progress_collection.update_one(
|
| 1403 |
+
{"uid": uid, "date": date_str},
|
| 1404 |
+
{"$set": {"tasbeeh_count": t_count}, "$setOnInsert": {"uid": uid, "date": date_str}},
|
| 1405 |
+
upsert=True,
|
| 1406 |
+
)
|
| 1407 |
+
|
| 1408 |
streak, golden_streak = await _progress_streaks(uid, today)
|
| 1409 |
return _progress_payload(doc, date_str, streak, golden_streak)
|
| 1410 |
|
|
|
|
| 1472 |
field = "quran_secs" if payload.category == "quran" else "hadith_secs"
|
| 1473 |
|
| 1474 |
doc = await daily_progress_collection.find_one(
|
| 1475 |
+
{"uid": uid, "date": date_str}, {"_id": 0}
|
| 1476 |
) or {}
|
| 1477 |
current = int(doc.get(field, 0) or 0)
|
| 1478 |
if current >= PROGRESS_GOAL_SECONDS:
|
| 1479 |
+
streak, golden_streak = await _progress_streaks(uid, today)
|
| 1480 |
+
return _progress_payload(doc, date_str, streak, golden_streak)
|
| 1481 |
|
| 1482 |
nxt = min(current + payload.seconds, PROGRESS_GOAL_SECONDS)
|
| 1483 |
await daily_progress_collection.update_one(
|
| 1484 |
{"uid": uid, "date": date_str},
|
| 1485 |
+
{"$set": {field: nxt}, "$setOnInsert": {"uid": uid, "date": date_str, "prayers": []}},
|
| 1486 |
upsert=True,
|
| 1487 |
)
|
| 1488 |
+
doc[field] = nxt
|
| 1489 |
+
streak, golden_streak = await _progress_streaks(uid, today)
|
| 1490 |
+
|
| 1491 |
+
# Broadcast realtime event so connected devices / homepage update instantly
|
| 1492 |
+
realtime.publish(uid, "prayer_progress_updated", {
|
| 1493 |
+
"date": date_str,
|
| 1494 |
+
field: nxt,
|
| 1495 |
+
})
|
| 1496 |
+
return _progress_payload(doc, date_str, streak, golden_streak)
|
| 1497 |
|
| 1498 |
|
| 1499 |
# =========================================================
|
|
|
|
| 1618 |
{"uid": uid, "date": {"$gte": start_date, "$lte": end_date}}, {"_id": 0}
|
| 1619 |
).sort("date", 1).to_list(length=100)
|
| 1620 |
|
| 1621 |
+
# Fetch tasbeeh sessions for the date range to guarantee all deeds are included
|
| 1622 |
+
tasbeeh_sessions = await tasbeeh_collection.find(
|
| 1623 |
+
{"uid": uid, "date": {"$gte": start_date, "$lte": end_date}}, {"_id": 0, "date": 1, "count": 1}
|
| 1624 |
+
).to_list(length=1000)
|
| 1625 |
+
tasbeeh_by_date = {}
|
| 1626 |
+
for ts in tasbeeh_sessions:
|
| 1627 |
+
ts_date = ts.get("date")
|
| 1628 |
+
if ts_date:
|
| 1629 |
+
tasbeeh_by_date[ts_date] = tasbeeh_by_date.get(ts_date, 0) + int(ts.get("count", 0) or 0)
|
| 1630 |
+
|
| 1631 |
docs_by_date = {d["date"]: d for d in docs}
|
| 1632 |
days_list = []
|
| 1633 |
prayer_counts = {"Fajr": 0, "Dhuhr": 0, "Asr": 0, "Maghrib": 0, "Isha": 0}
|
|
|
|
| 1642 |
is_full = len(prayers) == 5
|
| 1643 |
q_secs = int(item.get("quran_secs", 0) or 0)
|
| 1644 |
h_secs = int(item.get("hadith_secs", 0) or 0)
|
| 1645 |
+
t_count = max(int(item.get("tasbeeh_count", 0) or 0), tasbeeh_by_date.get(d, 0))
|
| 1646 |
+
is_golden = is_full and (q_secs >= PROGRESS_GOAL_SECONDS) and (h_secs >= PROGRESS_GOAL_SECONDS or t_count >= PROGRESS_TASBEEH_GOAL)
|
| 1647 |
|
| 1648 |
if is_full:
|
| 1649 |
full_days += 1
|
|
|
|
| 1662 |
"is_golden": is_golden,
|
| 1663 |
"quran_secs": q_secs,
|
| 1664 |
"hadith_secs": h_secs,
|
| 1665 |
+
"tasbeeh_count": t_count,
|
| 1666 |
})
|
| 1667 |
|
| 1668 |
# Elapsed days calculation (so future unelapsed days don't falsely register as missed)
|
|
|
|
| 1713 |
}
|
| 1714 |
|
| 1715 |
|
| 1716 |
+
@router.get('/progress/recorded-missed')
|
| 1717 |
+
@limiter.limit("60/minute")
|
| 1718 |
+
async def get_recorded_missed_prayers(request: Request, tz: float = 0.0, user: dict = Depends(get_current_user)):
|
| 1719 |
+
"""Calculates all-time completed and missed prayers across all recorded daily progress data."""
|
| 1720 |
+
uid = user["uid"]
|
| 1721 |
+
today = _progress_local_date(tz)
|
| 1722 |
+
today_str = today.isoformat()
|
| 1723 |
+
|
| 1724 |
+
docs = await daily_progress_collection.find(
|
| 1725 |
+
{"uid": uid}, {"_id": 0, "date": 1, "prayers": 1, "quran_secs": 1, "hadith_secs": 1, "tasbeeh_count": 1}
|
| 1726 |
+
).to_list(length=3000)
|
| 1727 |
+
|
| 1728 |
+
missed_counts = {"Fajr": 0, "Dhuhr": 0, "Asr": 0, "Maghrib": 0, "Isha": 0}
|
| 1729 |
+
prayed_counts = {"Fajr": 0, "Dhuhr": 0, "Asr": 0, "Maghrib": 0, "Isha": 0}
|
| 1730 |
+
total_quran_days = 0
|
| 1731 |
+
total_golden_days = 0
|
| 1732 |
+
|
| 1733 |
+
for doc in docs:
|
| 1734 |
+
d_str = doc.get("date")
|
| 1735 |
+
if not d_str:
|
| 1736 |
+
continue
|
| 1737 |
+
raw_prayers = doc.get("prayers", []) or []
|
| 1738 |
+
norm_set = set(_normalize_progress_prayer_name(p) for p in raw_prayers if _normalize_progress_prayer_name(p))
|
| 1739 |
+
|
| 1740 |
+
# Only count missed prayers for past dates (today is in-progress)
|
| 1741 |
+
is_past = d_str < today_str
|
| 1742 |
+
for p in PROGRESS_PRAYERS:
|
| 1743 |
+
if p in norm_set:
|
| 1744 |
+
prayed_counts[p] += 1
|
| 1745 |
+
elif is_past:
|
| 1746 |
+
missed_counts[p] += 1
|
| 1747 |
+
|
| 1748 |
+
q_secs = int(doc.get("quran_secs", 0) or 0)
|
| 1749 |
+
h_secs = int(doc.get("hadith_secs", 0) or 0)
|
| 1750 |
+
t_count = int(doc.get("tasbeeh_count", 0) or 0)
|
| 1751 |
+
if q_secs >= PROGRESS_GOAL_SECONDS:
|
| 1752 |
+
total_quran_days += 1
|
| 1753 |
+
if len(norm_set) == 5 and q_secs >= PROGRESS_GOAL_SECONDS and (h_secs >= PROGRESS_GOAL_SECONDS or t_count >= PROGRESS_TASBEEH_GOAL):
|
| 1754 |
+
total_golden_days += 1
|
| 1755 |
+
|
| 1756 |
+
total_missed = sum(missed_counts.values())
|
| 1757 |
+
total_prayed = sum(prayed_counts.values())
|
| 1758 |
+
|
| 1759 |
+
return {
|
| 1760 |
+
"total_days": len(docs),
|
| 1761 |
+
"missed": missed_counts,
|
| 1762 |
+
"prayed": prayed_counts,
|
| 1763 |
+
"total_missed": total_missed,
|
| 1764 |
+
"total_prayed": total_prayed,
|
| 1765 |
+
"total_quran_days": total_quran_days,
|
| 1766 |
+
"total_golden_days": total_golden_days,
|
| 1767 |
+
}
|
| 1768 |
+
|
| 1769 |
+
|
| 1770 |
+
# =========================================================
|
| 1771 |
+
# 11b. TASBEEH & DHIKR PERSISTENCE & 30-DAY CONSISTENCY
|
| 1772 |
+
# =========================================================
|
| 1773 |
+
|
| 1774 |
+
class TasbeehLogReq(BaseModel):
|
| 1775 |
+
count: int = Field(..., ge=1, le=100000)
|
| 1776 |
+
dhikr: str = Field("Subhan Allah", max_length=150)
|
| 1777 |
+
arabic: Optional[str] = Field("", max_length=150)
|
| 1778 |
+
laps: int = Field(0, ge=0)
|
| 1779 |
+
target: int = Field(33, ge=0)
|
| 1780 |
+
duration_seconds: int = Field(0, ge=0)
|
| 1781 |
+
date: Optional[str] = None # YYYY-MM-DD local date
|
| 1782 |
+
tz: float = Field(default=0.0, ge=-12, le=14)
|
| 1783 |
+
|
| 1784 |
+
|
| 1785 |
+
@router.post('/tasbeeh/log')
|
| 1786 |
+
@limiter.limit("120/minute")
|
| 1787 |
+
async def log_tasbeeh_session(
|
| 1788 |
+
payload: TasbeehLogReq,
|
| 1789 |
+
request: Request,
|
| 1790 |
+
user: dict = Depends(get_current_user)
|
| 1791 |
+
):
|
| 1792 |
+
uid = user["uid"]
|
| 1793 |
+
date_str = payload.date or _progress_local_date(payload.tz).isoformat()
|
| 1794 |
+
now_utc = datetime.datetime.utcnow().isoformat() + "Z"
|
| 1795 |
+
|
| 1796 |
+
session_doc = {
|
| 1797 |
+
"uid": uid,
|
| 1798 |
+
"date": date_str,
|
| 1799 |
+
"timestamp": now_utc,
|
| 1800 |
+
"count": payload.count,
|
| 1801 |
+
"dhikr": payload.dhikr,
|
| 1802 |
+
"arabic": payload.arabic or "",
|
| 1803 |
+
"laps": payload.laps,
|
| 1804 |
+
"target": payload.target,
|
| 1805 |
+
"duration_seconds": payload.duration_seconds,
|
| 1806 |
+
}
|
| 1807 |
+
await tasbeeh_collection.insert_one(session_doc)
|
| 1808 |
+
|
| 1809 |
+
# Accumulate into daily_progress_collection
|
| 1810 |
+
await daily_progress_collection.update_one(
|
| 1811 |
+
{"uid": uid, "date": date_str},
|
| 1812 |
+
{
|
| 1813 |
+
"$inc": {"tasbeeh_count": payload.count},
|
| 1814 |
+
"$setOnInsert": {
|
| 1815 |
+
"uid": uid,
|
| 1816 |
+
"date": date_str,
|
| 1817 |
+
"prayers": [],
|
| 1818 |
+
"quran_secs": 0,
|
| 1819 |
+
"hadith_secs": 0
|
| 1820 |
+
}
|
| 1821 |
+
},
|
| 1822 |
+
upsert=True
|
| 1823 |
+
)
|
| 1824 |
+
|
| 1825 |
+
# Query updated doc to get full persistent count and publish real-time update
|
| 1826 |
+
updated_doc = await daily_progress_collection.find_one({"uid": uid, "date": date_str}, {"_id": 0}) or {}
|
| 1827 |
+
new_tasbeeh_count = int(updated_doc.get("tasbeeh_count", 0) or payload.count)
|
| 1828 |
+
|
| 1829 |
+
realtime.publish(uid, "prayer_progress_updated", {
|
| 1830 |
+
"date": date_str,
|
| 1831 |
+
"tasbeeh_count": new_tasbeeh_count,
|
| 1832 |
+
})
|
| 1833 |
+
|
| 1834 |
+
return {
|
| 1835 |
+
"status": "success",
|
| 1836 |
+
"logged_count": payload.count,
|
| 1837 |
+
"tasbeeh_count": new_tasbeeh_count,
|
| 1838 |
+
"date": date_str,
|
| 1839 |
+
}
|
| 1840 |
+
|
| 1841 |
+
|
| 1842 |
+
@router.get('/tasbeeh/summary')
|
| 1843 |
+
@limiter.limit("60/minute")
|
| 1844 |
+
async def get_tasbeeh_summary(
|
| 1845 |
+
request: Request,
|
| 1846 |
+
tz: float = 0.0,
|
| 1847 |
+
user: dict = Depends(get_current_user)
|
| 1848 |
+
):
|
| 1849 |
+
uid = user["uid"]
|
| 1850 |
+
today = _progress_local_date(tz)
|
| 1851 |
+
start_date = (today - datetime.timedelta(days=29)).isoformat()
|
| 1852 |
+
end_date = today.isoformat()
|
| 1853 |
+
today_str = today.isoformat()
|
| 1854 |
+
|
| 1855 |
+
# Query last 30 days sessions
|
| 1856 |
+
docs = await tasbeeh_collection.find(
|
| 1857 |
+
{"uid": uid, "date": {"$gte": start_date, "$lte": end_date}},
|
| 1858 |
+
{"_id": 0}
|
| 1859 |
+
).sort("timestamp", -1).to_list(length=500)
|
| 1860 |
+
|
| 1861 |
+
today_count = 0
|
| 1862 |
+
month_total = 0
|
| 1863 |
+
total_seconds = 0
|
| 1864 |
+
active_dates = set()
|
| 1865 |
+
daily_sums = {}
|
| 1866 |
+
dhikr_counts = {}
|
| 1867 |
+
|
| 1868 |
+
for d in docs:
|
| 1869 |
+
c = int(d.get("count", 0) or 0)
|
| 1870 |
+
month_total += c
|
| 1871 |
+
total_seconds += int(d.get("duration_seconds", 0) or 0)
|
| 1872 |
+
dt = d.get("date")
|
| 1873 |
+
if dt:
|
| 1874 |
+
active_dates.add(dt)
|
| 1875 |
+
daily_sums[dt] = daily_sums.get(dt, 0) + c
|
| 1876 |
+
if dt == today_str:
|
| 1877 |
+
today_count += c
|
| 1878 |
+
dhikr_name = d.get("dhikr") or "General Dhikr"
|
| 1879 |
+
dhikr_counts[dhikr_name] = dhikr_counts.get(dhikr_name, 0) + c
|
| 1880 |
+
|
| 1881 |
+
# Cross-check with daily_progress_collection so today's count never resets to zero
|
| 1882 |
+
daily_doc = await daily_progress_collection.find_one({"uid": uid, "date": today_str}, {"_id": 0, "tasbeeh_count": 1}) or {}
|
| 1883 |
+
daily_tasbeeh = int(daily_doc.get("tasbeeh_count", 0) or 0)
|
| 1884 |
+
today_count = max(today_count, daily_tasbeeh)
|
| 1885 |
+
if today_count > 0:
|
| 1886 |
+
active_dates.add(today_str)
|
| 1887 |
+
month_total = max(month_total, today_count)
|
| 1888 |
+
|
| 1889 |
+
best_day_count = max(daily_sums.values()) if daily_sums else today_count
|
| 1890 |
+
best_day_count = max(best_day_count, today_count)
|
| 1891 |
+
avg_daily = round(month_total / 30.0) if month_total > 0 else 0
|
| 1892 |
+
|
| 1893 |
+
# Top Dhikrs breakdown
|
| 1894 |
+
sorted_dhikrs = sorted(dhikr_counts.items(), key=lambda x: x[1], reverse=True)
|
| 1895 |
+
top_dhikrs = []
|
| 1896 |
+
for name, c in sorted_dhikrs[:8]:
|
| 1897 |
+
pct = round((c / float(month_total)) * 100, 1) if month_total > 0 else 0.0
|
| 1898 |
+
top_dhikrs.append({"dhikr": name, "count": c, "pct": pct})
|
| 1899 |
+
|
| 1900 |
+
# Recent 25 sessions for detailed statistics sheet
|
| 1901 |
+
recent_sessions = docs[:25]
|
| 1902 |
+
|
| 1903 |
+
# Calculate streak of active Dhikr days ending today or yesterday
|
| 1904 |
+
streak = 0
|
| 1905 |
+
check_date = today
|
| 1906 |
+
if today_str not in active_dates:
|
| 1907 |
+
check_date = today - datetime.timedelta(days=1)
|
| 1908 |
+
|
| 1909 |
+
while check_date.isoformat() in active_dates:
|
| 1910 |
+
streak += 1
|
| 1911 |
+
check_date -= datetime.timedelta(days=1)
|
| 1912 |
+
|
| 1913 |
+
return {
|
| 1914 |
+
"today_count": today_count,
|
| 1915 |
+
"month_total": month_total,
|
| 1916 |
+
"active_days": len(active_dates),
|
| 1917 |
+
"streak_days": streak,
|
| 1918 |
+
"best_day_count": best_day_count,
|
| 1919 |
+
"avg_daily": avg_daily,
|
| 1920 |
+
"total_seconds": total_seconds,
|
| 1921 |
+
"top_dhikrs": top_dhikrs,
|
| 1922 |
+
"recent_sessions": recent_sessions,
|
| 1923 |
+
"date": today_str,
|
| 1924 |
+
}
|
| 1925 |
+
|
| 1926 |
+
|
| 1927 |
class RequestEmailChangeReq(BaseModel):
|
| 1928 |
new_email: str = Field(..., min_length=5, max_length=150)
|
| 1929 |
|
app/database.py
CHANGED
|
@@ -26,18 +26,18 @@ class AsyncDatabase:
|
|
| 26 |
if cls._instance is None:
|
| 27 |
cls._instance = super(AsyncDatabase, cls).__new__(cls)
|
| 28 |
|
| 29 |
-
# 🚀 ENTERPRISE CONNECTION POOLING (
|
| 30 |
cls._client = AsyncIOMotorClient(
|
| 31 |
MONGO_URI,
|
| 32 |
-
maxPoolSize=
|
| 33 |
-
minPoolSize=
|
| 34 |
-
maxIdleTimeMS=
|
| 35 |
-
waitQueueTimeoutMS=
|
| 36 |
-
connectTimeoutMS=
|
| 37 |
-
serverSelectionTimeoutMS=
|
| 38 |
retryWrites=True
|
| 39 |
)
|
| 40 |
-
print("🚀 Enterprise Async Connection Pool Initialized (Tuned
|
| 41 |
return cls._instance
|
| 42 |
|
| 43 |
@property
|
|
@@ -86,6 +86,7 @@ daily_ayah_pool_collection = db["daily_ayah_pool"]
|
|
| 86 |
# devices and survive a reinstall.
|
| 87 |
daily_progress_collection = db["daily_progress"]
|
| 88 |
qaza_collection = db["qaza_tracker"]
|
|
|
|
| 89 |
|
| 90 |
# 🚀 MASJID EVENTS
|
| 91 |
# Events posted by masjid admins/co-admins for public viewing
|
|
|
|
| 26 |
if cls._instance is None:
|
| 27 |
cls._instance = super(AsyncDatabase, cls).__new__(cls)
|
| 28 |
|
| 29 |
+
# 🚀 ENTERPRISE CONNECTION POOLING (Resilient Atlas M0/Dedicated Pool Sizing)
|
| 30 |
cls._client = AsyncIOMotorClient(
|
| 31 |
MONGO_URI,
|
| 32 |
+
maxPoolSize=35, # Safe per-worker limit to avoid Atlas 500-conn starvation
|
| 33 |
+
minPoolSize=5, # Keep 5 persistent pipes warm per worker
|
| 34 |
+
maxIdleTimeMS=30000, # Recycle idle connections every 30s
|
| 35 |
+
waitQueueTimeoutMS=3000, # Fast fail-over (3s) under extreme queue pressure
|
| 36 |
+
connectTimeoutMS=8000, # TCP connect timeout
|
| 37 |
+
serverSelectionTimeoutMS=4000, # Fail fast (4s) if primary replica becomes unreachable
|
| 38 |
retryWrites=True
|
| 39 |
)
|
| 40 |
+
print("🚀 Enterprise Async Connection Pool Initialized (Tuned: 35 max, 5 min, 3s queue timeout)")
|
| 41 |
return cls._instance
|
| 42 |
|
| 43 |
@property
|
|
|
|
| 86 |
# devices and survive a reinstall.
|
| 87 |
daily_progress_collection = db["daily_progress"]
|
| 88 |
qaza_collection = db["qaza_tracker"]
|
| 89 |
+
tasbeeh_collection = db["tasbeeh_records"]
|
| 90 |
|
| 91 |
# 🚀 MASJID EVENTS
|
| 92 |
# Events posted by masjid admins/co-admins for public viewing
|
app/payment_routes.py
CHANGED
|
@@ -695,6 +695,10 @@ async def get_user_transactions(
|
|
| 695 |
"status": tx.get("status", "completed"),
|
| 696 |
"reference_id": tx.get("reference_id"),
|
| 697 |
"payment_method": tx.get("payment_method", "wallet"),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 698 |
}
|
| 699 |
for tx in tx_list
|
| 700 |
]
|
|
|
|
| 695 |
"status": tx.get("status", "completed"),
|
| 696 |
"reference_id": tx.get("reference_id"),
|
| 697 |
"payment_method": tx.get("payment_method", "wallet"),
|
| 698 |
+
"tag": tx.get("tag"),
|
| 699 |
+
"name": tx.get("name"),
|
| 700 |
+
"why": tx.get("why"),
|
| 701 |
+
"validity": tx.get("validity"),
|
| 702 |
}
|
| 703 |
for tx in tx_list
|
| 704 |
]
|
app/r2_config.py
CHANGED
|
@@ -10,30 +10,71 @@ from typing import Optional
|
|
| 10 |
|
| 11 |
# R2 Bucket Configuration
|
| 12 |
R2_ACCOUNT_ID = os.getenv("CLOUDFLARE_ACCOUNT_ID", "d7fc285dc6825480f6d8c887f93e7084")
|
| 13 |
-
R2_BUCKET_NAME = "sahihislam"
|
| 14 |
R2_ACCESS_KEY_ID = os.getenv("R2_ACCESS_KEY_ID")
|
| 15 |
R2_SECRET_ACCESS_KEY = os.getenv("R2_SECRET_ACCESS_KEY")
|
|
|
|
| 16 |
|
| 17 |
# R2 Endpoint
|
| 18 |
R2_ENDPOINT = f"https://{R2_ACCOUNT_ID}.r2.cloudflarestorage.com"
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
# Initialize S3 client for R2 (R2 is S3-compatible)
|
| 21 |
def get_r2_client():
|
| 22 |
-
"""Get boto3 S3 client configured for Cloudflare R2"""
|
| 23 |
if not R2_ACCESS_KEY_ID or not R2_SECRET_ACCESS_KEY:
|
| 24 |
-
|
| 25 |
-
"R2 credentials not configured. Set R2_ACCESS_KEY_ID and "
|
| 26 |
-
"R2_SECRET_ACCESS_KEY in environment variables."
|
| 27 |
-
)
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
# Asset Folders
|
| 39 |
R2_QURAN_TAFSEER_FOLDER = "quran_tafseer"
|
|
@@ -41,37 +82,32 @@ R2_QAIDA_AUDIO_FOLDER = "qaida_audio"
|
|
| 41 |
R2_NIMAZ_AUDIO_FOLDER = "Nimaz_Mutarjam_audio"
|
| 42 |
|
| 43 |
# Signed URL expiration (in seconds)
|
| 44 |
-
# 3600 = 1 hour (default)
|
| 45 |
-
# 86400 = 24 hours
|
| 46 |
-
# 604800 = 7 days
|
| 47 |
-
# 2592000 = 30 days (maximum recommended)
|
| 48 |
SIGNED_URL_EXPIRATION = 86400 # 24 hours - good balance of security and performance
|
| 49 |
|
| 50 |
|
| 51 |
def generate_signed_url(object_key: str, expiration: int = SIGNED_URL_EXPIRATION) -> str:
|
| 52 |
"""
|
| 53 |
-
Generate a temporary signed URL for accessing a private R2 object
|
| 54 |
-
|
| 55 |
-
Args:
|
| 56 |
-
object_key: Full path to object in bucket (e.g., "quran_tafseer/Al_Fatihah_Tafseer.json")
|
| 57 |
-
expiration: URL expiration time in seconds (default: 1 hour)
|
| 58 |
-
|
| 59 |
-
Returns:
|
| 60 |
-
Presigned URL string
|
| 61 |
"""
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
|
| 77 |
def get_tafseer_url(filename: str, signed: bool = True) -> str:
|
|
@@ -82,28 +118,69 @@ def get_tafseer_url(filename: str, signed: bool = True) -> str:
|
|
| 82 |
object_key = f"{R2_QURAN_TAFSEER_FOLDER}/{filename}"
|
| 83 |
if signed:
|
| 84 |
return generate_signed_url(object_key)
|
|
|
|
|
|
|
| 85 |
return f"{R2_ENDPOINT}/{R2_BUCKET_NAME}/{object_key}"
|
| 86 |
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
def get_qaida_audio_url(filename: str, signed: bool = True) -> str:
|
| 89 |
"""
|
| 90 |
-
Get
|
| 91 |
-
Example: lesson_01.mp3
|
| 92 |
"""
|
| 93 |
-
|
|
|
|
| 94 |
if signed:
|
| 95 |
return generate_signed_url(object_key)
|
|
|
|
|
|
|
| 96 |
return f"{R2_ENDPOINT}/{R2_BUCKET_NAME}/{object_key}"
|
| 97 |
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
def get_nimaz_audio_url(filename: str, signed: bool = True) -> str:
|
| 100 |
"""
|
| 101 |
-
Get
|
| 102 |
-
Example:
|
| 103 |
"""
|
| 104 |
-
|
|
|
|
| 105 |
if signed:
|
| 106 |
return generate_signed_url(object_key)
|
|
|
|
|
|
|
| 107 |
return f"{R2_ENDPOINT}/{R2_BUCKET_NAME}/{object_key}"
|
| 108 |
|
| 109 |
|
|
@@ -126,7 +203,7 @@ def get_tafseer_by_surah(surah_number: int, signed: bool = True) -> str:
|
|
| 126 |
SURAH_NAMES = {
|
| 127 |
1: "Al_Fatihah_Tafseer.json",
|
| 128 |
2: "Al_Baqarah_Tafseer.json",
|
| 129 |
-
3: "
|
| 130 |
4: "An_Nisa_Tafseer.json",
|
| 131 |
5: "Al_Maidah_Tafseer.json",
|
| 132 |
6: "Al_Anam_Tafseer.json",
|
|
@@ -144,7 +221,7 @@ SURAH_NAMES = {
|
|
| 144 |
18: "Al_Kahf_Tafseer.json",
|
| 145 |
19: "Maryam_Tafseer.json",
|
| 146 |
20: "Ta_Ha_Tafseer.json",
|
| 147 |
-
21: "
|
| 148 |
22: "Al_Hajj_Tafseer.json",
|
| 149 |
23: "Al_Muminun_Tafseer.json",
|
| 150 |
24: "An_Nur_Tafseer.json",
|
|
@@ -165,7 +242,7 @@ SURAH_NAMES = {
|
|
| 165 |
39: "Az_Zumar_Tafseer.json",
|
| 166 |
40: "Ghafir_Tafseer.json",
|
| 167 |
41: "Fussilat_Tafseer.json",
|
| 168 |
-
42: "
|
| 169 |
43: "Az_Zukhruf_Tafseer.json",
|
| 170 |
44: "Ad_Dukhan_Tafseer.json",
|
| 171 |
45: "Al_Jathiyah_Tafseer.json",
|
|
@@ -184,7 +261,7 @@ SURAH_NAMES = {
|
|
| 184 |
58: "Al_Mujadilah_Tafseer.json",
|
| 185 |
59: "Al_Hashr_Tafseer.json",
|
| 186 |
60: "Al_Mumtahanah_Tafseer.json",
|
| 187 |
-
61: "
|
| 188 |
62: "Al_Jumuah_Tafseer.json",
|
| 189 |
63: "Al_Munafiqun_Tafseer.json",
|
| 190 |
64: "At_Taghabun_Tafseer.json",
|
|
@@ -215,8 +292,8 @@ SURAH_NAMES = {
|
|
| 215 |
89: "Al_Fajr_Tafseer.json",
|
| 216 |
90: "Al_Balad_Tafseer.json",
|
| 217 |
91: "Ash_Shams_Tafseer.json",
|
| 218 |
-
92: "
|
| 219 |
-
93: "
|
| 220 |
94: "Ash_Sharh_Tafseer.json",
|
| 221 |
95: "At_Tin_Tafseer.json",
|
| 222 |
96: "Al_Alaq_Tafseer.json",
|
|
@@ -229,9 +306,9 @@ SURAH_NAMES = {
|
|
| 229 |
103: "Al_Asr_Tafseer.json",
|
| 230 |
104: "Al_Humazah_Tafseer.json",
|
| 231 |
105: "Al_Fil_Tafseer.json",
|
| 232 |
-
106: "
|
| 233 |
107: "Al_Maun_Tafseer.json",
|
| 234 |
-
108: "
|
| 235 |
109: "Al_Kafirun_Tafseer.json",
|
| 236 |
110: "An_Nasr_Tafseer.json",
|
| 237 |
111: "Al_Masad_Tafseer.json",
|
|
|
|
| 10 |
|
| 11 |
# R2 Bucket Configuration
|
| 12 |
R2_ACCOUNT_ID = os.getenv("CLOUDFLARE_ACCOUNT_ID", "d7fc285dc6825480f6d8c887f93e7084")
|
| 13 |
+
R2_BUCKET_NAME = os.getenv("R2_BUCKET_NAME", "sahihislam")
|
| 14 |
R2_ACCESS_KEY_ID = os.getenv("R2_ACCESS_KEY_ID")
|
| 15 |
R2_SECRET_ACCESS_KEY = os.getenv("R2_SECRET_ACCESS_KEY")
|
| 16 |
+
R2_PUBLIC_URL = os.getenv("R2_PUBLIC_URL", "").rstrip("/")
|
| 17 |
|
| 18 |
# R2 Endpoint
|
| 19 |
R2_ENDPOINT = f"https://{R2_ACCOUNT_ID}.r2.cloudflarestorage.com"
|
| 20 |
|
| 21 |
+
# Mapping of letter names to their R2 global numbered audio filenames
|
| 22 |
+
# Sabaq 1 (Mufrad Huroof): Letter 1 (Alif) = 4.mp3, Letter 2 (Baa) = 5.mp3, etc.
|
| 23 |
+
LETTER_NAME_TO_AUDIO_ID = {
|
| 24 |
+
"alif": "4.mp3",
|
| 25 |
+
"baa": "5.mp3",
|
| 26 |
+
"taa": "6.mp3",
|
| 27 |
+
"thaa": "7.mp3",
|
| 28 |
+
"jeem": "8.mp3",
|
| 29 |
+
"haa": "9.mp3",
|
| 30 |
+
"khaa": "10.mp3",
|
| 31 |
+
"daal": "11.mp3",
|
| 32 |
+
"thaal": "12.mp3",
|
| 33 |
+
"raa": "13.mp3",
|
| 34 |
+
"zaa": "14.mp3",
|
| 35 |
+
"seen": "15.mp3",
|
| 36 |
+
"sheen": "16.mp3",
|
| 37 |
+
"saad": "17.mp3",
|
| 38 |
+
"daad": "18.mp3",
|
| 39 |
+
"toot": "19.mp3",
|
| 40 |
+
"toa": "19.mp3",
|
| 41 |
+
"taa_heavy": "19.mp3",
|
| 42 |
+
"zhaa": "20.mp3",
|
| 43 |
+
"zoa": "20.mp3",
|
| 44 |
+
"zaa_heavy": "20.mp3",
|
| 45 |
+
"ayn": "21.mp3",
|
| 46 |
+
"ghayn": "22.mp3",
|
| 47 |
+
"faa": "23.mp3",
|
| 48 |
+
"qaaf": "24.mp3",
|
| 49 |
+
"kaaf": "25.mp3",
|
| 50 |
+
"laam": "26.mp3",
|
| 51 |
+
"meem": "27.mp3",
|
| 52 |
+
"noon": "28.mp3",
|
| 53 |
+
"waw": "29.mp3",
|
| 54 |
+
"haa_round": "30.mp3",
|
| 55 |
+
"hamzah": "31.mp3",
|
| 56 |
+
"yaa": "32.mp3",
|
| 57 |
+
"yaa_small": "33.mp3",
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
# Initialize S3 client for R2 (R2 is S3-compatible)
|
| 61 |
def get_r2_client():
|
| 62 |
+
"""Get boto3 S3 client configured for Cloudflare R2, or None if credentials missing"""
|
| 63 |
if not R2_ACCESS_KEY_ID or not R2_SECRET_ACCESS_KEY:
|
| 64 |
+
return None
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
try:
|
| 67 |
+
return boto3.client(
|
| 68 |
+
's3',
|
| 69 |
+
endpoint_url=R2_ENDPOINT,
|
| 70 |
+
aws_access_key_id=R2_ACCESS_KEY_ID,
|
| 71 |
+
aws_secret_access_key=R2_SECRET_ACCESS_KEY,
|
| 72 |
+
config=Config(signature_version='s3v4'),
|
| 73 |
+
region_name='auto' # R2 uses 'auto' as region
|
| 74 |
+
)
|
| 75 |
+
except Exception as e:
|
| 76 |
+
print(f"Error initializing R2 S3 client: {e}")
|
| 77 |
+
return None
|
| 78 |
|
| 79 |
# Asset Folders
|
| 80 |
R2_QURAN_TAFSEER_FOLDER = "quran_tafseer"
|
|
|
|
| 82 |
R2_NIMAZ_AUDIO_FOLDER = "Nimaz_Mutarjam_audio"
|
| 83 |
|
| 84 |
# Signed URL expiration (in seconds)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
SIGNED_URL_EXPIRATION = 86400 # 24 hours - good balance of security and performance
|
| 86 |
|
| 87 |
|
| 88 |
def generate_signed_url(object_key: str, expiration: int = SIGNED_URL_EXPIRATION) -> str:
|
| 89 |
"""
|
| 90 |
+
Generate a temporary signed URL for accessing a private R2 object,
|
| 91 |
+
or falls back to public/direct URL if S3 credentials not configured.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
"""
|
| 93 |
+
s3_client = get_r2_client()
|
| 94 |
+
if s3_client:
|
| 95 |
+
try:
|
| 96 |
+
return s3_client.generate_presigned_url(
|
| 97 |
+
'get_object',
|
| 98 |
+
Params={
|
| 99 |
+
'Bucket': R2_BUCKET_NAME,
|
| 100 |
+
'Key': object_key
|
| 101 |
+
},
|
| 102 |
+
ExpiresIn=expiration
|
| 103 |
+
)
|
| 104 |
+
except ClientError as e:
|
| 105 |
+
print(f"Failed to generate signed URL: {e}")
|
| 106 |
+
|
| 107 |
+
# Fallback: direct public URL or Cloudflare R2 endpoint
|
| 108 |
+
if R2_PUBLIC_URL:
|
| 109 |
+
return f"{R2_PUBLIC_URL}/{object_key}"
|
| 110 |
+
return f"{R2_ENDPOINT}/{R2_BUCKET_NAME}/{object_key}"
|
| 111 |
|
| 112 |
|
| 113 |
def get_tafseer_url(filename: str, signed: bool = True) -> str:
|
|
|
|
| 118 |
object_key = f"{R2_QURAN_TAFSEER_FOLDER}/{filename}"
|
| 119 |
if signed:
|
| 120 |
return generate_signed_url(object_key)
|
| 121 |
+
if R2_PUBLIC_URL:
|
| 122 |
+
return f"{R2_PUBLIC_URL}/{object_key}"
|
| 123 |
return f"{R2_ENDPOINT}/{R2_BUCKET_NAME}/{object_key}"
|
| 124 |
|
| 125 |
|
| 126 |
+
def resolve_qaida_filename(filename: str) -> str:
|
| 127 |
+
"""
|
| 128 |
+
Normalize filename to match R2 bucket layout:
|
| 129 |
+
- Strips 'numbered/' or 'qaida_audio/' prefixes
|
| 130 |
+
- Resolves letter names (e.g., 'alif.mp3' -> '4.mp3', 'baa.mp3' -> '5.mp3')
|
| 131 |
+
"""
|
| 132 |
+
clean_name = filename.strip("/").replace("\\", "/")
|
| 133 |
+
if clean_name.startswith("qaida_audio/"):
|
| 134 |
+
clean_name = clean_name[len("qaida_audio/"):]
|
| 135 |
+
if clean_name.startswith("numbered/"):
|
| 136 |
+
clean_name = clean_name[len("numbered/"):]
|
| 137 |
+
|
| 138 |
+
# Check letter name mapping
|
| 139 |
+
name_no_ext = clean_name.rsplit(".", 1)[0].lower()
|
| 140 |
+
if name_no_ext in LETTER_NAME_TO_AUDIO_ID:
|
| 141 |
+
return LETTER_NAME_TO_AUDIO_ID[name_no_ext]
|
| 142 |
+
|
| 143 |
+
return clean_name
|
| 144 |
+
|
| 145 |
+
|
| 146 |
def get_qaida_audio_url(filename: str, signed: bool = True) -> str:
|
| 147 |
"""
|
| 148 |
+
Get URL for Qaida audio file in R2 (qaida_audio/{resolved_filename})
|
|
|
|
| 149 |
"""
|
| 150 |
+
resolved_file = resolve_qaida_filename(filename)
|
| 151 |
+
object_key = f"{R2_QAIDA_AUDIO_FOLDER}/{resolved_file}"
|
| 152 |
if signed:
|
| 153 |
return generate_signed_url(object_key)
|
| 154 |
+
if R2_PUBLIC_URL:
|
| 155 |
+
return f"{R2_PUBLIC_URL}/{object_key}"
|
| 156 |
return f"{R2_ENDPOINT}/{R2_BUCKET_NAME}/{object_key}"
|
| 157 |
|
| 158 |
|
| 159 |
+
def resolve_nimaz_filename(filename: str) -> str:
|
| 160 |
+
"""
|
| 161 |
+
Normalize filename for Nimaz Mutarjam audio in R2:
|
| 162 |
+
- Strips 'Nimaz_Mutarjam_audio/' or 'nimaz/' prefix
|
| 163 |
+
- Ensures clean path for R2 key
|
| 164 |
+
"""
|
| 165 |
+
clean_name = filename.strip("/").replace("\\", "/")
|
| 166 |
+
if clean_name.startswith("Nimaz_Mutarjam_audio/"):
|
| 167 |
+
clean_name = clean_name[len("Nimaz_Mutarjam_audio/"):]
|
| 168 |
+
if clean_name.startswith("nimaz/"):
|
| 169 |
+
clean_name = clean_name[len("nimaz/"):]
|
| 170 |
+
return clean_name
|
| 171 |
+
|
| 172 |
+
|
| 173 |
def get_nimaz_audio_url(filename: str, signed: bool = True) -> str:
|
| 174 |
"""
|
| 175 |
+
Get URL for Nimaz Mutarjam audio file in R2 (Nimaz_Mutarjam_audio/{clean_name})
|
| 176 |
+
Example: A1.m4a, H1.m4a, etc.
|
| 177 |
"""
|
| 178 |
+
clean_name = resolve_nimaz_filename(filename)
|
| 179 |
+
object_key = f"{R2_NIMAZ_AUDIO_FOLDER}/{clean_name}"
|
| 180 |
if signed:
|
| 181 |
return generate_signed_url(object_key)
|
| 182 |
+
if R2_PUBLIC_URL:
|
| 183 |
+
return f"{R2_PUBLIC_URL}/{object_key}"
|
| 184 |
return f"{R2_ENDPOINT}/{R2_BUCKET_NAME}/{object_key}"
|
| 185 |
|
| 186 |
|
|
|
|
| 203 |
SURAH_NAMES = {
|
| 204 |
1: "Al_Fatihah_Tafseer.json",
|
| 205 |
2: "Al_Baqarah_Tafseer.json",
|
| 206 |
+
3: "Aal_Imran_Tafseer.json",
|
| 207 |
4: "An_Nisa_Tafseer.json",
|
| 208 |
5: "Al_Maidah_Tafseer.json",
|
| 209 |
6: "Al_Anam_Tafseer.json",
|
|
|
|
| 221 |
18: "Al_Kahf_Tafseer.json",
|
| 222 |
19: "Maryam_Tafseer.json",
|
| 223 |
20: "Ta_Ha_Tafseer.json",
|
| 224 |
+
21: "Al_Anbiya_Tafseer.json",
|
| 225 |
22: "Al_Hajj_Tafseer.json",
|
| 226 |
23: "Al_Muminun_Tafseer.json",
|
| 227 |
24: "An_Nur_Tafseer.json",
|
|
|
|
| 242 |
39: "Az_Zumar_Tafseer.json",
|
| 243 |
40: "Ghafir_Tafseer.json",
|
| 244 |
41: "Fussilat_Tafseer.json",
|
| 245 |
+
42: "Ash_Shura_Tafseer.json",
|
| 246 |
43: "Az_Zukhruf_Tafseer.json",
|
| 247 |
44: "Ad_Dukhan_Tafseer.json",
|
| 248 |
45: "Al_Jathiyah_Tafseer.json",
|
|
|
|
| 261 |
58: "Al_Mujadilah_Tafseer.json",
|
| 262 |
59: "Al_Hashr_Tafseer.json",
|
| 263 |
60: "Al_Mumtahanah_Tafseer.json",
|
| 264 |
+
61: "As_Saff_Tafseer.json",
|
| 265 |
62: "Al_Jumuah_Tafseer.json",
|
| 266 |
63: "Al_Munafiqun_Tafseer.json",
|
| 267 |
64: "At_Taghabun_Tafseer.json",
|
|
|
|
| 292 |
89: "Al_Fajr_Tafseer.json",
|
| 293 |
90: "Al_Balad_Tafseer.json",
|
| 294 |
91: "Ash_Shams_Tafseer.json",
|
| 295 |
+
92: "Al_Lail_Tafseer.json",
|
| 296 |
+
93: "Ad_Duha_Tafseer.json",
|
| 297 |
94: "Ash_Sharh_Tafseer.json",
|
| 298 |
95: "At_Tin_Tafseer.json",
|
| 299 |
96: "Al_Alaq_Tafseer.json",
|
|
|
|
| 306 |
103: "Al_Asr_Tafseer.json",
|
| 307 |
104: "Al_Humazah_Tafseer.json",
|
| 308 |
105: "Al_Fil_Tafseer.json",
|
| 309 |
+
106: "Quraish_Tafseer.json",
|
| 310 |
107: "Al_Maun_Tafseer.json",
|
| 311 |
+
108: "Al_Kauthar_Tafseer.json",
|
| 312 |
109: "Al_Kafirun_Tafseer.json",
|
| 313 |
110: "An_Nasr_Tafseer.json",
|
| 314 |
111: "Al_Masad_Tafseer.json",
|
app/r2_routes.py
CHANGED
|
@@ -2,15 +2,20 @@
|
|
| 2 |
Cloudflare R2 Asset Routes
|
| 3 |
Serves Quran Tafseer (text only), Qaida Audio, and Nimaz Mutarjam Audio from R2
|
| 4 |
"""
|
| 5 |
-
from fastapi import APIRouter, HTTPException
|
| 6 |
-
from fastapi.responses import RedirectResponse, JSONResponse
|
| 7 |
from typing import Optional
|
|
|
|
|
|
|
|
|
|
| 8 |
import httpx
|
| 9 |
from .r2_config import (
|
| 10 |
get_tafseer_url,
|
| 11 |
get_qaida_audio_url,
|
| 12 |
get_nimaz_audio_url,
|
| 13 |
get_tafseer_by_name,
|
|
|
|
|
|
|
| 14 |
SURAH_NAMES
|
| 15 |
)
|
| 16 |
|
|
@@ -53,22 +58,30 @@ async def get_tafseer_json(surah_number: int):
|
|
| 53 |
detail=f"Tafseer file not found for Surah {surah_number}"
|
| 54 |
)
|
| 55 |
|
| 56 |
-
# Fetch the JSON from R2 and return it
|
| 57 |
try:
|
| 58 |
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 59 |
response = await client.get(tafseer_url)
|
| 60 |
response.raise_for_status()
|
| 61 |
return response.json()
|
| 62 |
-
except
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
raise HTTPException(
|
| 64 |
status_code=502,
|
| 65 |
detail=f"Failed to fetch Tafseer from R2: {str(e)}"
|
| 66 |
)
|
| 67 |
-
except Exception as e:
|
| 68 |
-
raise HTTPException(
|
| 69 |
-
status_code=500,
|
| 70 |
-
detail=f"Error processing Tafseer: {str(e)}"
|
| 71 |
-
)
|
| 72 |
|
| 73 |
|
| 74 |
@router.get("/tafseer/url/{surah_number}")
|
|
@@ -97,17 +110,69 @@ async def get_tafseer_url_only(surah_number: int):
|
|
| 97 |
# QAIDA AUDIO - Served from R2
|
| 98 |
# ==============================================================================
|
| 99 |
|
| 100 |
-
@router.get("/qaida/audio/{filename}")
|
| 101 |
-
async def get_qaida_audio(filename: str):
|
| 102 |
"""
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
| 105 |
"""
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
|
|
|
| 111 |
|
| 112 |
|
| 113 |
@router.get("/qaida/audio/list")
|
|
@@ -127,17 +192,71 @@ async def list_qaida_audio():
|
|
| 127 |
# NIMAZ MUTARJAM AUDIO - Served from R2
|
| 128 |
# ==============================================================================
|
| 129 |
|
| 130 |
-
@router.get("/nimaz/audio/{filename}")
|
| 131 |
-
async def get_nimaz_audio(filename: str):
|
| 132 |
"""
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
| 135 |
"""
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
|
| 143 |
@router.get("/nimaz/audio/list")
|
|
|
|
| 2 |
Cloudflare R2 Asset Routes
|
| 3 |
Serves Quran Tafseer (text only), Qaida Audio, and Nimaz Mutarjam Audio from R2
|
| 4 |
"""
|
| 5 |
+
from fastapi import APIRouter, HTTPException, Query
|
| 6 |
+
from fastapi.responses import RedirectResponse, JSONResponse, StreamingResponse, FileResponse
|
| 7 |
from typing import Optional
|
| 8 |
+
import os
|
| 9 |
+
import io
|
| 10 |
+
import json
|
| 11 |
import httpx
|
| 12 |
from .r2_config import (
|
| 13 |
get_tafseer_url,
|
| 14 |
get_qaida_audio_url,
|
| 15 |
get_nimaz_audio_url,
|
| 16 |
get_tafseer_by_name,
|
| 17 |
+
resolve_qaida_filename,
|
| 18 |
+
resolve_nimaz_filename,
|
| 19 |
SURAH_NAMES
|
| 20 |
)
|
| 21 |
|
|
|
|
| 58 |
detail=f"Tafseer file not found for Surah {surah_number}"
|
| 59 |
)
|
| 60 |
|
| 61 |
+
# Fetch the JSON from R2 (primary) and return it
|
| 62 |
try:
|
| 63 |
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 64 |
response = await client.get(tafseer_url)
|
| 65 |
response.raise_for_status()
|
| 66 |
return response.json()
|
| 67 |
+
except Exception as e:
|
| 68 |
+
print(f"R2 Tafseer fetch failed for Surah {surah_number}: {e}. Checking local fallback...")
|
| 69 |
+
filename = SURAH_NAMES.get(surah_number)
|
| 70 |
+
if filename:
|
| 71 |
+
local_path = os.path.join(
|
| 72 |
+
os.path.dirname(os.path.dirname(__file__)), "data", "quran_tafseer", filename
|
| 73 |
+
)
|
| 74 |
+
if os.path.exists(local_path) and os.path.isfile(local_path):
|
| 75 |
+
try:
|
| 76 |
+
with open(local_path, "r", encoding="utf-8") as f:
|
| 77 |
+
return json.load(f)
|
| 78 |
+
except Exception as file_err:
|
| 79 |
+
print(f"Local Tafseer read failed for {local_path}: {file_err}")
|
| 80 |
+
|
| 81 |
raise HTTPException(
|
| 82 |
status_code=502,
|
| 83 |
detail=f"Failed to fetch Tafseer from R2: {str(e)}"
|
| 84 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
|
| 87 |
@router.get("/tafseer/url/{surah_number}")
|
|
|
|
| 110 |
# QAIDA AUDIO - Served from R2
|
| 111 |
# ==============================================================================
|
| 112 |
|
| 113 |
+
@router.get("/qaida/audio/{filename:path}")
|
| 114 |
+
async def get_qaida_audio(filename: str, redirect: bool = Query(False)):
|
| 115 |
"""
|
| 116 |
+
Stream or redirect to Qaida audio file from Cloudflare R2 (qaida_audio/ folder).
|
| 117 |
+
Supports:
|
| 118 |
+
- Global numbered files: /r2/qaida/audio/4.mp3, /r2/qaida/audio/5.mp3
|
| 119 |
+
- Subpaths: /r2/qaida/audio/numbered/4.mp3 (auto-normalized to 4.mp3)
|
| 120 |
+
- Letter names: /r2/qaida/audio/alif.mp3 (auto-mapped to 4.mp3)
|
| 121 |
"""
|
| 122 |
+
resolved_name = resolve_qaida_filename(filename)
|
| 123 |
+
|
| 124 |
+
# Generate extension candidates (e.g. 1.m4a, 1.mp3, 1.wav)
|
| 125 |
+
if "." in resolved_name:
|
| 126 |
+
base_name, req_ext = resolved_name.rsplit(".", 1)
|
| 127 |
+
ext_priority = [req_ext, "m4a", "mp3", "wav"]
|
| 128 |
+
else:
|
| 129 |
+
base_name = resolved_name
|
| 130 |
+
ext_priority = ["m4a", "mp3", "wav"]
|
| 131 |
+
|
| 132 |
+
candidate_names = []
|
| 133 |
+
for ext in ext_priority:
|
| 134 |
+
cand = f"{base_name}.{ext}"
|
| 135 |
+
if cand not in candidate_names:
|
| 136 |
+
candidate_names.append(cand)
|
| 137 |
+
|
| 138 |
+
# Try streaming audio directly from R2 URL for each candidate
|
| 139 |
+
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
|
| 140 |
+
for c_name in candidate_names:
|
| 141 |
+
c_url = get_qaida_audio_url(c_name)
|
| 142 |
+
try:
|
| 143 |
+
resp = await client.get(c_url)
|
| 144 |
+
if resp.status_code == 200 and len(resp.content) > 0:
|
| 145 |
+
if redirect:
|
| 146 |
+
return RedirectResponse(url=c_url, status_code=307)
|
| 147 |
+
|
| 148 |
+
media_type = "audio/mpeg"
|
| 149 |
+
if c_name.endswith('.wav'):
|
| 150 |
+
media_type = "audio/wav"
|
| 151 |
+
elif c_name.endswith('.m4a'):
|
| 152 |
+
media_type = "audio/mp4"
|
| 153 |
+
|
| 154 |
+
return StreamingResponse(
|
| 155 |
+
io.BytesIO(resp.content),
|
| 156 |
+
media_type=media_type,
|
| 157 |
+
headers={
|
| 158 |
+
"Content-Length": str(len(resp.content)),
|
| 159 |
+
"Accept-Ranges": "bytes",
|
| 160 |
+
"Cache-Control": "public, max-age=86400",
|
| 161 |
+
}
|
| 162 |
+
)
|
| 163 |
+
except Exception as e:
|
| 164 |
+
print(f"R2 audio stream failed for candidate {c_name}: {e}")
|
| 165 |
+
|
| 166 |
+
# Fallback to local files if present in BACKEND/data/qaida_audio
|
| 167 |
+
for c_name in candidate_names:
|
| 168 |
+
local_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "qaida_audio", c_name)
|
| 169 |
+
if os.path.exists(local_path) and os.path.isfile(local_path):
|
| 170 |
+
media_type = "audio/mp4" if c_name.endswith('.m4a') else "audio/mpeg"
|
| 171 |
+
return FileResponse(local_path, media_type=media_type)
|
| 172 |
|
| 173 |
+
# If not found locally either, redirect to primary R2 URL as last resort
|
| 174 |
+
primary_url = get_qaida_audio_url(candidate_names[0])
|
| 175 |
+
return RedirectResponse(url=primary_url, status_code=307)
|
| 176 |
|
| 177 |
|
| 178 |
@router.get("/qaida/audio/list")
|
|
|
|
| 192 |
# NIMAZ MUTARJAM AUDIO - Served from R2
|
| 193 |
# ==============================================================================
|
| 194 |
|
| 195 |
+
@router.get("/nimaz/audio/{filename:path}")
|
| 196 |
+
async def get_nimaz_audio(filename: str, redirect: bool = Query(False)):
|
| 197 |
"""
|
| 198 |
+
Stream or redirect to Nimaz Mutarjam audio file from Cloudflare R2 (Nimaz_Mutarjam_audio/ folder).
|
| 199 |
+
Supports:
|
| 200 |
+
- Direct filenames: A1.m4a, A2.m4a, A3.m4a, A4.m4a, H1.m4a
|
| 201 |
+
- Extension-less: A1 -> resolves to A1.m4a or A1.mp3
|
| 202 |
+
- Subpaths: Nimaz_Mutarjam_audio/A1.m4a (auto-stripped)
|
| 203 |
"""
|
| 204 |
+
clean_name = resolve_nimaz_filename(filename)
|
| 205 |
+
|
| 206 |
+
# Determine base name and extension candidates
|
| 207 |
+
# In R2, files are uploaded as .m4a (e.g., A1.m4a, A2.m4a, H1.m4a)
|
| 208 |
+
if "." in clean_name:
|
| 209 |
+
base_name, ext = clean_name.rsplit(".", 1)
|
| 210 |
+
ext = ext.lower()
|
| 211 |
+
if ext == "m4a":
|
| 212 |
+
candidates = [clean_name, f"{base_name}.mp3", f"{base_name}.wav"]
|
| 213 |
+
elif ext == "mp3":
|
| 214 |
+
candidates = [f"{base_name}.m4a", clean_name, f"{base_name}.wav"]
|
| 215 |
+
else:
|
| 216 |
+
candidates = [clean_name, f"{base_name}.m4a", f"{base_name}.mp3"]
|
| 217 |
+
else:
|
| 218 |
+
# If requested without extension, prioritize .m4a then .mp3
|
| 219 |
+
candidates = [f"{clean_name}.m4a", f"{clean_name}.mp3", f"{clean_name}.wav"]
|
| 220 |
+
|
| 221 |
+
primary_url = get_nimaz_audio_url(candidates[0])
|
| 222 |
+
if redirect:
|
| 223 |
+
return RedirectResponse(url=primary_url, status_code=307)
|
| 224 |
+
|
| 225 |
+
# Try streaming from R2 using candidates
|
| 226 |
+
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
|
| 227 |
+
for candidate in candidates:
|
| 228 |
+
cand_url = get_nimaz_audio_url(candidate)
|
| 229 |
+
try:
|
| 230 |
+
resp = await client.get(cand_url)
|
| 231 |
+
if resp.status_code == 200 and len(resp.content) > 0:
|
| 232 |
+
media_type = "audio/mp4" if candidate.endswith('.m4a') else "audio/mpeg"
|
| 233 |
+
if candidate.endswith('.wav'):
|
| 234 |
+
media_type = "audio/wav"
|
| 235 |
+
|
| 236 |
+
return StreamingResponse(
|
| 237 |
+
io.BytesIO(resp.content),
|
| 238 |
+
media_type=media_type,
|
| 239 |
+
headers={
|
| 240 |
+
"Content-Length": str(len(resp.content)),
|
| 241 |
+
"Accept-Ranges": "bytes",
|
| 242 |
+
"Cache-Control": "public, max-age=86400",
|
| 243 |
+
}
|
| 244 |
+
)
|
| 245 |
+
except Exception as e:
|
| 246 |
+
print(f"R2 nimaz audio stream candidate {candidate} failed: {e}")
|
| 247 |
+
|
| 248 |
+
# Fallback to local files if present
|
| 249 |
+
for candidate in candidates:
|
| 250 |
+
local_candidates = [
|
| 251 |
+
os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "Nimaz_Mutarjam_audio", candidate),
|
| 252 |
+
os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "nimaz_audio", candidate),
|
| 253 |
+
]
|
| 254 |
+
for local_path in local_candidates:
|
| 255 |
+
if os.path.exists(local_path) and os.path.isfile(local_path):
|
| 256 |
+
media_type = "audio/mp4" if candidate.endswith('.m4a') else "audio/mpeg"
|
| 257 |
+
return FileResponse(local_path, media_type=media_type)
|
| 258 |
+
|
| 259 |
+
return RedirectResponse(url=primary_url, status_code=307)
|
| 260 |
|
| 261 |
|
| 262 |
@router.get("/nimaz/audio/list")
|
app/superadmin_routes.py
CHANGED
|
@@ -2,10 +2,13 @@
|
|
| 2 |
SuperAdmin Routes - Complete control panel for system administration.
|
| 3 |
Only users with superadmin=true in database can access these endpoints.
|
| 4 |
"""
|
| 5 |
-
from fastapi import APIRouter, Depends, HTTPException
|
| 6 |
from pydantic import BaseModel, Field
|
| 7 |
-
from typing import Optional
|
| 8 |
import logging
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
from .auth_deps import get_current_user
|
| 11 |
from .database import (
|
|
@@ -20,6 +23,7 @@ from .database import (
|
|
| 20 |
orders_collection,
|
| 21 |
transactions_collection,
|
| 22 |
wallets_collection,
|
|
|
|
| 23 |
)
|
| 24 |
|
| 25 |
logger = logging.getLogger(__name__)
|
|
@@ -79,6 +83,19 @@ class AuditLogQuery(BaseModel):
|
|
| 79 |
collection: Optional[str] = None
|
| 80 |
limit: int = 100
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
# =========================================================
|
| 83 |
# USER MANAGEMENT
|
| 84 |
# =========================================================
|
|
@@ -161,6 +178,425 @@ async def delete_user(uid: str, admin: dict = Depends(require_superadmin)):
|
|
| 161 |
|
| 162 |
return {"status": "ok", "deleted_uid": uid}
|
| 163 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
# =========================================================
|
| 165 |
# MASJID MANAGEMENT
|
| 166 |
# =========================================================
|
|
|
|
| 2 |
SuperAdmin Routes - Complete control panel for system administration.
|
| 3 |
Only users with superadmin=true in database can access these endpoints.
|
| 4 |
"""
|
| 5 |
+
from fastapi import APIRouter, Depends, HTTPException, Query
|
| 6 |
from pydantic import BaseModel, Field
|
| 7 |
+
from typing import Optional, List
|
| 8 |
import logging
|
| 9 |
+
import datetime
|
| 10 |
+
import uuid
|
| 11 |
+
import re
|
| 12 |
|
| 13 |
from .auth_deps import get_current_user
|
| 14 |
from .database import (
|
|
|
|
| 23 |
orders_collection,
|
| 24 |
transactions_collection,
|
| 25 |
wallets_collection,
|
| 26 |
+
subscriptions_collection,
|
| 27 |
)
|
| 28 |
|
| 29 |
logger = logging.getLogger(__name__)
|
|
|
|
| 83 |
collection: Optional[str] = None
|
| 84 |
limit: int = 100
|
| 85 |
|
| 86 |
+
class GrantProVipRequest(BaseModel):
|
| 87 |
+
email: str = Field(..., min_length=3, max_length=256)
|
| 88 |
+
name: str = Field(..., min_length=1, max_length=100)
|
| 89 |
+
days: int = Field(..., ge=1, le=3650)
|
| 90 |
+
why: str = Field(..., min_length=1, max_length=500)
|
| 91 |
+
|
| 92 |
+
class GrantAdMoneyVipRequest(BaseModel):
|
| 93 |
+
email: str = Field(..., min_length=3, max_length=256)
|
| 94 |
+
name: str = Field(..., min_length=1, max_length=100)
|
| 95 |
+
amount: float = Field(..., gt=0)
|
| 96 |
+
validity: str = Field(..., min_length=1, max_length=100)
|
| 97 |
+
why: str = Field(..., min_length=1, max_length=500)
|
| 98 |
+
|
| 99 |
# =========================================================
|
| 100 |
# USER MANAGEMENT
|
| 101 |
# =========================================================
|
|
|
|
| 178 |
|
| 179 |
return {"status": "ok", "deleted_uid": uid}
|
| 180 |
|
| 181 |
+
# =========================================================
|
| 182 |
+
# VIP OFFERS & GRANTS (PRO SUBSCRIPTION & AADS WALLET)
|
| 183 |
+
# =========================================================
|
| 184 |
+
|
| 185 |
+
@router.get('/users/search')
|
| 186 |
+
async def search_user_by_email(
|
| 187 |
+
email: str = Query(..., min_length=1, max_length=256),
|
| 188 |
+
admin: dict = Depends(require_superadmin)
|
| 189 |
+
):
|
| 190 |
+
"""Search a user by email address to grant VIP offers or inspect profile."""
|
| 191 |
+
clean_email = email.strip()
|
| 192 |
+
user = await users_collection.find_one(
|
| 193 |
+
{"email": {"$regex": f"^{re.escape(clean_email)}$", "$options": "i"}},
|
| 194 |
+
{"_id": 0, "uid": 1, "email": 1, "username": 1, "role": 1, "is_pro": 1, "subscription": 1, "superadmin": 1, "created_at": 1}
|
| 195 |
+
)
|
| 196 |
+
if not user:
|
| 197 |
+
user = await users_collection.find_one(
|
| 198 |
+
{"email": {"$regex": re.escape(clean_email), "$options": "i"}},
|
| 199 |
+
{"_id": 0, "uid": 1, "email": 1, "username": 1, "role": 1, "is_pro": 1, "subscription": 1, "superadmin": 1, "created_at": 1}
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
if not user:
|
| 203 |
+
raise HTTPException(status_code=404, detail=f"No user found with email matching '{clean_email}'")
|
| 204 |
+
|
| 205 |
+
# Fetch wallet balance for ad credit info
|
| 206 |
+
wallet = await wallets_collection.find_one({"user_id": user["uid"]})
|
| 207 |
+
wallet_balance = float(wallet.get("balance", 0.0)) if wallet else 0.0
|
| 208 |
+
|
| 209 |
+
sub = user.get("subscription", {}) or {}
|
| 210 |
+
is_pro = bool(user.get("is_pro") or sub.get("is_pro", False))
|
| 211 |
+
expires_at = sub.get("expires_at")
|
| 212 |
+
if isinstance(expires_at, datetime.datetime):
|
| 213 |
+
expires_at_str = expires_at.isoformat()
|
| 214 |
+
elif isinstance(expires_at, str):
|
| 215 |
+
expires_at_str = expires_at
|
| 216 |
+
else:
|
| 217 |
+
expires_at_str = None
|
| 218 |
+
|
| 219 |
+
return {
|
| 220 |
+
"uid": user["uid"],
|
| 221 |
+
"email": user.get("email", ""),
|
| 222 |
+
"username": user.get("username") or user.get("email", "").split("@")[0],
|
| 223 |
+
"role": user.get("role", "USER"),
|
| 224 |
+
"is_pro": is_pro,
|
| 225 |
+
"subscription": {
|
| 226 |
+
"is_pro": is_pro,
|
| 227 |
+
"plan_id": sub.get("plan_id", "free"),
|
| 228 |
+
"tier": sub.get("tier", "FREE"),
|
| 229 |
+
"status": sub.get("status", "ACTIVE" if is_pro else "FREE"),
|
| 230 |
+
"expires_at": expires_at_str,
|
| 231 |
+
"tag": sub.get("tag"),
|
| 232 |
+
"name": sub.get("name"),
|
| 233 |
+
"why": sub.get("why"),
|
| 234 |
+
},
|
| 235 |
+
"wallet_balance": wallet_balance,
|
| 236 |
+
"created_at": str(user.get("created_at", "")),
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
@router.post('/vip-offers/grant-pro')
|
| 240 |
+
async def grant_pro_vip_offer(
|
| 241 |
+
payload: GrantProVipRequest,
|
| 242 |
+
admin: dict = Depends(require_superadmin)
|
| 243 |
+
):
|
| 244 |
+
"""
|
| 245 |
+
SuperAdmin grant: Give PRO subscription to a user by email.
|
| 246 |
+
Includes fields: why, no. of days, name.
|
| 247 |
+
Recorded for BOTH the superadmin and user with tag 'VIP offer'.
|
| 248 |
+
"""
|
| 249 |
+
clean_email = payload.email.strip()
|
| 250 |
+
target_user = await users_collection.find_one(
|
| 251 |
+
{"email": {"$regex": f"^{re.escape(clean_email)}$", "$options": "i"}}
|
| 252 |
+
)
|
| 253 |
+
if not target_user:
|
| 254 |
+
target_user = await users_collection.find_one(
|
| 255 |
+
{"email": {"$regex": re.escape(clean_email), "$options": "i"}}
|
| 256 |
+
)
|
| 257 |
+
if not target_user:
|
| 258 |
+
raise HTTPException(
|
| 259 |
+
status_code=404,
|
| 260 |
+
detail=f"User with email '{clean_email}' not found"
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
uid = target_user["uid"]
|
| 264 |
+
now = datetime.datetime.utcnow()
|
| 265 |
+
expires_at = now + datetime.timedelta(days=payload.days)
|
| 266 |
+
plan_slug = f"vip_{re.sub(r'[^a-zA-Z0-9]+', '_', payload.name.lower()).strip('_')}"
|
| 267 |
+
admin_email = admin.get("email") or admin.get("username") or admin["uid"]
|
| 268 |
+
|
| 269 |
+
# 1. Update user profile with Pro subscription
|
| 270 |
+
await users_collection.update_one(
|
| 271 |
+
{"uid": uid},
|
| 272 |
+
{
|
| 273 |
+
"$set": {
|
| 274 |
+
"is_pro": True,
|
| 275 |
+
"subscription.is_pro": True,
|
| 276 |
+
"subscription.plan_id": plan_slug,
|
| 277 |
+
"subscription.tier": "PRO",
|
| 278 |
+
"subscription.status": "ACTIVE",
|
| 279 |
+
"subscription.name": payload.name,
|
| 280 |
+
"subscription.why": payload.why,
|
| 281 |
+
"subscription.days": payload.days,
|
| 282 |
+
"subscription.tag": "VIP offer",
|
| 283 |
+
"subscription.activated_at": now,
|
| 284 |
+
"subscription.expires_at": expires_at,
|
| 285 |
+
"subscription.granted_by": admin_email,
|
| 286 |
+
"subscription.payment_method": "VIP offer",
|
| 287 |
+
"updated_at": now,
|
| 288 |
+
}
|
| 289 |
+
}
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
# 2. Upsert into subscriptions_collection
|
| 293 |
+
await subscriptions_collection.update_one(
|
| 294 |
+
{"user_id": uid},
|
| 295 |
+
{
|
| 296 |
+
"$set": {
|
| 297 |
+
"user_id": uid,
|
| 298 |
+
"user_email": target_user.get("email"),
|
| 299 |
+
"plan_id": plan_slug,
|
| 300 |
+
"name": payload.name,
|
| 301 |
+
"why": payload.why,
|
| 302 |
+
"days": payload.days,
|
| 303 |
+
"status": "active",
|
| 304 |
+
"is_pro": True,
|
| 305 |
+
"tag": "VIP offer",
|
| 306 |
+
"started_at": now,
|
| 307 |
+
"expires_at": expires_at,
|
| 308 |
+
"renews_at": expires_at,
|
| 309 |
+
"granted_by": admin_email,
|
| 310 |
+
"admin_uid": admin["uid"],
|
| 311 |
+
"updated_at": now,
|
| 312 |
+
},
|
| 313 |
+
"$setOnInsert": {"created_at": now}
|
| 314 |
+
},
|
| 315 |
+
upsert=True
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
# 3. Record transaction for USER (with tag: "VIP offer")
|
| 319 |
+
user_tx_id = f"vip_sub_{uuid.uuid4().hex[:10]}"
|
| 320 |
+
user_tx_doc = {
|
| 321 |
+
"transaction_id": user_tx_id,
|
| 322 |
+
"user_id": uid,
|
| 323 |
+
"target_email": target_user.get("email"),
|
| 324 |
+
"amount": 0.0,
|
| 325 |
+
"type": "vip_offer_subscription",
|
| 326 |
+
"tag": "VIP offer",
|
| 327 |
+
"category": "VIP offer",
|
| 328 |
+
"name": payload.name,
|
| 329 |
+
"why": payload.why,
|
| 330 |
+
"days": payload.days,
|
| 331 |
+
"expires_at": expires_at.isoformat(),
|
| 332 |
+
"granted_by": admin_email,
|
| 333 |
+
"admin_uid": admin["uid"],
|
| 334 |
+
"payment_method": "VIP offer",
|
| 335 |
+
"status": "completed",
|
| 336 |
+
"description": f"[VIP offer] Pro Subscription '{payload.name}' granted for {payload.days} days. Reason: {payload.why}",
|
| 337 |
+
"created_at": now,
|
| 338 |
+
}
|
| 339 |
+
await transactions_collection.insert_one(user_tx_doc)
|
| 340 |
+
|
| 341 |
+
# 4. Record transaction for SUPERADMIN (with tag: "VIP offer")
|
| 342 |
+
admin_tx_id = f"admin_vip_sub_{uuid.uuid4().hex[:10]}"
|
| 343 |
+
admin_tx_doc = {
|
| 344 |
+
"transaction_id": admin_tx_id,
|
| 345 |
+
"user_id": admin["uid"],
|
| 346 |
+
"admin_email": admin_email,
|
| 347 |
+
"target_uid": uid,
|
| 348 |
+
"target_email": target_user.get("email"),
|
| 349 |
+
"amount": 0.0,
|
| 350 |
+
"type": "vip_offer_subscription_granted",
|
| 351 |
+
"tag": "VIP offer",
|
| 352 |
+
"category": "VIP offer grant",
|
| 353 |
+
"name": payload.name,
|
| 354 |
+
"why": payload.why,
|
| 355 |
+
"days": payload.days,
|
| 356 |
+
"expires_at": expires_at.isoformat(),
|
| 357 |
+
"payment_method": "VIP offer",
|
| 358 |
+
"status": "completed",
|
| 359 |
+
"description": f"[VIP offer] Granted Pro Subscription '{payload.name}' ({payload.days} days) to {target_user.get('email')}. Reason: {payload.why}",
|
| 360 |
+
"created_at": now,
|
| 361 |
+
}
|
| 362 |
+
await transactions_collection.insert_one(admin_tx_doc)
|
| 363 |
+
|
| 364 |
+
# 5. Create audit log
|
| 365 |
+
await create_audit_log(
|
| 366 |
+
action="grant_pro_subscription",
|
| 367 |
+
entity_type="user",
|
| 368 |
+
admin_uid=admin["uid"],
|
| 369 |
+
entity_id=uid,
|
| 370 |
+
details={
|
| 371 |
+
"tag": "VIP offer",
|
| 372 |
+
"name": payload.name,
|
| 373 |
+
"days": payload.days,
|
| 374 |
+
"why": payload.why,
|
| 375 |
+
"target_email": target_user.get("email"),
|
| 376 |
+
"expires_at": expires_at.isoformat(),
|
| 377 |
+
"user_transaction_id": user_tx_id,
|
| 378 |
+
"admin_transaction_id": admin_tx_id,
|
| 379 |
+
}
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
logger.info("superadmin: admin=%s granted Pro Subscription [VIP offer] to %s (days=%d, name=%s)",
|
| 383 |
+
admin["uid"], target_user.get("email"), payload.days, payload.name)
|
| 384 |
+
|
| 385 |
+
return {
|
| 386 |
+
"success": True,
|
| 387 |
+
"status": "ok",
|
| 388 |
+
"message": f"Successfully granted Pro Subscription '{payload.name}' for {payload.days} days to {target_user.get('email')}",
|
| 389 |
+
"tag": "VIP offer",
|
| 390 |
+
"subscription": {
|
| 391 |
+
"name": payload.name,
|
| 392 |
+
"why": payload.why,
|
| 393 |
+
"days": payload.days,
|
| 394 |
+
"is_pro": True,
|
| 395 |
+
"expires_at": expires_at.isoformat(),
|
| 396 |
+
"target_email": target_user.get("email"),
|
| 397 |
+
"target_uid": uid,
|
| 398 |
+
},
|
| 399 |
+
"user_transaction_id": user_tx_id,
|
| 400 |
+
"admin_transaction_id": admin_tx_id,
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
@router.post('/vip-offers/grant-ad-money')
|
| 404 |
+
async def grant_ad_money_vip_offer(
|
| 405 |
+
payload: GrantAdMoneyVipRequest,
|
| 406 |
+
admin: dict = Depends(require_superadmin)
|
| 407 |
+
):
|
| 408 |
+
"""
|
| 409 |
+
SuperAdmin grant: Add money to anyone's account for AADS by searching them through email.
|
| 410 |
+
Includes fields: why, amount, name, validity.
|
| 411 |
+
Recorded for BOTH the superadmin and user with tag 'VIP offer'.
|
| 412 |
+
"""
|
| 413 |
+
clean_email = payload.email.strip()
|
| 414 |
+
target_user = await users_collection.find_one(
|
| 415 |
+
{"email": {"$regex": f"^{re.escape(clean_email)}$", "$options": "i"}}
|
| 416 |
+
)
|
| 417 |
+
if not target_user:
|
| 418 |
+
target_user = await users_collection.find_one(
|
| 419 |
+
{"email": {"$regex": re.escape(clean_email), "$options": "i"}}
|
| 420 |
+
)
|
| 421 |
+
if not target_user:
|
| 422 |
+
raise HTTPException(
|
| 423 |
+
status_code=404,
|
| 424 |
+
detail=f"User with email '{clean_email}' not found"
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
uid = target_user["uid"]
|
| 428 |
+
now = datetime.datetime.utcnow()
|
| 429 |
+
amount = float(payload.amount)
|
| 430 |
+
admin_email = admin.get("email") or admin.get("username") or admin["uid"]
|
| 431 |
+
|
| 432 |
+
# 1. Update wallet balance and record VIP grant in wallet
|
| 433 |
+
grant_id = f"grant_{uuid.uuid4().hex[:8]}"
|
| 434 |
+
wallet_res = await wallets_collection.find_one_and_update(
|
| 435 |
+
{"user_id": uid},
|
| 436 |
+
{
|
| 437 |
+
"$inc": {"balance": amount},
|
| 438 |
+
"$set": {"updated_at": now},
|
| 439 |
+
"$push": {
|
| 440 |
+
"vip_grants": {
|
| 441 |
+
"grant_id": grant_id,
|
| 442 |
+
"name": payload.name,
|
| 443 |
+
"amount": amount,
|
| 444 |
+
"why": payload.why,
|
| 445 |
+
"validity": payload.validity,
|
| 446 |
+
"tag": "VIP offer",
|
| 447 |
+
"granted_by": admin_email,
|
| 448 |
+
"granted_at": now.isoformat(),
|
| 449 |
+
}
|
| 450 |
+
},
|
| 451 |
+
"$setOnInsert": {"created_at": now, "currency": "INR"}
|
| 452 |
+
},
|
| 453 |
+
upsert=True,
|
| 454 |
+
return_document=True
|
| 455 |
+
)
|
| 456 |
+
new_balance = float(wallet_res.get("balance", amount))
|
| 457 |
+
|
| 458 |
+
# 2. Record transaction for USER (with tag: "VIP offer")
|
| 459 |
+
user_tx_id = f"vip_ad_{uuid.uuid4().hex[:10]}"
|
| 460 |
+
user_tx_doc = {
|
| 461 |
+
"transaction_id": user_tx_id,
|
| 462 |
+
"user_id": uid,
|
| 463 |
+
"target_email": target_user.get("email"),
|
| 464 |
+
"amount": amount,
|
| 465 |
+
"type": "vip_offer_ad_credit",
|
| 466 |
+
"tag": "VIP offer",
|
| 467 |
+
"category": "ad_budget",
|
| 468 |
+
"name": payload.name,
|
| 469 |
+
"why": payload.why,
|
| 470 |
+
"validity": payload.validity,
|
| 471 |
+
"granted_by": admin_email,
|
| 472 |
+
"admin_uid": admin["uid"],
|
| 473 |
+
"payment_method": "VIP offer",
|
| 474 |
+
"status": "completed",
|
| 475 |
+
"description": f"[VIP offer] Ad Money Credited: {payload.name} - ₹{amount:.2f}. Validity: {payload.validity}. Reason: {payload.why}",
|
| 476 |
+
"created_at": now,
|
| 477 |
+
}
|
| 478 |
+
await transactions_collection.insert_one(user_tx_doc)
|
| 479 |
+
|
| 480 |
+
# 3. Record transaction for SUPERADMIN (with tag: "VIP offer")
|
| 481 |
+
admin_tx_id = f"admin_vip_ad_{uuid.uuid4().hex[:10]}"
|
| 482 |
+
admin_tx_doc = {
|
| 483 |
+
"transaction_id": admin_tx_id,
|
| 484 |
+
"user_id": admin["uid"],
|
| 485 |
+
"admin_email": admin_email,
|
| 486 |
+
"target_uid": uid,
|
| 487 |
+
"target_email": target_user.get("email"),
|
| 488 |
+
"amount": amount,
|
| 489 |
+
"type": "vip_offer_ad_credit_granted",
|
| 490 |
+
"tag": "VIP offer",
|
| 491 |
+
"category": "ad_credit_grant",
|
| 492 |
+
"name": payload.name,
|
| 493 |
+
"why": payload.why,
|
| 494 |
+
"validity": payload.validity,
|
| 495 |
+
"payment_method": "VIP offer",
|
| 496 |
+
"status": "completed",
|
| 497 |
+
"description": f"[VIP offer] Credited ₹{amount:.2f} Ad Money to {target_user.get('email')}. Validity: {payload.validity}. Reason: {payload.why}",
|
| 498 |
+
"created_at": now,
|
| 499 |
+
}
|
| 500 |
+
await transactions_collection.insert_one(admin_tx_doc)
|
| 501 |
+
|
| 502 |
+
# 4. Create audit log
|
| 503 |
+
await create_audit_log(
|
| 504 |
+
action="grant_ad_money",
|
| 505 |
+
entity_type="wallet",
|
| 506 |
+
admin_uid=admin["uid"],
|
| 507 |
+
entity_id=uid,
|
| 508 |
+
details={
|
| 509 |
+
"tag": "VIP offer",
|
| 510 |
+
"name": payload.name,
|
| 511 |
+
"amount": amount,
|
| 512 |
+
"why": payload.why,
|
| 513 |
+
"validity": payload.validity,
|
| 514 |
+
"target_email": target_user.get("email"),
|
| 515 |
+
"new_balance": new_balance,
|
| 516 |
+
"user_transaction_id": user_tx_id,
|
| 517 |
+
"admin_transaction_id": admin_tx_id,
|
| 518 |
+
}
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
logger.info("superadmin: admin=%s added ₹%.2f Ad Money [VIP offer] to %s (validity=%s, name=%s)",
|
| 522 |
+
admin["uid"], amount, target_user.get("email"), payload.validity, payload.name)
|
| 523 |
+
|
| 524 |
+
return {
|
| 525 |
+
"success": True,
|
| 526 |
+
"status": "ok",
|
| 527 |
+
"message": f"Successfully credited ₹{amount:.2f} Ad Money '{payload.name}' to {target_user.get('email')}",
|
| 528 |
+
"tag": "VIP offer",
|
| 529 |
+
"wallet": {
|
| 530 |
+
"name": payload.name,
|
| 531 |
+
"amount": amount,
|
| 532 |
+
"why": payload.why,
|
| 533 |
+
"validity": payload.validity,
|
| 534 |
+
"new_balance": new_balance,
|
| 535 |
+
"currency": wallet_res.get("currency", "INR"),
|
| 536 |
+
"target_email": target_user.get("email"),
|
| 537 |
+
"target_uid": uid,
|
| 538 |
+
},
|
| 539 |
+
"user_transaction_id": user_tx_id,
|
| 540 |
+
"admin_transaction_id": admin_tx_id,
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
@router.get('/vip-offers/transactions')
|
| 544 |
+
async def get_vip_offer_transactions(
|
| 545 |
+
page: int = Query(1, ge=1),
|
| 546 |
+
limit: int = Query(50, ge=1, le=200),
|
| 547 |
+
type: Optional[str] = None,
|
| 548 |
+
admin: dict = Depends(require_superadmin)
|
| 549 |
+
):
|
| 550 |
+
"""
|
| 551 |
+
Get all transactions recorded under 'VIP offer' for audit, transparency, and reporting.
|
| 552 |
+
"""
|
| 553 |
+
try:
|
| 554 |
+
skip = (page - 1) * limit
|
| 555 |
+
filter_query = {"tag": "VIP offer"}
|
| 556 |
+
if type:
|
| 557 |
+
filter_query["type"] = type
|
| 558 |
+
|
| 559 |
+
total = await transactions_collection.count_documents(filter_query)
|
| 560 |
+
cursor = transactions_collection.find(filter_query).sort("created_at", -1).skip(skip).limit(limit)
|
| 561 |
+
tx_list = await cursor.to_list(length=limit)
|
| 562 |
+
|
| 563 |
+
formatted = []
|
| 564 |
+
for tx in tx_list:
|
| 565 |
+
created_at = tx.get("created_at")
|
| 566 |
+
if isinstance(created_at, datetime.datetime):
|
| 567 |
+
created_str = created_at.isoformat()
|
| 568 |
+
else:
|
| 569 |
+
created_str = str(created_at or "")
|
| 570 |
+
|
| 571 |
+
formatted.append({
|
| 572 |
+
"id": tx.get("transaction_id", str(tx.get("_id", ""))),
|
| 573 |
+
"transaction_id": tx.get("transaction_id", str(tx.get("_id", ""))),
|
| 574 |
+
"user_id": tx.get("user_id", ""),
|
| 575 |
+
"target_email": tx.get("target_email") or tx.get("admin_email") or "",
|
| 576 |
+
"amount": float(tx.get("amount", 0.0)),
|
| 577 |
+
"type": tx.get("type", "vip_offer"),
|
| 578 |
+
"tag": tx.get("tag", "VIP offer"),
|
| 579 |
+
"name": tx.get("name", ""),
|
| 580 |
+
"why": tx.get("why", ""),
|
| 581 |
+
"days": tx.get("days"),
|
| 582 |
+
"validity": tx.get("validity"),
|
| 583 |
+
"granted_by": tx.get("granted_by") or tx.get("admin_email") or "",
|
| 584 |
+
"status": tx.get("status", "completed"),
|
| 585 |
+
"description": tx.get("description", ""),
|
| 586 |
+
"created_at": created_str,
|
| 587 |
+
})
|
| 588 |
+
|
| 589 |
+
return {
|
| 590 |
+
"transactions": formatted,
|
| 591 |
+
"page": page,
|
| 592 |
+
"limit": limit,
|
| 593 |
+
"total": total,
|
| 594 |
+
"tag": "VIP offer",
|
| 595 |
+
}
|
| 596 |
+
except Exception as e:
|
| 597 |
+
logger.error(f"SuperAdmin get VIP offer transactions error: {str(e)}")
|
| 598 |
+
raise HTTPException(status_code=500, detail="Failed to fetch VIP offer transactions")
|
| 599 |
+
|
| 600 |
# =========================================================
|
| 601 |
# MASJID MANAGEMENT
|
| 602 |
# =========================================================
|
app/tafsir_routes.py
CHANGED
|
@@ -11,10 +11,11 @@ import re
|
|
| 11 |
import html
|
| 12 |
import sqlite3
|
| 13 |
import asyncio
|
|
|
|
| 14 |
from pathlib import Path
|
| 15 |
from typing import Optional, List, Dict, Any
|
| 16 |
from fastapi import APIRouter, HTTPException, Query, Request
|
| 17 |
-
from fastapi.responses import FileResponse, RedirectResponse
|
| 18 |
import httpx
|
| 19 |
|
| 20 |
router = APIRouter(prefix="/tafsir", tags=["Quran Tafseer Engine"])
|
|
@@ -82,11 +83,14 @@ CURATED_EDITIONS: List[Dict[str, Any]] = [
|
|
| 82 |
{
|
| 83 |
"id": "en-tafsir-tafheem-ul-quran",
|
| 84 |
"slug": "en-tafsir-tafheem-ul-quran",
|
| 85 |
-
"name": "Towards Understanding the Quran",
|
| 86 |
"author": "Syed Abul A'la Maududi",
|
| 87 |
"language": "english",
|
| 88 |
"direction": "ltr",
|
| 89 |
"is_popular": True,
|
|
|
|
|
|
|
|
|
|
| 90 |
},
|
| 91 |
{
|
| 92 |
"id": "en-tafsir-tazkirul-quran",
|
|
@@ -108,23 +112,17 @@ CURATED_EDITIONS: List[Dict[str, Any]] = [
|
|
| 108 |
},
|
| 109 |
|
| 110 |
# Urdu (Sunni)
|
| 111 |
-
{
|
| 112 |
-
"id": "ur-tafsir-taqi-usmani",
|
| 113 |
-
"slug": "ur-tafsir-taqi-usmani",
|
| 114 |
-
"name": "Aasaan Tarjuma Quran (آسان ترجمہ قرآن)",
|
| 115 |
-
"author": "Mufti Muhammad Taqi Usmani (مفتی تقی عثمانی)",
|
| 116 |
-
"language": "urdu",
|
| 117 |
-
"direction": "rtl",
|
| 118 |
-
"is_popular": True,
|
| 119 |
-
},
|
| 120 |
{
|
| 121 |
"id": "ur-tafsir-tafheem-ul-quran",
|
| 122 |
"slug": "ur-tafsir-tafheem-ul-quran",
|
| 123 |
-
"name": "Tafheem-ul-Quran (
|
| 124 |
-
"author": "Syed Abul A'la Maududi (
|
| 125 |
"language": "urdu",
|
| 126 |
"direction": "rtl",
|
| 127 |
"is_popular": True,
|
|
|
|
|
|
|
|
|
|
| 128 |
},
|
| 129 |
{
|
| 130 |
"id": "tafsir-bayan-ul-quran",
|
|
@@ -138,11 +136,14 @@ CURATED_EDITIONS: List[Dict[str, Any]] = [
|
|
| 138 |
{
|
| 139 |
"id": "tafseer-ibn-e-kaseer-urdu",
|
| 140 |
"slug": "tafseer-ibn-e-kaseer-urdu",
|
| 141 |
-
"name": "Tafsir Ibn Kathir (
|
| 142 |
-
"author": "Hafiz Ibn Kathir",
|
| 143 |
"language": "urdu",
|
| 144 |
"direction": "rtl",
|
| 145 |
"is_popular": True,
|
|
|
|
|
|
|
|
|
|
| 146 |
},
|
| 147 |
{
|
| 148 |
"id": "ur-tafsir-fee-zilal-il-quran",
|
|
@@ -153,15 +154,6 @@ CURATED_EDITIONS: List[Dict[str, Any]] = [
|
|
| 153 |
"direction": "rtl",
|
| 154 |
"is_popular": True,
|
| 155 |
},
|
| 156 |
-
{
|
| 157 |
-
"id": "ur-tafsir-zia-ul-quran",
|
| 158 |
-
"slug": "ur-tafsir-zia-ul-quran",
|
| 159 |
-
"name": "Zia-ul-Quran (ضیاء القرآن)",
|
| 160 |
-
"author": "Pir Muhammad Karam Shah Al-Azhari (پیر محمد کرم شاہ)",
|
| 161 |
-
"language": "urdu",
|
| 162 |
-
"direction": "rtl",
|
| 163 |
-
"is_popular": False,
|
| 164 |
-
},
|
| 165 |
{
|
| 166 |
"id": "ur-tafsir-tazkirul-quran",
|
| 167 |
"slug": "ur-tafsir-tazkirul-quran",
|
|
@@ -181,17 +173,6 @@ CURATED_EDITIONS: List[Dict[str, Any]] = [
|
|
| 181 |
"is_popular": True,
|
| 182 |
},
|
| 183 |
|
| 184 |
-
# Hindi
|
| 185 |
-
{
|
| 186 |
-
"id": "hi-tafsir-tafheem-ul-quran",
|
| 187 |
-
"slug": "hi-tafsir-tafheem-ul-quran",
|
| 188 |
-
"name": "तफ़हीम-उल-क़ुरआन (Tafheem-ul-Quran Hindi)",
|
| 189 |
-
"author": "Syed Abul A'la Maududi (M. Farooq Khan)",
|
| 190 |
-
"language": "hindi",
|
| 191 |
-
"direction": "ltr",
|
| 192 |
-
"is_popular": True,
|
| 193 |
-
},
|
| 194 |
-
|
| 195 |
# Arabic (Strictly Sunni Ahl us-Sunnah wal-Jama'ah)
|
| 196 |
{
|
| 197 |
"id": "ar-tafsir-muyassar",
|
|
@@ -379,7 +360,6 @@ def clean_tafsir_text(raw: str) -> str:
|
|
| 379 |
|
| 380 |
|
| 381 |
FAWAZ_MAP: Dict[str, str] = {
|
| 382 |
-
"ur-tafsir-taqi-usmani": "urd-muhammadtaqiusm",
|
| 383 |
"en-tafsir-taqi-usmani": "eng-muftitaqiusmani",
|
| 384 |
}
|
| 385 |
|
|
@@ -521,10 +501,20 @@ async def list_tafsir_editions(language: Optional[str] = Query(None, description
|
|
| 521 |
|
| 522 |
|
| 523 |
# ==============================================================================
|
| 524 |
-
# AUDIO TAFSEER STREAMING & REDUNDANCY (
|
| 525 |
# ==============================================================================
|
| 526 |
AUDIO_DIR = DB_DIR / "audio" / "tafseer"
|
| 527 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 528 |
URDU_AUDIO_MAP_FILE = DB_DIR / "tafsir_audio_map.json"
|
| 529 |
URDU_AUDIO_MAP: Dict[int, str] = {}
|
| 530 |
if URDU_AUDIO_MAP_FILE.exists():
|
|
@@ -545,68 +535,101 @@ if ENGLISH_AUDIO_MAP_FILE.exists():
|
|
| 545 |
except Exception as e:
|
| 546 |
print(f"Warning loading English audio map: {e}")
|
| 547 |
|
|
|
|
|
|
|
| 548 |
def get_urdu_archive_url(surah: int) -> Optional[str]:
|
| 549 |
fname = URDU_AUDIO_MAP.get(surah)
|
| 550 |
if not fname:
|
| 551 |
return None
|
| 552 |
-
import urllib.parse
|
| 553 |
return f"https://archive.org/download/BayanUlQuranInUrduByDr.IsrarAhmedAudioMP3-HQ/{urllib.parse.quote(fname)}"
|
| 554 |
|
| 555 |
def get_english_archive_url(surah: int) -> Optional[str]:
|
| 556 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
if not fname:
|
| 558 |
return None
|
| 559 |
-
|
| 560 |
-
return f"https://archive.org/download/Bayan-ul-Quran-in-English-by-Dr-Israr-Ahmed-Audio-MP3-CD/{urllib.parse.quote(fname)}"
|
| 561 |
|
| 562 |
|
| 563 |
-
@router.api_route("/audio/{
|
| 564 |
-
|
|
|
|
| 565 |
"""
|
| 566 |
-
Streams Sunni Tafseer audio
|
| 567 |
-
|
| 568 |
-
full HTTP Range (206 Partial Content) support for instant seeking.
|
| 569 |
-
2. If not yet on local disk or downloading, redirects (307) to the Archive.org CDN.
|
| 570 |
"""
|
| 571 |
if surah < 1 or surah > 114:
|
| 572 |
raise HTTPException(status_code=400, detail="Invalid Surah number (must be 1-114)")
|
| 573 |
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
ep = min(max(1, surah), 27)
|
| 585 |
target_url = f"https://archive.org/download/DoraTafseerUlQuranByDr.NighatHashmiEp01/Dora%20Tafseer%20ul%20Quran%20by%20Dr.Nighat%20Hashmi%20Ep{ep:02d}.mp3"
|
| 586 |
return RedirectResponse(url=target_url, status_code=307)
|
| 587 |
-
else:
|
| 588 |
-
raise HTTPException(status_code=400, detail="Supported audio editions are 'urdu', 'english', 'nighat'")
|
| 589 |
|
| 590 |
-
|
| 591 |
-
local_file = AUDIO_DIR / folder / f"{surah_str}.mp3"
|
| 592 |
-
|
| 593 |
-
if local_file.exists() and local_file.stat().st_size > 100_000:
|
| 594 |
-
return FileResponse(
|
| 595 |
-
path=str(local_file),
|
| 596 |
-
media_type="audio/mpeg",
|
| 597 |
-
filename=f"{folder}_tafseer_{surah_str}.mp3",
|
| 598 |
-
)
|
| 599 |
-
|
| 600 |
-
if fallback_url:
|
| 601 |
-
return RedirectResponse(url=fallback_url, status_code=307)
|
| 602 |
-
|
| 603 |
-
raise HTTPException(status_code=404, detail="Tafseer audio file not found")
|
| 604 |
|
| 605 |
|
| 606 |
@router.api_route("/audio/ayah/{edition}/{surah}/{ayah}", methods=["GET", "HEAD"])
|
| 607 |
async def stream_ayah_tafsir_audio(edition: str, surah: int, ayah: int, request: Request):
|
| 608 |
"""
|
| 609 |
-
Streams single-ayah Tafseer audio (e.g. Dr. Farhat Hashmi
|
| 610 |
Redirects (307) directly to high-speed public CDN.
|
| 611 |
"""
|
| 612 |
if surah < 1 or surah > 114:
|
|
@@ -621,20 +644,112 @@ async def stream_ayah_tafsir_audio(edition: str, surah: int, ayah: int, request:
|
|
| 621 |
if "farhat" in ed:
|
| 622 |
target_url = f"https://everyayah.com/data/translations/urdu_farhat_hashmi/{surah_str}{ayah_str}.mp3"
|
| 623 |
return RedirectResponse(url=target_url, status_code=307)
|
| 624 |
-
elif "taqi" in ed or "usmani" in ed or "shamshad" in ed:
|
| 625 |
-
target_url = f"https://everyayah.com/data/translations/urdu_shamshad_ali_khan_46kbps/{surah_str}{ayah_str}.mp3"
|
| 626 |
-
return RedirectResponse(url=target_url, status_code=307)
|
| 627 |
-
else:
|
| 628 |
-
target_url = f"https://everyayah.com/data/translations/urdu_farhat_hashmi/{surah_str}{ayah_str}.mp3"
|
| 629 |
-
return RedirectResponse(url=target_url, status_code=307)
|
| 630 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 631 |
|
| 632 |
|
| 633 |
@router.get("/{tafsir_id}/{surah}/{ayah}")
|
| 634 |
async def get_ayah_tafsir(tafsir_id: str, surah: int, ayah: int):
|
| 635 |
"""
|
| 636 |
Returns the Tafseer of a specific Ayah.
|
| 637 |
-
|
| 638 |
"""
|
| 639 |
if surah < 1 or surah > 114:
|
| 640 |
raise HTTPException(status_code=400, detail="Invalid Surah number (must be 1-114)")
|
|
@@ -643,93 +758,176 @@ async def get_ayah_tafsir(tafsir_id: str, surah: int, ayah: int):
|
|
| 643 |
|
| 644 |
canonical_id = SLUG_ALIASES.get(tafsir_id, tafsir_id)
|
| 645 |
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
""
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
finally:
|
| 666 |
-
conn.close()
|
| 667 |
-
|
| 668 |
-
# Not found locally: stream & cache entire surah from CDN
|
| 669 |
-
surah_items = await fetch_and_cache_surah(canonical_id, surah)
|
| 670 |
-
for item in surah_items:
|
| 671 |
-
if item["ayah"] == ayah:
|
| 672 |
-
return {
|
| 673 |
-
"tafsir_id": tafsir_id,
|
| 674 |
-
"surah": surah,
|
| 675 |
-
"ayah": ayah,
|
| 676 |
-
"text": item["text"],
|
| 677 |
-
"cached": False,
|
| 678 |
-
}
|
| 679 |
|
| 680 |
raise HTTPException(
|
| 681 |
status_code=404,
|
| 682 |
-
detail=f"Tafseer
|
| 683 |
)
|
| 684 |
|
| 685 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 686 |
@router.get("/{tafsir_id}/{surah}")
|
| 687 |
async def get_surah_tafsir(tafsir_id: str, surah: int):
|
| 688 |
"""
|
| 689 |
-
Returns the Tafseer for ALL ayahs in a Surah.
|
| 690 |
-
Used for seamless full-surah Tafseer reading mode in the app.
|
| 691 |
"""
|
| 692 |
if surah < 1 or surah > 114:
|
| 693 |
raise HTTPException(status_code=400, detail="Invalid Surah number (must be 1-114)")
|
| 694 |
|
| 695 |
canonical_id = SLUG_ALIASES.get(tafsir_id, tafsir_id)
|
| 696 |
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
if rows:
|
| 710 |
return {
|
| 711 |
"tafsir_id": tafsir_id,
|
| 712 |
"surah": surah,
|
| 713 |
-
"total_ayahs": len(
|
| 714 |
-
"ayahs":
|
| 715 |
"cached": True,
|
|
|
|
| 716 |
}
|
| 717 |
-
finally:
|
| 718 |
-
conn.close()
|
| 719 |
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
status_code=404,
|
| 725 |
-
detail=f"Tafseer not found for {tafsir_id} at Surah {surah}",
|
| 726 |
-
)
|
| 727 |
-
|
| 728 |
-
return {
|
| 729 |
-
"tafsir_id": tafsir_id,
|
| 730 |
-
"surah": surah,
|
| 731 |
-
"total_ayahs": len(items),
|
| 732 |
-
"ayahs": [{"ayah": i["ayah"], "text": i["text"]} for i in items],
|
| 733 |
-
"cached": False,
|
| 734 |
-
}
|
| 735 |
|
|
|
|
| 11 |
import html
|
| 12 |
import sqlite3
|
| 13 |
import asyncio
|
| 14 |
+
import json
|
| 15 |
from pathlib import Path
|
| 16 |
from typing import Optional, List, Dict, Any
|
| 17 |
from fastapi import APIRouter, HTTPException, Query, Request
|
| 18 |
+
from fastapi.responses import FileResponse, RedirectResponse, JSONResponse
|
| 19 |
import httpx
|
| 20 |
|
| 21 |
router = APIRouter(prefix="/tafsir", tags=["Quran Tafseer Engine"])
|
|
|
|
| 83 |
{
|
| 84 |
"id": "en-tafsir-tafheem-ul-quran",
|
| 85 |
"slug": "en-tafsir-tafheem-ul-quran",
|
| 86 |
+
"name": "Towards Understanding the Quran (Audio & Text)",
|
| 87 |
"author": "Syed Abul A'la Maududi",
|
| 88 |
"language": "english",
|
| 89 |
"direction": "ltr",
|
| 90 |
"is_popular": True,
|
| 91 |
+
"has_audio": True,
|
| 92 |
+
"audio_type": "surah",
|
| 93 |
+
"audio_source": "archive_org_maududi_en",
|
| 94 |
},
|
| 95 |
{
|
| 96 |
"id": "en-tafsir-tazkirul-quran",
|
|
|
|
| 112 |
},
|
| 113 |
|
| 114 |
# Urdu (Sunni)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
{
|
| 116 |
"id": "ur-tafsir-tafheem-ul-quran",
|
| 117 |
"slug": "ur-tafsir-tafheem-ul-quran",
|
| 118 |
+
"name": "Tafheem-ul-Quran (Audio & Text)",
|
| 119 |
+
"author": "Syed Abul A'la Maududi (تفہیم القرآن)",
|
| 120 |
"language": "urdu",
|
| 121 |
"direction": "rtl",
|
| 122 |
"is_popular": True,
|
| 123 |
+
"has_audio": True,
|
| 124 |
+
"audio_type": "surah",
|
| 125 |
+
"audio_source": "archive_org_maududi_ur",
|
| 126 |
},
|
| 127 |
{
|
| 128 |
"id": "tafsir-bayan-ul-quran",
|
|
|
|
| 136 |
{
|
| 137 |
"id": "tafseer-ibn-e-kaseer-urdu",
|
| 138 |
"slug": "tafseer-ibn-e-kaseer-urdu",
|
| 139 |
+
"name": "Tafsir Ibn Kathir (Audio & Text)",
|
| 140 |
+
"author": "Hafiz Ibn Kathir (تفسیر ابن کثیر اردو)",
|
| 141 |
"language": "urdu",
|
| 142 |
"direction": "rtl",
|
| 143 |
"is_popular": True,
|
| 144 |
+
"has_audio": True,
|
| 145 |
+
"audio_type": "surah",
|
| 146 |
+
"audio_source": "archive_org_ibn_kathir_ur",
|
| 147 |
},
|
| 148 |
{
|
| 149 |
"id": "ur-tafsir-fee-zilal-il-quran",
|
|
|
|
| 154 |
"direction": "rtl",
|
| 155 |
"is_popular": True,
|
| 156 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
{
|
| 158 |
"id": "ur-tafsir-tazkirul-quran",
|
| 159 |
"slug": "ur-tafsir-tazkirul-quran",
|
|
|
|
| 173 |
"is_popular": True,
|
| 174 |
},
|
| 175 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
# Arabic (Strictly Sunni Ahl us-Sunnah wal-Jama'ah)
|
| 177 |
{
|
| 178 |
"id": "ar-tafsir-muyassar",
|
|
|
|
| 360 |
|
| 361 |
|
| 362 |
FAWAZ_MAP: Dict[str, str] = {
|
|
|
|
| 363 |
"en-tafsir-taqi-usmani": "eng-muftitaqiusmani",
|
| 364 |
}
|
| 365 |
|
|
|
|
| 501 |
|
| 502 |
|
| 503 |
# ==============================================================================
|
| 504 |
+
# AUDIO TAFSEER STREAMING & REDUNDANCY (Verified CDN Audio)
|
| 505 |
# ==============================================================================
|
| 506 |
AUDIO_DIR = DB_DIR / "audio" / "tafseer"
|
| 507 |
|
| 508 |
+
ARCHIVE_MAPPINGS_FILE = DB_DIR / "archive_surah_audio_mappings.json"
|
| 509 |
+
ARCHIVE_AUDIO_MAPS: Dict[str, Dict[str, str]] = {}
|
| 510 |
+
if ARCHIVE_MAPPINGS_FILE.exists():
|
| 511 |
+
try:
|
| 512 |
+
import json
|
| 513 |
+
with open(ARCHIVE_MAPPINGS_FILE, "r", encoding="utf-8") as f:
|
| 514 |
+
ARCHIVE_AUDIO_MAPS = json.load(f)
|
| 515 |
+
except Exception as e:
|
| 516 |
+
print(f"Warning loading archive audio mappings: {e}")
|
| 517 |
+
|
| 518 |
URDU_AUDIO_MAP_FILE = DB_DIR / "tafsir_audio_map.json"
|
| 519 |
URDU_AUDIO_MAP: Dict[int, str] = {}
|
| 520 |
if URDU_AUDIO_MAP_FILE.exists():
|
|
|
|
| 535 |
except Exception as e:
|
| 536 |
print(f"Warning loading English audio map: {e}")
|
| 537 |
|
| 538 |
+
import urllib.parse
|
| 539 |
+
|
| 540 |
def get_urdu_archive_url(surah: int) -> Optional[str]:
|
| 541 |
fname = URDU_AUDIO_MAP.get(surah)
|
| 542 |
if not fname:
|
| 543 |
return None
|
|
|
|
| 544 |
return f"https://archive.org/download/BayanUlQuranInUrduByDr.IsrarAhmedAudioMP3-HQ/{urllib.parse.quote(fname)}"
|
| 545 |
|
| 546 |
def get_english_archive_url(surah: int) -> Optional[str]:
|
| 547 |
+
if surah < 1 or surah > 114:
|
| 548 |
+
return None
|
| 549 |
+
file_idx = min(surah, 113)
|
| 550 |
+
fname = f"Dr. Israr Ahmed - Tafseer of Quran English {file_idx:03d}of113.mp3"
|
| 551 |
+
return f"https://archive.org/download/Dr.IsrarAhmedEnglishTafsirFullQuran/{urllib.parse.quote(fname)}"
|
| 552 |
+
|
| 553 |
+
def get_maududi_urdu_archive_url(surah: int) -> Optional[str]:
|
| 554 |
+
m = ARCHIVE_AUDIO_MAPS.get("Maududi_Urdu", {})
|
| 555 |
+
fname = m.get(str(surah))
|
| 556 |
+
if not fname:
|
| 557 |
+
return None
|
| 558 |
+
return f"https://archive.org/download/Tafheem-ul-Quran-by-Syed-Abul-Ala-Moududi-Audio-MP3-CD/{urllib.parse.quote(fname)}"
|
| 559 |
+
|
| 560 |
+
def get_maududi_english_archive_url(surah: int) -> Optional[str]:
|
| 561 |
+
m = ARCHIVE_AUDIO_MAPS.get("Maududi_English", {})
|
| 562 |
+
fname = m.get(str(surah))
|
| 563 |
+
if not fname:
|
| 564 |
+
return None
|
| 565 |
+
return f"https://archive.org/download/Towards-Understanding-the-Quran-Abridged-Version-Of-Tafhim-Al-Quran-Audio-Mp3/{urllib.parse.quote(fname)}"
|
| 566 |
+
|
| 567 |
+
def get_saadi_arabic_archive_url(surah: int) -> Optional[str]:
|
| 568 |
+
if surah < 1 or surah > 114:
|
| 569 |
+
return None
|
| 570 |
+
return f"https://archive.org/download/Tafseer_Al-Saadi_mp3/{surah:03d}.mp3"
|
| 571 |
+
|
| 572 |
+
def get_ibn_kathir_urdu_archive_url(surah: int) -> Optional[str]:
|
| 573 |
+
m = ARCHIVE_AUDIO_MAPS.get("Ibn_Kathir_Urdu", {})
|
| 574 |
+
fname = m.get(str(surah))
|
| 575 |
if not fname:
|
| 576 |
return None
|
| 577 |
+
return f"https://archive.org/download/Tafsir-ibne-kaseer-kathir-urdu-----audio-mp3-hq/{urllib.parse.quote(fname)}"
|
|
|
|
| 578 |
|
| 579 |
|
| 580 |
+
@router.api_route("/audio/surah/{edition}/{surah}", methods=["GET", "HEAD"])
|
| 581 |
+
@router.api_route("/audio/{edition}/{surah}", methods=["GET", "HEAD"])
|
| 582 |
+
async def stream_tafsir_audio(edition: str, surah: int, request: Request):
|
| 583 |
"""
|
| 584 |
+
Streams verified Sunni Tafseer audio strictly mapped to each authentic scholar.
|
| 585 |
+
Directly streams or 307 redirects to high-speed public CDN.
|
|
|
|
|
|
|
| 586 |
"""
|
| 587 |
if surah < 1 or surah > 114:
|
| 588 |
raise HTTPException(status_code=400, detail="Invalid Surah number (must be 1-114)")
|
| 589 |
|
| 590 |
+
ed = edition.lower().strip()
|
| 591 |
+
|
| 592 |
+
if ed in ("ur-tafsir-tafheem-ul-quran", "tafheem", "maududi_ur"):
|
| 593 |
+
target_url = get_maududi_urdu_archive_url(surah)
|
| 594 |
+
if target_url:
|
| 595 |
+
return RedirectResponse(url=target_url, status_code=307)
|
| 596 |
+
elif ed in ("en-tafsir-tafheem-ul-quran", "tafheem_en", "maududi_en"):
|
| 597 |
+
target_url = get_maududi_english_archive_url(surah)
|
| 598 |
+
if target_url:
|
| 599 |
+
return RedirectResponse(url=target_url, status_code=307)
|
| 600 |
+
elif ed in ("ar-tafsir-as-saadi", "saadi", "saadi_ar"):
|
| 601 |
+
target_url = get_saadi_arabic_archive_url(surah)
|
| 602 |
+
if target_url:
|
| 603 |
+
return RedirectResponse(url=target_url, status_code=307)
|
| 604 |
+
elif ed in ("ur-tafseer-ibn-e-kaseer", "tafseer-ibn-e-kaseer-urdu", "ibn_kathir_ur"):
|
| 605 |
+
target_url = get_ibn_kathir_urdu_archive_url(surah)
|
| 606 |
+
if target_url:
|
| 607 |
+
return RedirectResponse(url=target_url, status_code=307)
|
| 608 |
+
elif ed in ("ur", "urdu", "bayan", "israr", "ur-tafsir-bayan-ul-quran", "tafsir-bayan-ul-quran"):
|
| 609 |
+
# Check local HF disk first, then redirect to Archive
|
| 610 |
+
surah_str = f"{surah:03d}"
|
| 611 |
+
local_file = AUDIO_DIR / "urdu" / f"{surah_str}.mp3"
|
| 612 |
+
if local_file.exists() and local_file.stat().st_size > 100_000:
|
| 613 |
+
return FileResponse(path=str(local_file), media_type="audio/mpeg", filename=f"urdu_tafseer_{surah_str}.mp3")
|
| 614 |
+
target_url = get_urdu_archive_url(surah)
|
| 615 |
+
if target_url:
|
| 616 |
+
return RedirectResponse(url=target_url, status_code=307)
|
| 617 |
+
elif ed in ("en", "english", "en-tafsir-israr-audio", "israr_en"):
|
| 618 |
+
target_url = get_english_archive_url(surah)
|
| 619 |
+
if target_url:
|
| 620 |
+
return RedirectResponse(url=target_url, status_code=307)
|
| 621 |
+
elif "nighat" in ed:
|
| 622 |
ep = min(max(1, surah), 27)
|
| 623 |
target_url = f"https://archive.org/download/DoraTafseerUlQuranByDr.NighatHashmiEp01/Dora%20Tafseer%20ul%20Quran%20by%20Dr.Nighat%20Hashmi%20Ep{ep:02d}.mp3"
|
| 624 |
return RedirectResponse(url=target_url, status_code=307)
|
|
|
|
|
|
|
| 625 |
|
| 626 |
+
raise HTTPException(status_code=404, detail=f"No authentic audio commentary available for edition '{edition}'")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 627 |
|
| 628 |
|
| 629 |
@router.api_route("/audio/ayah/{edition}/{surah}/{ayah}", methods=["GET", "HEAD"])
|
| 630 |
async def stream_ayah_tafsir_audio(edition: str, surah: int, ayah: int, request: Request):
|
| 631 |
"""
|
| 632 |
+
Streams single-ayah Tafseer audio (e.g. Dr. Farhat Hashmi).
|
| 633 |
Redirects (307) directly to high-speed public CDN.
|
| 634 |
"""
|
| 635 |
if surah < 1 or surah > 114:
|
|
|
|
| 644 |
if "farhat" in ed:
|
| 645 |
target_url = f"https://everyayah.com/data/translations/urdu_farhat_hashmi/{surah_str}{ayah_str}.mp3"
|
| 646 |
return RedirectResponse(url=target_url, status_code=307)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 647 |
|
| 648 |
+
raise HTTPException(status_code=404, detail=f"Single-ayah audio commentary not supported for '{edition}'")
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
# UNIFIED COMPREHENSIVE TAFSEER STORAGE & SERVING
|
| 652 |
+
# ==============================================================================
|
| 653 |
+
UNIFIED_DIRS = [
|
| 654 |
+
DB_DIR / "quran_tafseer",
|
| 655 |
+
Path(__file__).resolve().parent.parent.parent / "quran_tafseer",
|
| 656 |
+
]
|
| 657 |
+
|
| 658 |
+
SURAH_FILE_NAMES = {
|
| 659 |
+
1: ["Al_Fataih_Tafseer.json", "Al_Fatihah_Tafseer.json", "001.json", "surah_001.json"],
|
| 660 |
+
2: ["Al_Baqarah_Tafseer.json", "002.json", "surah_002.json"],
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
_UNIFIED_CACHE: Dict[int, Dict[str, Any]] = {}
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
def get_unified_surah_data(surah: int) -> Optional[Dict[str, Any]]:
|
| 667 |
+
"""Loads unified multi-scholar JSON for a surah, caching in memory."""
|
| 668 |
+
if surah in _UNIFIED_CACHE:
|
| 669 |
+
return _UNIFIED_CACHE[surah]
|
| 670 |
+
|
| 671 |
+
names = list(SURAH_FILE_NAMES.get(surah, []))
|
| 672 |
+
names.extend([f"{surah:03d}.json", f"surah_{surah:03d}.json", f"{surah}.json"])
|
| 673 |
+
for d in UNIFIED_DIRS:
|
| 674 |
+
if not d.exists():
|
| 675 |
+
continue
|
| 676 |
+
# Also check any file matching *Tafseer.json where surah number matches
|
| 677 |
+
for p in d.glob("*Tafseer.json"):
|
| 678 |
+
if p.name not in names:
|
| 679 |
+
names.append(p.name)
|
| 680 |
+
for name in names:
|
| 681 |
+
p = d / name
|
| 682 |
+
if p.exists():
|
| 683 |
+
try:
|
| 684 |
+
with open(p, "r", encoding="utf-8") as f:
|
| 685 |
+
data = json.load(f)
|
| 686 |
+
_UNIFIED_CACHE[surah] = data
|
| 687 |
+
return data
|
| 688 |
+
except Exception as e:
|
| 689 |
+
print(f"Error loading unified file {p}: {e}")
|
| 690 |
+
return None
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
@router.get("/unified/{surah}")
|
| 694 |
+
async def get_unified_surah_tafsir(surah: int):
|
| 695 |
+
"""
|
| 696 |
+
Returns the complete unified Tafseer file for the given Surah,
|
| 697 |
+
containing all ayahs and all verified scholars per ayah.
|
| 698 |
+
"""
|
| 699 |
+
if surah < 1 or surah > 114:
|
| 700 |
+
raise HTTPException(status_code=400, detail="Invalid Surah number (must be 1-114)")
|
| 701 |
+
|
| 702 |
+
data = get_unified_surah_data(surah)
|
| 703 |
+
if not data:
|
| 704 |
+
raise HTTPException(
|
| 705 |
+
status_code=404,
|
| 706 |
+
detail=f"Unified tafseer file not found for Surah {surah}",
|
| 707 |
+
)
|
| 708 |
+
return data
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
@router.get("/unified/{surah}/{ayah}")
|
| 712 |
+
async def get_unified_ayah_tafsir(surah: int, ayah: int):
|
| 713 |
+
"""
|
| 714 |
+
Returns all scholars' tafseer for a specific Ayah from the unified JSON.
|
| 715 |
+
"""
|
| 716 |
+
if surah < 1 or surah > 114:
|
| 717 |
+
raise HTTPException(status_code=400, detail="Invalid Surah number (must be 1-114)")
|
| 718 |
+
if ayah < 1:
|
| 719 |
+
raise HTTPException(status_code=400, detail="Invalid Ayah number")
|
| 720 |
+
|
| 721 |
+
data = get_unified_surah_data(surah)
|
| 722 |
+
if not data:
|
| 723 |
+
raise HTTPException(
|
| 724 |
+
status_code=404,
|
| 725 |
+
detail=f"Unified tafseer file not found for Surah {surah}",
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
surahs = data.get("surahs", [])
|
| 729 |
+
if not surahs:
|
| 730 |
+
raise HTTPException(status_code=404, detail="Malformed unified tafseer data")
|
| 731 |
+
|
| 732 |
+
surah_obj = surahs[0]
|
| 733 |
+
for a in surah_obj.get("ayahs", []):
|
| 734 |
+
if a.get("ayah_no") == ayah:
|
| 735 |
+
return {
|
| 736 |
+
"surah_no": surah,
|
| 737 |
+
"ayah_no": ayah,
|
| 738 |
+
"reference": a.get("reference", f"{surah}:{ayah}"),
|
| 739 |
+
"tafsirs": a.get("tafsirs", []),
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
raise HTTPException(
|
| 743 |
+
status_code=404,
|
| 744 |
+
detail=f"Ayah {ayah} not found in unified data for Surah {surah}",
|
| 745 |
+
)
|
| 746 |
|
| 747 |
|
| 748 |
@router.get("/{tafsir_id}/{surah}/{ayah}")
|
| 749 |
async def get_ayah_tafsir(tafsir_id: str, surah: int, ayah: int):
|
| 750 |
"""
|
| 751 |
Returns the Tafseer of a specific Ayah.
|
| 752 |
+
Checks unified verified repository first, then SQLite, then CDN.
|
| 753 |
"""
|
| 754 |
if surah < 1 or surah > 114:
|
| 755 |
raise HTTPException(status_code=400, detail="Invalid Surah number (must be 1-114)")
|
|
|
|
| 758 |
|
| 759 |
canonical_id = SLUG_ALIASES.get(tafsir_id, tafsir_id)
|
| 760 |
|
| 761 |
+
# 1. Check unified data first (highest priority & 101% authentic)
|
| 762 |
+
unified_data = get_unified_surah_data(surah)
|
| 763 |
+
if unified_data and "surahs" in unified_data and len(unified_data["surahs"]) > 0:
|
| 764 |
+
for a in unified_data["surahs"][0].get("ayahs", []):
|
| 765 |
+
if a.get("ayah_no") == ayah:
|
| 766 |
+
for t in a.get("tafsirs", []):
|
| 767 |
+
tid = t.get("tafsir_id")
|
| 768 |
+
if tid == tafsir_id or tid == canonical_id:
|
| 769 |
+
return {
|
| 770 |
+
"tafsir_id": tafsir_id,
|
| 771 |
+
"surah": surah,
|
| 772 |
+
"ayah": ayah,
|
| 773 |
+
"text": t.get("text", ""),
|
| 774 |
+
"scholar": t.get("scholar"),
|
| 775 |
+
"language": t.get("language"),
|
| 776 |
+
"source": t.get("source"),
|
| 777 |
+
"cached": True,
|
| 778 |
+
"unified": True,
|
| 779 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 780 |
|
| 781 |
raise HTTPException(
|
| 782 |
status_code=404,
|
| 783 |
+
detail=f"Tafseer for {tafsir_id} at {surah}:{ayah} is not in the verified repository or is currently being compiled.",
|
| 784 |
)
|
| 785 |
|
| 786 |
|
| 787 |
+
# ==============================================================================
|
| 788 |
+
# SELF-HOSTED QURAN & ISLAMIC BOOKS PDF STREAMING ENGINE
|
| 789 |
+
# ==============================================================================
|
| 790 |
+
# Serves all 30 Holy Quran chapters, Tajweed Qaida, Short Surahs & Duas
|
| 791 |
+
# directly from local storage with full Range requests & CORS headers.
|
| 792 |
+
# ==============================================================================
|
| 793 |
+
QURAN_PDFS_DIR = DB_DIR / "quran_pdfs"
|
| 794 |
+
QURAN_PDFS_DIR.mkdir(parents=True, exist_ok=True)
|
| 795 |
+
|
| 796 |
+
# Dedicated router for `/api/quran/pdf/{book_id}`
|
| 797 |
+
quran_pdf_router = APIRouter(prefix="/quran/pdf", tags=["Quran PDF Library"])
|
| 798 |
+
|
| 799 |
+
CORS_PDF_HEADERS = {
|
| 800 |
+
"Access-Control-Allow-Origin": "*",
|
| 801 |
+
"Access-Control-Allow-Methods": "GET, HEAD, OPTIONS",
|
| 802 |
+
"Access-Control-Allow-Headers": "*",
|
| 803 |
+
"Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges",
|
| 804 |
+
"Accept-Ranges": "bytes",
|
| 805 |
+
"Cache-Control": "public, max-age=604800, immutable",
|
| 806 |
+
}
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def _serve_quran_pdf_file(book_id: str):
|
| 810 |
+
"""
|
| 811 |
+
Safely resolves, validates, and streams a PDF book from local disk.
|
| 812 |
+
Supports HTTP range requests for ultra-fast partial page loading.
|
| 813 |
+
Seamlessly resolves juzz_XX, juz_XX, and chapterXX aliases.
|
| 814 |
+
"""
|
| 815 |
+
safe_id = re.sub(r"[^a-zA-Z0-9_-]", "", book_id).lower()
|
| 816 |
+
pdf_path = QURAN_PDFS_DIR / f"{safe_id}.pdf"
|
| 817 |
+
|
| 818 |
+
if not pdf_path.is_file():
|
| 819 |
+
# Check aliases
|
| 820 |
+
if safe_id.startswith("juzz_"):
|
| 821 |
+
num = safe_id.replace("juzz_", "")
|
| 822 |
+
alt_path = QURAN_PDFS_DIR / f"juz_{num}.pdf"
|
| 823 |
+
if alt_path.is_file():
|
| 824 |
+
pdf_path = alt_path
|
| 825 |
+
elif safe_id.startswith("juz_"):
|
| 826 |
+
num = safe_id.replace("juz_", "")
|
| 827 |
+
alt_path = QURAN_PDFS_DIR / f"juzz_{num}.pdf"
|
| 828 |
+
if alt_path.is_file():
|
| 829 |
+
pdf_path = alt_path
|
| 830 |
+
elif safe_id.startswith("chapter"):
|
| 831 |
+
num = safe_id.replace("chapter", "")
|
| 832 |
+
try:
|
| 833 |
+
num_int = int(num)
|
| 834 |
+
for prefix in ("juzz_", "juz_"):
|
| 835 |
+
cand = QURAN_PDFS_DIR / f"{prefix}{num_int:02d}.pdf"
|
| 836 |
+
if cand.is_file():
|
| 837 |
+
pdf_path = cand
|
| 838 |
+
break
|
| 839 |
+
except Exception:
|
| 840 |
+
pass
|
| 841 |
+
|
| 842 |
+
if not pdf_path.is_file() or pdf_path.stat().st_size < 1000:
|
| 843 |
+
raise HTTPException(
|
| 844 |
+
status_code=404,
|
| 845 |
+
detail=f"PDF document '{safe_id}' not found in local library.",
|
| 846 |
+
)
|
| 847 |
+
|
| 848 |
+
return FileResponse(
|
| 849 |
+
path=str(pdf_path),
|
| 850 |
+
media_type="application/pdf",
|
| 851 |
+
filename=f"{pdf_path.name}",
|
| 852 |
+
headers=CORS_PDF_HEADERS,
|
| 853 |
+
)
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
@router.get("/pdf/{book_id}")
|
| 857 |
+
async def get_pdf_via_tafsir(book_id: str):
|
| 858 |
+
"""Serves PDF document under `/api/tafsir/pdf/{book_id}`."""
|
| 859 |
+
return _serve_quran_pdf_file(book_id)
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
@router.options("/pdf/{book_id}")
|
| 863 |
+
async def options_pdf_via_tafsir(book_id: str):
|
| 864 |
+
"""CORS preflight handler for `/api/tafsir/pdf/{book_id}`."""
|
| 865 |
+
return JSONResponse(content={"status": "ok"}, headers=CORS_PDF_HEADERS)
|
| 866 |
+
|
| 867 |
+
|
| 868 |
+
@quran_pdf_router.get("/{book_id}")
|
| 869 |
+
async def get_pdf_via_quran(book_id: str):
|
| 870 |
+
"""Serves PDF document under `/api/quran/pdf/{book_id}`."""
|
| 871 |
+
return _serve_quran_pdf_file(book_id)
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
@quran_pdf_router.options("/{book_id}")
|
| 875 |
+
async def options_pdf_via_quran(book_id: str):
|
| 876 |
+
"""CORS preflight handler for `/api/quran/pdf/{book_id}`."""
|
| 877 |
+
return JSONResponse(content={"status": "ok"}, headers=CORS_PDF_HEADERS)
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
@quran_pdf_router.get("/list/status")
|
| 881 |
+
async def get_quran_pdf_library_status():
|
| 882 |
+
"""Returns availability & file size for all 30 Quran Juz PDFs."""
|
| 883 |
+
status = {}
|
| 884 |
+
if QURAN_PDFS_DIR.exists():
|
| 885 |
+
for p in sorted(QURAN_PDFS_DIR.glob("juzz_*.pdf")):
|
| 886 |
+
status[p.stem] = {
|
| 887 |
+
"available": True,
|
| 888 |
+
"size_bytes": p.stat().st_size,
|
| 889 |
+
"size_mb": round(p.stat().st_size / (1024 * 1024), 2),
|
| 890 |
+
}
|
| 891 |
+
return {
|
| 892 |
+
"total_books": len(status),
|
| 893 |
+
"library_dir": str(QURAN_PDFS_DIR),
|
| 894 |
+
"books": status,
|
| 895 |
+
}
|
| 896 |
+
|
| 897 |
+
|
| 898 |
@router.get("/{tafsir_id}/{surah}")
|
| 899 |
async def get_surah_tafsir(tafsir_id: str, surah: int):
|
| 900 |
"""
|
| 901 |
+
Returns the Tafseer for ALL ayahs in a Surah from the verified repository.
|
|
|
|
| 902 |
"""
|
| 903 |
if surah < 1 or surah > 114:
|
| 904 |
raise HTTPException(status_code=400, detail="Invalid Surah number (must be 1-114)")
|
| 905 |
|
| 906 |
canonical_id = SLUG_ALIASES.get(tafsir_id, tafsir_id)
|
| 907 |
|
| 908 |
+
# 1. Check unified data (101% authentic & strictly enforced)
|
| 909 |
+
unified_data = get_unified_surah_data(surah)
|
| 910 |
+
if unified_data and "surahs" in unified_data and len(unified_data["surahs"]) > 0:
|
| 911 |
+
matched_ayahs = []
|
| 912 |
+
for a in unified_data["surahs"][0].get("ayahs", []):
|
| 913 |
+
ano = a.get("ayah_no")
|
| 914 |
+
for t in a.get("tafsirs", []):
|
| 915 |
+
tid = t.get("tafsir_id")
|
| 916 |
+
if tid == tafsir_id or tid == canonical_id:
|
| 917 |
+
matched_ayahs.append({"ayah": ano, "text": t.get("text", "")})
|
| 918 |
+
break
|
| 919 |
+
if matched_ayahs:
|
|
|
|
| 920 |
return {
|
| 921 |
"tafsir_id": tafsir_id,
|
| 922 |
"surah": surah,
|
| 923 |
+
"total_ayahs": len(matched_ayahs),
|
| 924 |
+
"ayahs": matched_ayahs,
|
| 925 |
"cached": True,
|
| 926 |
+
"unified": True,
|
| 927 |
}
|
|
|
|
|
|
|
| 928 |
|
| 929 |
+
raise HTTPException(
|
| 930 |
+
status_code=404,
|
| 931 |
+
detail=f"Tafseer for Surah {surah} is currently being compiled in the verified quran_tafseer repository.",
|
| 932 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 933 |
|