-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2642 lines (2265 loc) · 87.7 KB
/
Copy pathmain.py
File metadata and controls
2642 lines (2265 loc) · 87.7 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
from fastapi import FastAPI, Depends, HTTPException, WebSocket, WebSocketDisconnect, Body, Request, Query
from fastapi.responses import RedirectResponse
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import os
import asyncio
import base64
from contextlib import suppress
import hashlib
import html
import json
import re
import shutil
from datetime import datetime, timezone, timedelta
from email.utils import parseaddr, parsedate_to_datetime, make_msgid
from email.message import EmailMessage
from typing import Any, Dict, List, Optional, Union
import requests
from pydantic import BaseModel, Field
from urllib.parse import urlencode
import jwt
from redis.asyncio import Redis
from google.cloud import pubsub_v1
import threading
import logging
from sqlalchemy import or_
from sqlalchemy.orm import Session
from database import SessionLocal, engine, ensure_runtime_schema
import models
from message_queue.producer import enqueue_email_analysis
from websocket.manager import manager
from redis_pubsub import REDIS_URL, REDIS_CHANNEL
from dotenv import load_dotenv
load_dotenv()
models.Base.metadata.create_all(bind=engine)
ensure_runtime_schema()
app = FastAPI()
bearer_scheme = HTTPBearer(auto_error=False)
# Pub/Sub config (set GCP_PUBSUB_SUBSCRIPTION to like "projects/<project>/subscriptions/<sub>")
GCP_PUBSUB_SUBSCRIPTION = os.getenv("GCP_PUBSUB_SUBSCRIPTION", "")
GCP_PUBSUB_TOPIC = os.getenv("GCP_PUBSUB_TOPIC", "")
logger = logging.getLogger(__name__)
async def _redis_listener() -> None:
redis_client = Redis.from_url(REDIS_URL, decode_responses=True)
pubsub = redis_client.pubsub()
await pubsub.subscribe(REDIS_CHANNEL)
try:
async for message in pubsub.listen():
if message.get("type") != "message":
continue
data = message.get("data")
if not data:
continue
try:
payload = json.loads(data)
except json.JSONDecodeError:
continue
user_id = payload.get("user_id")
if user_id is None:
continue
await manager.send_json(int(user_id), payload)
except asyncio.CancelledError:
pass
finally:
await pubsub.close()
await redis_client.close()
def _process_pubsub_notification(email_address: Optional[str], history_id: Optional[str]) -> None:
"""Run blocking fetch/store in a worker thread for a given email address."""
db = SessionLocal()
try:
if not email_address:
return
user = db.query(models.User).filter(
models.User.email == email_address).first()
if not user:
logger.info("Pub/Sub: user not found for email %s", email_address)
return
try:
if history_id and user.last_history_id:
try:
history_payload = _gmail_get_history(user, db, user.last_history_id)
records = history_payload.get("history", []) or []
if records:
_process_gmail_history_records(
user, db, records, notify_user_id=user.id
)
user.last_history_id = history_id
db.commit()
return
except HTTPException as exc:
logger.warning(
"Gmail history sync failed for %s: %s",
email_address,
exc.detail,
)
_fetch_and_store_emails_for_user(
user,
db,
max_results=50,
notify_user_id=user.id,
send_each_email=True,
)
if history_id:
user.last_history_id = history_id
else:
try:
profile = _gmail_get_profile(user, db)
if profile.get("historyId"):
user.last_history_id = profile.get("historyId")
except Exception:
pass
db.commit()
except Exception:
logger.exception(
"Error fetching/storing emails for user %s", email_address)
finally:
db.close()
def _pubsub_callback(message: pubsub_v1.subscriber.message.Message) -> None:
"""Callback for Pub/Sub messages from Gmail push notifications."""
try:
data = message.data.decode("utf-8")
payload = json.loads(data)
except Exception:
logger.exception("Failed to decode Pub/Sub message")
message.ack()
return
logger.info("Pub/Sub notification received: %s", payload)
email_address = payload.get("emailAddress") or payload.get(
"email") or payload.get("userId")
history_id = payload.get("historyId")
# Offload the heavy work to a thread to avoid blocking the Pub/Sub threads
t = threading.Thread(target=_process_pubsub_notification, args=(
email_address, history_id), daemon=True)
t.start()
message.ack()
async def _pubsub_listener() -> None:
"""Start a Google Pub/Sub subscriber and block until cancelled."""
if not GCP_PUBSUB_SUBSCRIPTION:
logger.info(
"GCP_PUBSUB_SUBSCRIPTION not set; skipping Pub/Sub listener")
return
subscriber = pubsub_v1.SubscriberClient()
subscription_path = GCP_PUBSUB_SUBSCRIPTION
streaming_pull_future = subscriber.subscribe(
subscription_path, callback=_pubsub_callback)
app.state.pubsub_subscriber = subscriber
app.state.pubsub_future = streaming_pull_future
try:
# This will block until the future is done/cancelled.
await asyncio.to_thread(streaming_pull_future.result)
except Exception:
logger.exception("Pub/Sub listener stopped with exception")
finally:
try:
streaming_pull_future.cancel()
except Exception:
pass
try:
subscriber.close()
except Exception:
pass
@app.post("/pubsub/push", tags = ['PubSub'])
async def pubsub_push(request: Request):
"""Endpoint to receive Pub/Sub push messages (no local GCP credentials required).
Expected body format (Pub/Sub push): {"message": {"data": "<base64>", ...}, "subscription": "..."}
"""
try:
body = await request.json()
except Exception:
raise HTTPException(status_code=400, detail="Invalid JSON")
message = body.get("message") or {}
data_b64 = message.get("data")
payload = None
if data_b64:
try:
decoded = base64.b64decode(data_b64).decode("utf-8")
payload = json.loads(decoded)
except Exception:
# Not JSON inside data, try to treat as plain string
try:
payload = json.loads(data_b64)
except Exception:
payload = {"raw": decoded}
else:
# If no data, try attributes
payload = message.get("attributes") or {}
# Extract common fields and offload processing
email_address = None
history_id = None
if isinstance(payload, dict):
email_address = payload.get("emailAddress") or payload.get(
"email") or payload.get("userId")
history_id = payload.get("historyId")
# Spawn thread to reuse existing sync logic
t = threading.Thread(target=_process_pubsub_notification, args=(
email_address, history_id), daemon=True)
t.start()
return {"status": "accepted"}
def _create_gmail_watch_for_user(user: models.User, db: Session) -> None:
"""Create a Gmail watch for a specific user using their credentials."""
if not GCP_PUBSUB_TOPIC:
logger.info("GCP_PUBSUB_TOPIC not set; skipping Gmail watch creation")
return
try:
access_token = _get_valid_google_access_token(user, db)
except Exception:
logger.exception(
"Failed to obtain access token for user %s", user.email)
return
url = "https://gmail.googleapis.com/gmail/v1/users/me/watch"
body = {"topicName": GCP_PUBSUB_TOPIC, "labelIds": ["INBOX"]}
try:
res = requests.post(
url, headers={"Authorization": f"Bearer {access_token}"}, json=body, timeout=15)
if not res.ok:
logger.warning(
"Failed to create Gmail watch for %s: %s", user.email, res.text)
else:
logger.info("Gmail watch created for %s", user.email)
except Exception:
logger.exception(
"Exception while creating Gmail watch for %s", user.email)
async def _ensure_watches_for_all_users() -> None:
"""Ensure Gmail watch is created for every Google user with tokens."""
if not GCP_PUBSUB_TOPIC:
logger.info("GCP_PUBSUB_TOPIC not set; skipping ensure watches")
return
def _sync():
db = SessionLocal()
try:
users = db.query(models.User).filter(
models.User.provider == "google").all()
for u in users:
if u.refresh_token or u.access_token:
_create_gmail_watch_for_user(u, db)
finally:
db.close()
await asyncio.to_thread(_sync)
@app.on_event("startup")
async def start_redis_listener() -> None:
app.state.redis_task = asyncio.create_task(_redis_listener())
# Start Pub/Sub listener if configured
app.state.pubsub_task = asyncio.create_task(_pubsub_listener())
# Ensure Gmail watches exist for all google users
app.state.gmail_watch_task = asyncio.create_task(
_ensure_watches_for_all_users())
@app.on_event("shutdown")
async def stop_redis_listener() -> None:
task = getattr(app.state, "redis_task", None)
if task:
task.cancel()
with suppress(asyncio.CancelledError):
await task
# Stop Pub/Sub listener
pubsub_future = getattr(app.state, "pubsub_future", None)
if pubsub_future:
try:
pubsub_future.cancel()
except Exception:
pass
pubsub_task = getattr(app.state, "pubsub_task", None)
if pubsub_task:
pubsub_task.cancel()
with suppress(asyncio.CancelledError):
await pubsub_task
gmail_watch_task = getattr(app.state, "gmail_watch_task", None)
if gmail_watch_task:
gmail_watch_task.cancel()
with suppress(asyncio.CancelledError):
await gmail_watch_task
CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID", "")
CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET", "")
REDIRECT_URI = os.getenv("GOOGLE_REDIRECT_URI", "")
JWT_SECRET = os.getenv("JWT_SECRET", "")
ATTACHMENTS_DIR = os.path.join(os.path.dirname(
os.path.abspath(__file__)), "attachments_store")
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def _decode_base64_url_bytes(data: str) -> bytes:
padding = "=" * (-len(data) % 4)
return base64.urlsafe_b64decode(data + padding)
def _decode_base64_url(data: str) -> str:
return _decode_base64_url_bytes(data).decode("utf-8", errors="replace")
def extract_body(payload: Dict[str, Any]) -> str:
plain_parts: List[str] = []
html_parts: List[str] = []
def walk(part: Dict[str, Any]) -> None:
mime_type = part.get("mimeType", "")
body = part.get("body", {})
data = body.get("data")
if data:
text = _decode_base64_url(data)
if mime_type == "text/plain":
plain_parts.append(text)
elif mime_type == "text/html":
html_parts.append(text)
for child in part.get("parts", []) or []:
walk(child)
walk(payload)
if html_parts:
return "\n".join(html_parts)
if plain_parts:
return "\n".join(plain_parts)
fallback = payload.get("body", {}).get("data")
return _decode_base64_url(fallback) if fallback else ""
def extract_headers(headers: List[Dict[str, str]]) -> Dict[str, Optional[str]]:
header_map: Dict[str, List[str]] = {}
raw_lines: List[str] = []
for header in headers:
name = header.get("name", "")
value = header.get("value", "")
if name:
raw_lines.append(f"{name}: {value}")
header_map.setdefault(name.lower(), []).append(value)
auth_results = ", ".join(header_map.get("authentication-results", []))
def extract_auth_result(key: str) -> Optional[str]:
if not auth_results:
return None
match = re.search(rf"{key}=([a-zA-Z0-9_\-]+)", auth_results)
return match.group(1) if match else None
return {
"raw_headers": "\n".join(raw_lines) if raw_lines else None,
"message_id": (header_map.get("message-id") or [None])[0],
"in_reply_to": (header_map.get("in-reply-to") or [None])[0],
"references": " ".join(header_map.get("references", [])) or None,
"return_path": (header_map.get("return-path") or [None])[0],
"received_chain": "\n".join(header_map.get("received", [])) or None,
"spf_result": extract_auth_result("spf"),
"dkim_result": extract_auth_result("dkim"),
"dmarc_result": extract_auth_result("dmarc"),
}
def extract_urls(body: str) -> List[str]:
if not body:
return []
urls = re.findall(r"https?://[^\s\"'<>]+", body)
return list(dict.fromkeys(urls))
def _parse_email_date(headers: List[Dict[str, str]], fallback_ms: Optional[str]) -> Optional[datetime]:
for header in headers:
if header.get("name", "").lower() == "date":
value = header.get("value")
if value:
try:
return parsedate_to_datetime(value)
except (TypeError, ValueError):
break
if fallback_ms:
try:
return datetime.fromtimestamp(int(fallback_ms) / 1000, tz=timezone.utc)
except (TypeError, ValueError):
return None
return None
def _decode_jwt_token(token: str) -> Dict[str, Any]:
normalized = token.strip()
if normalized.lower().startswith("bearer "):
normalized = normalized[7:]
try:
payload = jwt.decode(normalized, JWT_SECRET, algorithms=["HS256"])
except jwt.ExpiredSignatureError as exc:
raise HTTPException(
status_code=401, detail="JWT token expired") from exc
except jwt.InvalidTokenError as exc:
raise HTTPException(
status_code=401, detail="Invalid JWT token") from exc
token_type = payload.get("type")
if token_type and token_type != "access":
raise HTTPException(status_code=401, detail="Invalid JWT token type")
return payload
def _create_jwt_tokens(user_id: int, email: str) -> Dict[str, Any]:
access_expiry = datetime.now(timezone.utc) + timedelta(days=7)
refresh_expiry = datetime.now(timezone.utc) + timedelta(days=7)
access_token = jwt.encode(
{"user_id": user_id, "email": email, "type": "access", "exp": access_expiry},
JWT_SECRET,
algorithm="HS256",
)
refresh_token = jwt.encode(
{"user_id": user_id, "email": email,
"type": "refresh", "exp": refresh_expiry},
JWT_SECRET,
algorithm="HS256",
)
return {
"access_token": access_token,
"refresh_token": refresh_token,
"access_expiry": access_expiry,
"refresh_expiry": refresh_expiry,
}
def _get_current_user(token: str, db: Session) -> models.User:
payload = _decode_jwt_token(token)
user_id = payload.get("user_id") or payload.get("sub")
if not user_id:
raise HTTPException(status_code=401, detail="JWT missing user_id")
user = db.query(models.User).filter(models.User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
def get_current_user_from_auth(
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
db: Session = Depends(get_db),
) -> models.User:
if not credentials or not credentials.credentials:
raise HTTPException(status_code=401, detail="Missing JWT token")
return _get_current_user(credentials.credentials, db)
def _refresh_google_access_token(user: models.User, db: Session) -> str:
if not user.refresh_token:
raise HTTPException(
status_code=401, detail="Missing Google refresh token")
token_res = requests.post(
"https://oauth2.googleapis.com/token",
data={
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"refresh_token": user.refresh_token,
"grant_type": "refresh_token",
},
timeout=15,
)
if not token_res.ok:
raise HTTPException(
status_code=502, detail="Failed to refresh Google access token")
payload = token_res.json()
access_token = payload.get("access_token")
if not access_token:
raise HTTPException(
status_code=502, detail="Google access token missing in refresh response")
user.access_token = access_token
expires_in = payload.get("expires_in")
if expires_in:
user.token_expiry = datetime.now(
timezone.utc) + timedelta(seconds=int(expires_in))
db.commit()
return access_token
def _get_valid_google_access_token(user: models.User, db: Session) -> str:
if not user.access_token:
return _refresh_google_access_token(user, db)
if user.token_expiry:
expiry = user.token_expiry
if expiry.tzinfo is None:
expiry = expiry.replace(tzinfo=timezone.utc)
if expiry <= datetime.now(timezone.utc):
return _refresh_google_access_token(user, db)
return user.access_token
def _gmail_get_json(user: models.User, db: Session, url: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
access_token = _get_valid_google_access_token(user, db)
res = requests.get(
url,
headers={"Authorization": f"Bearer {access_token}"},
params=params,
timeout=15,
)
if res.status_code == 401:
access_token = _refresh_google_access_token(user, db)
res = requests.get(
url,
headers={"Authorization": f"Bearer {access_token}"},
params=params,
timeout=15,
)
if not res.ok:
raise HTTPException(
status_code=502, detail=f"Gmail API error: {res.text}")
return res.json()
def _gmail_get_profile(user: models.User, db: Session) -> Dict[str, Any]:
profile_url = "https://gmail.googleapis.com/gmail/v1/users/me/profile"
return _gmail_get_json(user, db, profile_url)
def _gmail_get_history(user: models.User, db: Session, start_history_id: str) -> Dict[str, Any]:
history_url = "https://gmail.googleapis.com/gmail/v1/users/me/history"
return _gmail_get_json(
user,
db,
history_url,
params={"startHistoryId": start_history_id},
)
def _delete_local_email(db: Session, email: models.Email) -> None:
attachment_dir = os.path.join(ATTACHMENTS_DIR, str(email.id))
db.query(models.StaticAnalysis).filter(
models.StaticAnalysis.attach_id.in_(
db.query(models.Attachments.id).filter(
models.Attachments.email_id == email.id)
)
).delete(synchronize_session=False)
db.query(models.DynamicAnalysis).filter(
models.DynamicAnalysis.attach_id.in_(
db.query(models.Attachments.id).filter(
models.Attachments.email_id == email.id)
)
).delete(synchronize_session=False)
db.query(models.AnalysisTask).filter(
models.AnalysisTask.email_id == email.id).delete(synchronize_session=False)
db.query(models.BodyClassification).filter(
models.BodyClassification.email_id == email.id).delete(synchronize_session=False)
db.query(models.EmailHeaders).filter(
models.EmailHeaders.email_id == email.id).delete(synchronize_session=False)
db.query(models.UrlsExtracted).filter(
models.UrlsExtracted.email_id == email.id).delete(synchronize_session=False)
db.query(models.EmailDeadline).filter(
models.EmailDeadline.email_id == email.id).delete(synchronize_session=False)
db.query(models.UserAction).filter(
models.UserAction.email_id == email.id).delete(synchronize_session=False)
db.query(models.EmailLabel).filter(
models.EmailLabel.email_id == email.id).delete(synchronize_session=False)
db.query(models.Interface).filter(
models.Interface.email_id == email.id).delete(synchronize_session=False)
db.query(models.Attachments).filter(
models.Attachments.email_id == email.id).delete(synchronize_session=False)
db.delete(email)
if os.path.isdir(attachment_dir):
shutil.rmtree(attachment_dir, ignore_errors=True)
def _create_email_from_gmail_message(
user: models.User,
db: Session,
message: Dict[str, Any],
notify_user_id: Optional[int] = None,
send_each_email: bool = False,
) -> Optional[models.Email]:
message_id = message.get("id")
if not message_id:
return None
payload = message.get("payload", {})
headers = payload.get("headers", []) or []
subject = next(
(header.get("value") for header in headers if header.get("name", "").lower() == "subject"),
None,
)
from_header = next(
(header.get("value") for header in headers if header.get("name", "").lower() == "from"),
"",
)
to_header = next(
(header.get("value") for header in headers if header.get("name", "").lower() == "to"),
"",
)
sender_name, sender_email = parseaddr(from_header)
receiver_name, receiver_email = parseaddr(to_header)
email_date = _parse_email_date(headers, message.get("internalDate"))
body_full = extract_body(payload)
snippet = message.get("snippet")
labels = message.get("labelIds") or []
category_name = _extract_category_name(labels)
category = _get_or_create_category(db, category_name)
is_starred = "STARRED" in labels
is_trash = "TRASH" in labels
is_read = "UNREAD" not in labels
email_record = models.Email(
gmail_message_id=message_id,
thread_id=message.get("threadId"),
subject=subject,
body_full=body_full,
body_snippet=snippet,
labels=None,
date=email_date,
category_id=category.id,
status="PENDING",
delivery_status="sent",
urls_status="PENDING",
attachments_status="PENDING",
body_status="PENDING",
headers_status="PENDING",
is_starred=is_starred,
is_trash=is_trash,
is_read=is_read,
)
db.add(email_record)
db.flush()
def _get_or_create_external_user(email_addr: str, display_name: str) -> Optional[models.User]:
if not email_addr:
return None
found = db.query(models.User).filter(models.User.email == email_addr).first()
if not found:
found = models.User(
email=email_addr,
name=display_name or None,
provider="external",
)
db.add(found)
db.flush()
return found
sender_user = _get_or_create_external_user(sender_email, sender_name)
receiver_user = _get_or_create_external_user(receiver_email, receiver_name)
is_self_sent = "SENT" in labels or (
sender_email and user.email and sender_email.strip().lower() == user.email.strip().lower()
)
interface_record = models.Interface(
sender_id=sender_user.id if sender_user else None,
receiver_id=receiver_user.id if receiver_user else None,
email_id=email_record.id,
)
db.add(interface_record)
_apply_label_rules_to_email(
db,
receiver_id=receiver_user.id if receiver_user else None,
sender_id=sender_user.id if sender_user else None,
email_id=email_record.id,
)
header_info = extract_headers(headers)
db.add(
models.EmailHeaders(
email_id=email_record.id,
return_path=header_info.get("return_path"),
message_id=header_info.get("message_id"),
in_reply_to=header_info.get("in_reply_to"),
references=header_info.get("references"),
received_chain=header_info.get("received_chain"),
spf_result=header_info.get("spf_result"),
dkim_result=header_info.get("dkim_result"),
dmarc_result=header_info.get("dmarc_result"),
raw_headers=header_info.get("raw_headers"),
status="PENDING",
)
)
urls = extract_urls(body_full)
for url in urls:
db.add(models.UrlsExtracted(email_id=email_record.id, url=url, status="PENDING"))
attachment_meta: List[Dict[str, Any]] = []
_collect_attachments(payload, attachment_meta)
for attachment in attachment_meta:
attachment_hash = None
attachment_size = attachment.get("size")
attachment_id = attachment.get("attachment_id")
attachment_url = (
f"https://gmail.googleapis.com/gmail/v1/users/me/messages/{message_id}/attachments/{attachment_id}"
)
attachment_payload = _gmail_get_json(user, db, attachment_url)
attachment_data = attachment_payload.get("data")
file_path = None
if attachment_data:
blob = _decode_base64_url_bytes(attachment_data)
attachment_hash = hashlib.sha256(blob).hexdigest()
if attachment_size is None:
attachment_size = len(blob)
email_att_dir = os.path.join(ATTACHMENTS_DIR, str(email_record.id))
os.makedirs(email_att_dir, exist_ok=True)
file_path = os.path.join(email_att_dir, attachment.get("filename", "unknown"))
with open(file_path, "wb") as f:
f.write(blob)
db.add(
models.Attachments(
email_id=email_record.id,
file_name=attachment.get("filename"),
file_type=attachment.get("mime_type"),
file_size=attachment_size,
hash_sha256=attachment_hash,
file_url=file_path,
status="PENDING",
)
)
db.commit()
if not is_self_sent:
enqueue_email_analysis(email_record.id)
if send_each_email and notify_user_id is not None:
if is_self_sent:
_send_email_updated(db, notify_user_id, email_record)
else:
_send_email_received(db, notify_user_id, email_record)
return email_record
def _sync_gmail_message_state(
user: models.User,
db: Session,
message: Dict[str, Any],
notify_user_id: Optional[int] = None,
) -> bool:
message_id = message.get("id")
if not message_id:
return False
if message.get("labelIds") is None or not message.get("payload"):
message_url = f"https://gmail.googleapis.com/gmail/v1/users/me/messages/{message_id}"
message = _gmail_get_json(user, db, message_url, params={"format": "full"})
existing = db.query(models.Email).filter(models.Email.gmail_message_id == message_id).first()
if existing:
return _sync_existing_email_with_gmail_message(
db, existing, message, notify_user_id=notify_user_id
)
created = _create_email_from_gmail_message(
user,
db,
message,
notify_user_id=notify_user_id,
send_each_email=True,
)
return created is not None
def _process_gmail_history_records(
user: models.User,
db: Session,
records: List[Dict[str, Any]],
notify_user_id: Optional[int] = None,
) -> int:
updated = 0
for record in records:
for message_data in (
record.get("messages", [])
+ record.get("messagesAdded", [])
+ record.get("messagesRemoved", [])
):
if _sync_gmail_message_state(user, db, message_data, notify_user_id=notify_user_id):
updated += 1
for label_change in (
record.get("labelsAdded", []) + record.get("labelsRemoved", [])
):
message_payload = label_change.get("message") if isinstance(label_change, dict) else None
if message_payload and _sync_gmail_message_state(
user, db, message_payload, notify_user_id=notify_user_id
):
updated += 1
for deleted in record.get("messagesDeleted", []):
message_payload = deleted.get("message") if isinstance(deleted, dict) else deleted
if not isinstance(message_payload, dict):
continue
message_id = message_payload.get("id")
if not message_id:
continue
existing = db.query(models.Email).filter(
models.Email.gmail_message_id == message_id
).first()
if existing:
_delete_local_email(db, existing)
updated += 1
return updated
def _gmail_trash_message(user: models.User, db: Session, message_id: str) -> None:
trash_url = f"https://gmail.googleapis.com/gmail/v1/users/me/messages/{message_id}/trash"
access_token = _get_valid_google_access_token(user, db)
res = requests.post(
trash_url,
headers={"Authorization": f"Bearer {access_token}"},
timeout=15,
)
if res.status_code == 401:
access_token = _refresh_google_access_token(user, db)
res = requests.post(
trash_url,
headers={"Authorization": f"Bearer {access_token}"},
timeout=15,
)
if not res.ok:
detail = res.text
if res.status_code == 403 and "insufficientPermissions" in detail:
detail += " | RESOLUTION: Visit https://myaccount.google.com/permissions, revoke this app, then re-login via /auth/google/login"
raise HTTPException(
status_code=502, detail=f"Failed to trash Gmail message: {detail}")
def _gmail_delete_message(user: models.User, db: Session, message_id: str) -> None:
delete_url = f"https://gmail.googleapis.com/gmail/v1/users/me/messages/{message_id}"
access_token = _get_valid_google_access_token(user, db)
res = requests.delete(
delete_url,
headers={"Authorization": f"Bearer {access_token}"},
timeout=15,
)
if res.status_code == 401:
access_token = _refresh_google_access_token(user, db)
res = requests.delete(
delete_url,
headers={"Authorization": f"Bearer {access_token}"},
timeout=15,
)
if not res.ok:
detail = res.text
if res.status_code == 403 and "insufficientPermissions" in detail:
detail += " | RESOLUTION: Visit https://myaccount.google.com/permissions, revoke this app, then re-login via /auth/google/login"
raise HTTPException(
status_code=502, detail=f"Failed to delete Gmail message: {detail}")
def _gmail_modify_message_labels(
user: models.User,
db: Session,
message_id: str,
add_labels: Optional[List[str]] = None,
remove_labels: Optional[List[str]] = None,
) -> None:
modify_url = f"https://gmail.googleapis.com/gmail/v1/users/me/messages/{message_id}/modify"
access_token = _get_valid_google_access_token(user, db)
payload = {}
if add_labels is not None:
payload["addLabelIds"] = add_labels
if remove_labels is not None:
payload["removeLabelIds"] = remove_labels
res = requests.post(
modify_url,
headers={"Authorization": f"Bearer {access_token}"},
json=payload,
timeout=15,
)
if res.status_code == 401:
access_token = _refresh_google_access_token(user, db)
res = requests.post(
modify_url,
headers={"Authorization": f"Bearer {access_token}"},
json=payload,
timeout=15,
)
if not res.ok:
detail = res.text
if res.status_code == 403 and "insufficientPermissions" in detail:
detail += " | RESOLUTION: Visit https://myaccount.google.com/permissions, revoke this app, then re-login via /auth/google/login"
raise HTTPException(
status_code=502, detail=f"Failed to modify Gmail labels: {detail}")
def _collect_attachments(payload: Dict[str, Any], out: List[Dict[str, Any]]) -> None:
filename = payload.get("filename")
body = payload.get("body", {})
attachment_id = body.get("attachmentId")
if filename and attachment_id:
out.append(
{
"filename": filename,
"mime_type": payload.get("mimeType"),
"attachment_id": attachment_id,
"size": body.get("size"),
}
)
for part in payload.get("parts", []) or []:
_collect_attachments(part, out)
def clean_email_body(raw: str) -> str:
if not raw:
return ""
text = re.sub(r"(?is)<(script|style).*?>.*?</\1>", " ", raw)
text = re.sub(r"(?i)<br\s*/?>", "\n", text)
text = re.sub(r"(?i)</p\s*>", "\n", text)
text = re.sub(r"(?s)<[^>]+>", " ", text)
text = html.unescape(text)
text = re.sub(r"[ \t\r\f\v]+", " ", text)
text = re.sub(r"\n\s*\n+", "\n", text)
return text.strip()
def _serialize_email(email: models.Email) -> Dict[str, Any]:
category_name = email.category.name if email.category else None
body_full = email.body_full or ""
body_clean = clean_email_body(body_full)
date_epoch_ms = int(email.date.timestamp() * 1000) if email.date else None
return {
"email_id": email.id,
"gmail_message_id": email.gmail_message_id,
"thread_id": email.thread_id,
"subject": email.subject,
"snippet": email.body_snippet,
"body": email.body_full,
"body_clean": body_clean,
"category": category_name,
"date": email.date.isoformat() if email.date else None,
"date_epoch_ms": date_epoch_ms,
"status": email.status,
"delivery_status": email.delivery_status,
"risk_score": email.risk_score,
"final_verdict": email.final_verdict,
"user_act": email.user_act,
"urls_status": email.urls_status,