-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathmain.py
More file actions
1669 lines (1358 loc) · 62 KB
/
main.py
File metadata and controls
1669 lines (1358 loc) · 62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Web viewer for Telegram Backup.
FastAPI application providing a web interface to browse backed-up messages.
v3.0: Async database operations with SQLAlchemy.
v5.0: WebSocket support for real-time updates and notifications.
"""
import asyncio
import glob
import hashlib
import json
import logging
import os
import secrets
import time
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING
from urllib.parse import quote
from zoneinfo import ZoneInfo
from fastapi import Cookie, Depends, FastAPI, HTTPException, Query, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from ..config import Config
from ..db import DatabaseAdapter, close_database, get_db_manager, init_database
from ..realtime import RealtimeListener
if TYPE_CHECKING:
from .push import PushNotificationManager
# Register MIME types for audio files (required for StaticFiles to serve with correct Content-Type)
import mimetypes
mimetypes.add_type("audio/ogg", ".ogg")
mimetypes.add_type("audio/opus", ".opus")
mimetypes.add_type("audio/mpeg", ".mp3")
mimetypes.add_type("audio/wav", ".wav")
mimetypes.add_type("audio/flac", ".flac")
mimetypes.add_type("audio/x-m4a", ".m4a")
mimetypes.add_type("video/mp4", ".mp4")
mimetypes.add_type("video/webm", ".webm")
mimetypes.add_type("image/webp", ".webp")
# WebSocket Connection Manager for real-time updates
class ConnectionManager:
"""Manages WebSocket connections for real-time updates."""
def __init__(self):
self.active_connections: dict[WebSocket, set[int]] = {}
self._allowed_chats: dict[WebSocket, set[int] | None] = {}
async def connect(self, websocket: WebSocket, allowed_chat_ids: set[int] | None = None):
await websocket.accept()
self.active_connections[websocket] = set()
self._allowed_chats[websocket] = allowed_chat_ids
logger.info(f"WebSocket connected. Total connections: {len(self.active_connections)}")
def disconnect(self, websocket: WebSocket):
self.active_connections.pop(websocket, None)
self._allowed_chats.pop(websocket, None)
logger.info(f"WebSocket disconnected. Total connections: {len(self.active_connections)}")
def subscribe(self, websocket: WebSocket, chat_id: int):
"""Subscribe a connection to updates for a specific chat."""
if websocket in self.active_connections:
allowed = self._allowed_chats.get(websocket)
if allowed is not None and chat_id not in allowed:
return
self.active_connections[websocket].add(chat_id)
def unsubscribe(self, websocket: WebSocket, chat_id: int):
"""Unsubscribe a connection from a specific chat."""
if websocket in self.active_connections:
self.active_connections[websocket].discard(chat_id)
async def broadcast_to_chat(self, chat_id: int, message: dict):
"""Broadcast a message to all connections subscribed to a chat."""
disconnected = []
for websocket, subscribed_chats in self.active_connections.items():
allowed = self._allowed_chats.get(websocket)
if allowed is not None and chat_id not in allowed:
continue
if chat_id in subscribed_chats or not subscribed_chats:
try:
await websocket.send_json(message)
except Exception as e:
logger.warning(f"Failed to send to websocket: {e}")
disconnected.append(websocket)
# Clean up disconnected sockets
for ws in disconnected:
self.disconnect(ws)
async def broadcast_to_all(self, message: dict):
"""Broadcast a message to all connected clients."""
disconnected = []
for websocket in self.active_connections:
try:
await websocket.send_json(message)
except Exception as e:
logger.warning(f"Failed to send to websocket: {e}")
disconnected.append(websocket)
for ws in disconnected:
self.disconnect(ws)
# Global connection manager
ws_manager = ConnectionManager()
# Configure logging
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize config
config = Config()
# Global database adapter (initialized on startup)
db: DatabaseAdapter | None = None
async def _normalize_display_chat_ids():
"""
Normalize DISPLAY_CHAT_IDS to use marked format.
If a positive ID doesn't exist in DB but -100{id} does, auto-correct it.
This handles common user mistakes where they forget the -100 prefix for channels.
"""
if not config.display_chat_ids or not db:
return
all_chats = await db.get_all_chats()
existing_ids = {c["id"] for c in all_chats}
normalized = set()
for chat_id in config.display_chat_ids:
if chat_id in existing_ids:
# ID exists as-is
normalized.add(chat_id)
elif chat_id > 0:
# Positive ID not found - try -100 prefix (channel/supergroup format)
marked_id = -1000000000000 - chat_id
if marked_id in existing_ids:
logger.warning(
f"DISPLAY_CHAT_IDS: Auto-correcting {chat_id} → {marked_id} "
f"(use marked format for channels/supergroups)"
)
normalized.add(marked_id)
else:
logger.warning(f"DISPLAY_CHAT_IDS: Chat ID {chat_id} not found in database")
normalized.add(chat_id) # Keep original, might be backed up later
else:
# Negative ID not found
logger.warning(f"DISPLAY_CHAT_IDS: Chat ID {chat_id} not found in database")
normalized.add(chat_id)
config.display_chat_ids = normalized
# Background tasks
stats_task: asyncio.Task | None = None
_session_cleanup_task: asyncio.Task | None = None
# Real-time listener (PostgreSQL LISTEN/NOTIFY)
realtime_listener: RealtimeListener | None = None
# Push notification manager (Web Push API)
push_manager: PushNotificationManager | None = None
async def handle_realtime_notification(payload: dict):
"""Handle real-time notifications and broadcast to WebSocket clients + push notifications."""
notification_type = payload.get("type")
chat_id = payload.get("chat_id")
data = payload.get("data", {})
# Check if this chat is allowed (respects DISPLAY_CHAT_IDS restriction)
if config.display_chat_ids and chat_id not in config.display_chat_ids:
# This viewer is restricted to specific chats, ignore notifications for other chats
return
if notification_type == "new_message":
await ws_manager.broadcast_to_chat(chat_id, {"type": "new_message", "message": data.get("message")})
# Send Web Push notification for new messages
if push_manager and push_manager.is_enabled:
message = data.get("message", {})
# Get chat info for the notification
chat = await db.get_chat_by_id(chat_id) if db else None
chat_title = chat.get("title", "Telegram") if chat else "Telegram"
sender_name = ""
if message.get("sender_id"):
sender = await db.get_user_by_id(message.get("sender_id")) if db else None
if sender:
sender_name = sender.get("first_name", "") or sender.get("username", "")
await push_manager.notify_new_message(
chat_id=chat_id,
chat_title=chat_title,
sender_name=sender_name,
message_text=message.get("text", "") or "[Media]",
message_id=message.get("id", 0),
)
elif notification_type == "edit":
await ws_manager.broadcast_to_chat(
chat_id, {"type": "edit", "message_id": data.get("message_id"), "new_text": data.get("new_text")}
)
elif notification_type == "delete":
await ws_manager.broadcast_to_chat(chat_id, {"type": "delete", "message_id": data.get("message_id")})
async def session_cleanup_task():
"""Periodically evict expired sessions and stale rate limit entries."""
while True:
try:
await asyncio.sleep(_SESSION_CLEANUP_INTERVAL)
now = time.time()
expired = [k for k, v in _sessions.items() if now - v.created_at > AUTH_SESSION_SECONDS]
for k in expired:
_sessions.pop(k, None)
if expired:
logger.info(f"Cleaned up {len(expired)} expired sessions from cache")
# Also clean DB
if db:
try:
db_cleaned = await db.cleanup_expired_sessions(AUTH_SESSION_SECONDS)
if db_cleaned:
logger.info(f"Cleaned up {db_cleaned} expired sessions from database")
except Exception as e:
logger.warning(f"DB session cleanup failed: {e}")
stale_ips = [ip for ip, ts in _login_attempts.items() if all(now - t > _LOGIN_RATE_WINDOW for t in ts)]
for ip in stale_ips:
_login_attempts.pop(ip, None)
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Session cleanup error: {e}")
async def stats_calculation_scheduler():
"""Background task that runs stats calculation daily at configured hour."""
while True:
try:
# Get current time in configured timezone
tz = ZoneInfo(config.viewer_timezone)
now = datetime.now(tz)
# Calculate next run time (configured hour, e.g., 3am)
target_hour = config.stats_calculation_hour
next_run = now.replace(hour=target_hour, minute=0, second=0, microsecond=0)
# If we've passed the target time today, schedule for tomorrow
if now.hour >= target_hour:
next_run = next_run.replace(day=now.day + 1)
# Wait until next run
wait_seconds = (next_run - now).total_seconds()
logger.info(
f"Stats calculation scheduled for {next_run.strftime('%Y-%m-%d %H:%M')} ({wait_seconds / 3600:.1f}h from now)"
)
await asyncio.sleep(wait_seconds)
# Run stats calculation
logger.info("Running scheduled stats calculation...")
await db.calculate_and_store_statistics()
logger.info("Stats calculation completed")
except asyncio.CancelledError:
logger.info("Stats calculation scheduler cancelled")
break
except Exception as e:
logger.error(f"Error in stats calculation scheduler: {e}")
# Wait an hour before retrying on error
await asyncio.sleep(3600)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
"""Manage application lifecycle - initialize and cleanup database."""
global db, stats_task, _session_cleanup_task
logger.info("Initializing database connection...")
db_manager = await init_database()
db = DatabaseAdapter(db_manager)
logger.info("Database connection established")
# Normalize display chat IDs (auto-correct missing -100 prefix)
await _normalize_display_chat_ids()
# Check if stats have ever been calculated, if not, run initial calculation
stats_calculated_at = await db.get_metadata("stats_calculated_at")
if not stats_calculated_at:
logger.info("No cached stats found, running initial calculation...")
try:
await db.calculate_and_store_statistics()
except Exception as e:
logger.warning(f"Initial stats calculation failed: {e}")
# Restore persistent sessions from database
if AUTH_ENABLED:
try:
rows = await db.load_all_sessions()
now = time.time()
restored = 0
for row in rows:
if now - row["created_at"] > AUTH_SESSION_SECONDS:
continue # skip expired, cleanup task will purge from DB
allowed = None
if row["allowed_chat_ids"]:
try:
allowed = set(json.loads(row["allowed_chat_ids"]))
except json.JSONDecodeError, TypeError:
logger.warning(f"Skipping session with corrupted allowed_chat_ids for {row['username']}")
continue
_sessions[row["token"]] = SessionData(
username=row["username"],
role=row["role"],
allowed_chat_ids=allowed,
created_at=row["created_at"],
last_accessed=row["last_accessed"],
)
restored += 1
if restored:
logger.info(f"Restored {restored} sessions from database")
except Exception as e:
logger.warning(f"Failed to restore sessions from database: {e}")
# Start background tasks
stats_task = asyncio.create_task(stats_calculation_scheduler())
_session_cleanup_task = asyncio.create_task(session_cleanup_task())
logger.info(
f"Stats calculation scheduler started (runs daily at {config.stats_calculation_hour}:00 {config.viewer_timezone})"
)
# Start real-time listener (auto-detects PostgreSQL vs SQLite)
global realtime_listener
db_manager_instance = await get_db_manager()
realtime_listener = RealtimeListener(db_manager_instance, callback=handle_realtime_notification)
await realtime_listener.init()
await realtime_listener.start()
logger.info("Real-time listener started (auto-detected database type)")
# Initialize Web Push notifications (if enabled)
global push_manager
if config.push_notifications == "full":
from .push import PushNotificationManager
push_manager = PushNotificationManager(db, config)
push_enabled = await push_manager.initialize()
if push_enabled:
logger.info("Web Push notifications enabled (PUSH_NOTIFICATIONS=full)")
else:
logger.warning("Web Push notifications failed to initialize")
else:
logger.info(f"Push notifications mode: {config.push_notifications}")
yield
# Cleanup
if realtime_listener:
await realtime_listener.stop()
for task in [stats_task, _session_cleanup_task]:
if task:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
logger.info("Closing database connection...")
await close_database()
logger.info("Database connection closed")
app = FastAPI(title="Telegram Archive", lifespan=lifespan)
# Enable CORS
# CORS_ORIGINS env var: comma-separated list of allowed origins (default: "*")
# When using "*", credentials are disabled for security (browser requirement)
_cors_origins_raw = os.getenv("CORS_ORIGINS", "*").strip()
_cors_origins = [o.strip() for o in _cors_origins_raw.split(",") if o.strip()]
_cors_allow_credentials = _cors_origins != ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=_cors_origins,
allow_credentials=_cors_allow_credentials,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["*"],
)
@app.middleware("http")
async def add_security_headers(request: Request, call_next):
"""Add security headers to all responses."""
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "SAMEORIGIN"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.tailwindcss.com https://unpkg.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; "
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; "
"img-src 'self' data: blob:; "
"media-src 'self' blob:; "
"connect-src 'self' ws: wss:; "
"font-src 'self' https://fonts.gstatic.com https://cdnjs.cloudflare.com"
)
return response
# ============================================================================
# Multi-User Authentication (v7.0.0)
# ============================================================================
VIEWER_USERNAME = os.getenv("VIEWER_USERNAME", "").strip()
VIEWER_PASSWORD = os.getenv("VIEWER_PASSWORD", "").strip()
AUTH_ENABLED = bool(VIEWER_USERNAME and VIEWER_PASSWORD)
AUTH_COOKIE_NAME = "viewer_auth"
AUTH_SESSION_DAYS = int(os.getenv("AUTH_SESSION_DAYS", "30"))
AUTH_SESSION_SECONDS = AUTH_SESSION_DAYS * 24 * 60 * 60
_MAX_SESSIONS_PER_USER = 10
_SESSION_CLEANUP_INTERVAL = 900 # 15 minutes
_LOGIN_RATE_LIMIT = 15 # max attempts
_LOGIN_RATE_WINDOW = 300 # per 5 minutes
if AUTH_ENABLED:
logger.info(f"Viewer authentication is ENABLED (Master: {VIEWER_USERNAME}, Session: {AUTH_SESSION_DAYS} days)")
else:
logger.info("Viewer authentication is DISABLED (no VIEWER_USERNAME / VIEWER_PASSWORD set)")
@dataclass
class UserContext:
username: str
role: str # "master" or "viewer"
allowed_chat_ids: set[int] | None = None # None = all chats
@dataclass
class SessionData:
username: str
role: str
allowed_chat_ids: set[int] | None = None
created_at: float = field(default_factory=time.time)
last_accessed: float = field(default_factory=time.time)
_sessions: dict[str, SessionData] = {}
_login_attempts: dict[str, list[float]] = {} # ip -> list of timestamps
def _hash_password(password: str, salt: str) -> str:
return hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 600_000).hex()
def _verify_password(password: str, salt: str, password_hash: str) -> bool:
return secrets.compare_digest(_hash_password(password, salt), password_hash)
def _check_rate_limit(ip: str) -> bool:
"""Returns True if the request is within rate limits."""
now = time.time()
attempts = _login_attempts.get(ip, [])
attempts = [t for t in attempts if now - t < _LOGIN_RATE_WINDOW]
_login_attempts[ip] = attempts
return len(attempts) < _LOGIN_RATE_LIMIT
def _record_login_attempt(ip: str) -> None:
_login_attempts.setdefault(ip, []).append(time.time())
async def _create_session(username: str, role: str, allowed_chat_ids: set[int] | None = None) -> str:
"""Create a new session, evicting oldest if user exceeds max sessions."""
user_sessions = [(k, v) for k, v in _sessions.items() if v.username == username]
if len(user_sessions) >= _MAX_SESSIONS_PER_USER:
user_sessions.sort(key=lambda x: x[1].created_at)
for token, _ in user_sessions[: len(user_sessions) - _MAX_SESSIONS_PER_USER + 1]:
_sessions.pop(token, None)
if db:
try:
await db.delete_session(token)
except Exception:
pass
now = time.time()
token = secrets.token_urlsafe(32)
_sessions[token] = SessionData(
username=username,
role=role,
allowed_chat_ids=allowed_chat_ids,
created_at=now,
last_accessed=now,
)
# Persist to database
if db:
try:
chat_ids_json = json.dumps(list(allowed_chat_ids)) if allowed_chat_ids is not None else None
await db.save_session(
token=token,
username=username,
role=role,
allowed_chat_ids=chat_ids_json,
created_at=now,
last_accessed=now,
)
except Exception as e:
logger.warning(f"Failed to persist session to database: {e}")
return token
async def _invalidate_user_sessions(username: str) -> None:
"""Remove all sessions for a given username."""
to_remove = [k for k, v in _sessions.items() if v.username == username]
for k in to_remove:
_sessions.pop(k, None)
if db:
try:
await db.delete_user_sessions(username)
except Exception as e:
logger.warning(f"Failed to delete DB sessions for {username}: {e}")
def _get_secure_cookies(request: Request) -> bool:
secure_env = os.getenv("SECURE_COOKIES", "").strip().lower()
if secure_env == "true":
return True
if secure_env == "false":
return False
forwarded_proto = request.headers.get("x-forwarded-proto", "")
return forwarded_proto == "https" or str(request.url.scheme) == "https"
async def _resolve_session(auth_cookie: str) -> SessionData | None:
"""Look up session from in-memory cache, falling back to DB if needed."""
session = _sessions.get(auth_cookie)
if session:
return session
if not db:
return None
try:
row = await db.get_session(auth_cookie)
except Exception:
return None
if not row or time.time() - row["created_at"] > AUTH_SESSION_SECONDS:
return None
allowed = None
if row["allowed_chat_ids"]:
try:
allowed = set(json.loads(row["allowed_chat_ids"]))
except json.JSONDecodeError, TypeError:
logger.warning(f"Corrupted allowed_chat_ids for session {row['username']}, denying access")
return None
session = SessionData(
username=row["username"],
role=row["role"],
allowed_chat_ids=allowed,
created_at=row["created_at"],
last_accessed=row["last_accessed"],
)
_sessions[auth_cookie] = session
return session
async def require_auth(auth_cookie: str | None = Cookie(default=None, alias=AUTH_COOKIE_NAME)) -> UserContext:
"""Dependency that enforces session-based auth. Returns UserContext."""
if not AUTH_ENABLED:
return UserContext(username="anonymous", role="master", allowed_chat_ids=None)
if not auth_cookie:
raise HTTPException(status_code=401, detail="Unauthorized")
session = await _resolve_session(auth_cookie)
if not session:
raise HTTPException(status_code=401, detail="Unauthorized")
if time.time() - session.created_at > AUTH_SESSION_SECONDS:
_sessions.pop(auth_cookie, None)
raise HTTPException(status_code=401, detail="Session expired")
session.last_accessed = time.time()
return UserContext(
username=session.username,
role=session.role,
allowed_chat_ids=session.allowed_chat_ids,
)
def require_master(request: Request, user: UserContext = Depends(require_auth)) -> UserContext:
"""Dependency that requires master role. Blocked when X-Viewer-Only header is set."""
if user.role != "master":
raise HTTPException(status_code=403, detail="Admin access required")
if request.headers.get("x-viewer-only", "").lower() == "true":
raise HTTPException(status_code=403, detail="Admin access required")
return user
def get_user_chat_ids(user: UserContext) -> set[int] | None:
"""Get the effective chat IDs a user can access.
Returns None if the user can see all chats (no restriction).
"""
master_filter = config.display_chat_ids or None # empty set -> None
if user.role == "master":
return master_filter
# Viewer: use their allowed_chat_ids, intersected with master filter
if user.allowed_chat_ids is None:
return master_filter
if master_filter is None:
return user.allowed_chat_ids
return user.allowed_chat_ids & master_filter
# Setup paths
templates_dir = Path(__file__).parent / "templates"
static_dir = Path(__file__).parent / "static"
@app.get("/sw.js")
async def serve_service_worker():
"""
Serve the service worker from root path with proper headers.
The Service-Worker-Allowed header allows the SW to have scope '/'
even though the file is served from /static/sw.js.
"""
sw_path = static_dir / "sw.js"
if not sw_path.exists():
raise HTTPException(status_code=404, detail="Service worker not found")
return FileResponse(sw_path, media_type="application/javascript", headers={"Service-Worker-Allowed": "/"})
# Mount static directory (no auth needed for CSS/JS/icons)
if static_dir.exists():
app.mount("/static", StaticFiles(directory=static_dir), name="static")
# Media is served via authenticated endpoint below (not StaticFiles)
_media_root = Path(config.media_path).resolve() if os.path.exists(config.media_path) else None
@app.get("/media/{path:path}")
async def serve_media(path: str, user: UserContext = Depends(require_auth)):
"""Serve media files with authentication and path traversal protection."""
if not _media_root:
raise HTTPException(status_code=404, detail="Media directory not configured")
resolved = (_media_root / path).resolve()
if not resolved.is_relative_to(_media_root):
raise HTTPException(status_code=403, detail="Access denied")
user_chat_ids = get_user_chat_ids(user)
if user_chat_ids is not None:
parts = path.split("/")
if len(parts) >= 2 and parts[0] != "avatars":
try:
media_chat_id = int(parts[0])
if media_chat_id not in user_chat_ids:
raise HTTPException(status_code=403, detail="Access denied")
except ValueError:
pass
if not resolved.is_file():
raise HTTPException(status_code=404, detail="File not found")
return FileResponse(resolved)
@app.get("/", response_class=HTMLResponse)
async def read_root():
"""Serve the main application page."""
return FileResponse(
templates_dir / "index.html",
headers={"Cache-Control": "no-cache, must-revalidate"},
)
@app.get("/api/auth/check")
async def check_auth(auth_cookie: str | None = Cookie(default=None, alias=AUTH_COOKIE_NAME)):
"""Check current authentication status. Returns role and username if authenticated."""
if not AUTH_ENABLED:
return {"authenticated": True, "auth_required": False, "role": "master", "username": "anonymous"}
if not auth_cookie:
return {"authenticated": False, "auth_required": True}
session = await _resolve_session(auth_cookie)
if not session:
return {"authenticated": False, "auth_required": True}
if time.time() - session.created_at > AUTH_SESSION_SECONDS:
_sessions.pop(auth_cookie, None)
return {"authenticated": False, "auth_required": True}
return {
"authenticated": True,
"auth_required": True,
"role": session.role,
"username": session.username,
}
@app.post("/api/login")
async def login(request: Request):
"""Authenticate user (master via env vars or viewer via DB accounts)."""
if not AUTH_ENABLED:
return JSONResponse({"success": True, "message": "Auth disabled"})
direct_ip = request.client.host if request.client else "unknown"
_trusted = direct_ip.startswith(("172.", "10.", "192.168.", "127.")) or direct_ip in ("::1", "localhost")
if _trusted:
client_ip = (
request.headers.get("x-forwarded-for", "").split(",")[0].strip()
or request.headers.get("x-real-ip", "")
or direct_ip
)
else:
client_ip = direct_ip
if not _check_rate_limit(client_ip):
raise HTTPException(status_code=429, detail="Too many login attempts. Try again later.")
try:
data = await request.json()
username = data.get("username", "").strip()
password = data.get("password", "").strip()
except Exception:
raise HTTPException(status_code=400, detail="Invalid request")
if not username or not password:
raise HTTPException(status_code=400, detail="Username and password required")
_record_login_attempt(client_ip)
user_agent = request.headers.get("user-agent", "")[:500]
# 1. Check DB viewer accounts first
if db:
viewer = await db.get_viewer_by_username(username)
if viewer and viewer["is_active"]:
if _verify_password(password, viewer["salt"], viewer["password_hash"]):
allowed = None
if viewer["allowed_chat_ids"]:
try:
allowed = set(json.loads(viewer["allowed_chat_ids"]))
except json.JSONDecodeError, TypeError:
allowed = None
token = await _create_session(username, "viewer", allowed)
response = JSONResponse({"success": True, "role": "viewer", "username": username})
response.set_cookie(
key=AUTH_COOKIE_NAME,
value=token,
httponly=True,
secure=_get_secure_cookies(request),
samesite="lax",
max_age=AUTH_SESSION_SECONDS,
)
if db:
await db.create_audit_log(
username=username,
role="viewer",
action="login_success",
endpoint="/api/login",
ip_address=client_ip,
user_agent=user_agent,
)
return response
# 2. Fall back to master env var credentials
viewer_only = request.headers.get("x-viewer-only", "").lower() == "true"
if secrets.compare_digest(username, VIEWER_USERNAME) and secrets.compare_digest(password, VIEWER_PASSWORD):
if viewer_only:
raise HTTPException(status_code=401, detail="Invalid credentials")
token = await _create_session(username, "master", None)
response = JSONResponse({"success": True, "role": "master", "username": username})
response.set_cookie(
key=AUTH_COOKIE_NAME,
value=token,
httponly=True,
secure=_get_secure_cookies(request),
samesite="lax",
max_age=AUTH_SESSION_SECONDS,
)
if db:
await db.create_audit_log(
username=username,
role="master",
action="login_success",
endpoint="/api/login",
ip_address=client_ip,
user_agent=user_agent,
)
return response
# Failed login
if db:
await db.create_audit_log(
username=username or "(empty)",
role="unknown",
action="login_failed",
endpoint="/api/login",
ip_address=client_ip,
user_agent=user_agent,
)
raise HTTPException(status_code=401, detail="Invalid credentials")
@app.post("/api/logout")
async def logout(
request: Request,
auth_cookie: str | None = Cookie(default=None, alias=AUTH_COOKIE_NAME),
):
"""Invalidate current session and clear cookie."""
if auth_cookie:
session = _sessions.pop(auth_cookie, None)
if db:
# Always attempt DB delete (session may exist in DB but not in memory cache)
try:
if not session:
row = await db.get_session(auth_cookie)
if row:
session = SessionData(username=row["username"], role=row["role"])
await db.delete_session(auth_cookie)
except Exception:
pass
if session:
await db.create_audit_log(
username=session.username,
role=session.role,
action="logout",
endpoint="/api/logout",
ip_address=request.client.host if request.client else None,
)
response = JSONResponse({"success": True})
response.delete_cookie(AUTH_COOKIE_NAME)
return response
def _find_avatar_path(chat_id: int, chat_type: str) -> str | None:
"""Find avatar file path for a chat.
Avatar files are stored as: {chat_id}_{photo_id}.jpg
For groups/channels, chat_id is negative (marked ID format).
"""
# Determine folder: 'chats' for groups/channels, 'users' for private
avatar_folder = "users" if chat_type == "private" else "chats"
avatar_dir = os.path.join(config.media_path, "avatars", avatar_folder)
if not os.path.exists(avatar_dir):
return None
# Look for avatar file matching chat_id
pattern = os.path.join(avatar_dir, f"{chat_id}_*.jpg")
matches = glob.glob(pattern)
# Legacy fallback: files saved without photo_id suffix
legacy_path = os.path.join(avatar_dir, f"{chat_id}.jpg")
if os.path.exists(legacy_path):
matches.append(legacy_path)
if matches:
# Return the most recently modified avatar (newest profile photo)
newest_avatar = max(matches, key=os.path.getmtime)
avatar_file = os.path.basename(newest_avatar)
return f"avatars/{avatar_folder}/{avatar_file}"
return None
# Cache avatar paths to avoid repeated filesystem lookups
_avatar_cache: dict[int, str | None] = {}
_avatar_cache_time: datetime | None = None
AVATAR_CACHE_TTL_SECONDS = 300 # 5 minutes
def _get_cached_avatar_path(chat_id: int, chat_type: str) -> str | None:
"""Get avatar path with caching."""
global _avatar_cache, _avatar_cache_time
# Invalidate cache if too old
if _avatar_cache_time and (datetime.utcnow() - _avatar_cache_time).total_seconds() > AVATAR_CACHE_TTL_SECONDS:
_avatar_cache.clear()
_avatar_cache_time = None
# Check cache
if chat_id in _avatar_cache:
return _avatar_cache[chat_id]
# Lookup and cache
avatar_path = _find_avatar_path(chat_id, chat_type)
_avatar_cache[chat_id] = avatar_path
if _avatar_cache_time is None:
_avatar_cache_time = datetime.utcnow()
return avatar_path
@app.get("/api/chats")
async def get_chats(
user: UserContext = Depends(require_auth),
limit: int = Query(50, ge=1, le=1000, description="Number of chats to return"),
offset: int = Query(0, ge=0, description="Offset for pagination"),
search: str = Query(None, description="Search query for chat names/usernames"),
archived: bool | None = Query(None, description="Filter by archived status"),
folder_id: int | None = Query(None, description="Filter by folder ID"),
):
"""Get chats with metadata, paginated. Returns most recent chats first.
If 'search' is provided, returns all chats matching the search query (up to limit).
Search is case-insensitive and matches title, first_name, last_name, or username.
v6.2.0: Added archived and folder_id filters.
"""
try:
user_chat_ids = get_user_chat_ids(user)
# If user has chat restrictions, we need to load all matching chats
# Otherwise, use pagination
if user_chat_ids is not None:
chats = await db.get_all_chats(search=search, archived=archived, folder_id=folder_id)
chats = [c for c in chats if c["id"] in user_chat_ids]
total = len(chats)
# Apply pagination after filtering
chats = chats[offset : offset + limit]
else:
chats = await db.get_all_chats(
limit=limit, offset=offset, search=search, archived=archived, folder_id=folder_id
)
total = await db.get_chat_count(search=search, archived=archived, folder_id=folder_id)
# Add avatar URLs using cache
for chat in chats:
try:
avatar_path = _get_cached_avatar_path(chat["id"], chat.get("type", "private"))
if avatar_path:
chat["avatar_url"] = f"/media/{avatar_path}"
else:
chat["avatar_url"] = None
except Exception as e:
logger.error(f"Error finding avatar for chat {chat.get('id')}: {e}")
chat["avatar_url"] = None
return {
"chats": chats,
"total": total,
"limit": limit,
"offset": offset,
"has_more": offset + len(chats) < total,
}
except Exception as e:
logger.error(f"Error fetching chats: {e}", exc_info=True)
raise HTTPException(status_code=500, detail="Internal server error")
@app.get("/api/chats/{chat_id}/messages")
async def get_messages(
chat_id: int,
user: UserContext = Depends(require_auth),
limit: int = 50,
offset: int = 0,
search: str | None = None,
before_date: str | None = None,
before_id: int | None = None,
topic_id: int | None = None,
):
"""
Get messages for a specific chat with user and media info.
Supports two pagination modes:
- Offset-based: ?offset=100 (slower for large offsets)
- Cursor-based: ?before_date=2026-01-15T12:00:00&before_id=12345 (O(1) performance)
v6.2.0: Added topic_id filter for forum topic messages.
Cursor-based pagination is preferred for infinite scroll.
"""
user_chat_ids = get_user_chat_ids(user)
if user_chat_ids is not None and chat_id not in user_chat_ids: