This commit is contained in:
2026-03-18 17:43:03 +01:00
parent d80d912fb3
commit c89c08c397
10 changed files with 2352 additions and 123 deletions
+193 -122
View File
@@ -1,20 +1,25 @@
"""
Logica di sincronizzazione messaggi IMAP.
Logica di sincronizzazione messaggi IMAP Fase 3 aggiornata.
Responsabilità:
1. Fetch della lista UID > last_sync_uid
2. Download envelope + raw EML per ogni UID
3. Parsing base degli header (subject, from, to, date)
4. Salvataggio in tabella messages
3. Parsing completo EML tramite app.parsers (Fase 3):
- Classificazione tipo PEC (X-Ricevuta / X-TipoRicevuta)
- Estrazione allegati (body text/html + allegati file)
- EML-in-EML per ricevute PEC
4. Salvataggio messaggio in tabella messages
5. Upload raw EML su MinIO
6. Aggiornamento last_sync_uid e last_sync_at sulla mailbox
7. Pubblicazione evento Redis per notifica WebSocket
6. Upload allegati su MinIO + inserimento in tabella attachments
7. State machine messaggi outbound (sent→accepted→delivered/anomaly)
tramite X-Riferimento-Message-ID
8. Aggiornamento last_sync_uid e last_sync_at sulla mailbox
9. Pubblicazione evento Redis per notifica WebSocket
"""
import email
import email.header
import email.utils
import hashlib
import json
import logging
import re
@@ -27,14 +32,16 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import get_settings
from app.models import Mailbox, Message
from app.storage.minio_client import upload_eml
from app.models import Attachment, Mailbox, Message
from app.parsers.eml_parser import parse_eml
from app.parsers.pec_parser import apply_outbound_transition, classify_pec_message
from app.storage.minio_client import upload_attachment, upload_eml
logger = logging.getLogger(__name__)
settings = get_settings()
# ─── Helper: decodifica header email ─────────────────────────────────────────
# ─── Helper legacy (mantenuti per backward compatibility con i test) ──────────
def _decode_header(header_value: str | None) -> str | None:
"""Decodifica header RFC 2047 (es. =?utf-8?b?...?=) in stringa Python."""
@@ -80,93 +87,38 @@ def _parse_date(date_str: str | None) -> datetime | None:
def _classify_pec_type(msg: email.message.Message) -> str:
"""
Classifica il tipo PEC dal header X-Ricevuta / X-TipoRicevuta.
Fase 3 fa il parsing completo; qui classifichiamo al meglio possibile.
Mantenuto per backward compatibility usa il parser completo internamente.
"""
x_ricevuta = msg.get("X-Ricevuta", "").lower()
x_tipo = msg.get("X-TipoRicevuta", "").lower()
TYPE_MAP = {
"accettazione": "accettazione",
"non-accettazione": "non_accettazione",
"presa-in-carico": "presa_in_carico",
"avvenuta-consegna": "avvenuta_consegna",
"mancata-consegna": "mancata_consegna",
"errore-consegna": "errore_consegna",
"preavviso-mancata-consegna": "preavviso_mancata_consegna",
"rilevazione-virus": "rilevazione_virus",
}
value = x_tipo or x_ricevuta
return TYPE_MAP.get(value, "posta_certificata")
pec_class = classify_pec_message(msg)
return pec_class.pec_type
def _parse_eml(raw_bytes: bytes) -> dict:
"""
Parsing di base di un EML estrae i campi necessari per la tabella messages.
Il parsing completo (body, allegati, EML-in-EML) è in Fase 3.
Parsing di base di un EML.
Wrapper del nuovo parser completo (Fase 3).
Mantenuto per backward compatibility con i test esistenti.
Restituisce un dict con i campi base necessari per la tabella messages.
"""
try:
msg = email.message_from_bytes(raw_bytes)
except Exception as e:
logger.warning(f"Errore parsing EML: {e}")
return {}
parsed = parse_eml(raw_bytes)
subject = _decode_header(msg.get("Subject"))
from_addr = email.utils.parseaddr(msg.get("From", ""))[1] or None
to_addrs = _extract_addresses(msg.get("To"))
cc_addrs = _extract_addresses(msg.get("Cc"))
message_id = msg.get("Message-ID", "").strip() or None
date = _parse_date(msg.get("Date"))
pec_type = _classify_pec_type(msg)
# Estrazione body text/html (best-effort Fase 3 fa il parsing completo)
body_text = None
body_html = None
has_attachments = False
if msg.is_multipart():
for part in msg.walk():
ct = part.get_content_type()
disp = part.get("Content-Disposition", "")
if "attachment" in disp or "inline" in disp:
if part.get_filename():
has_attachments = True
elif ct == "text/plain" and body_text is None:
try:
charset = part.get_content_charset() or "utf-8"
body_text = part.get_payload(decode=True).decode(charset, errors="replace")
except Exception:
pass
elif ct == "text/html" and body_html is None:
try:
charset = part.get_content_charset() or "utf-8"
body_html = part.get_payload(decode=True).decode(charset, errors="replace")
except Exception:
pass
else:
ct = msg.get_content_type()
try:
charset = msg.get_content_charset() or "utf-8"
payload = msg.get_payload(decode=True)
if payload:
if ct == "text/plain":
body_text = payload.decode(charset, errors="replace")
elif ct == "text/html":
body_html = payload.decode(charset, errors="replace")
except Exception:
pass
pec_type = "posta_certificata"
if parsed.raw_message is not None:
pec_class = classify_pec_message(parsed.raw_message)
pec_type = pec_class.pec_type
return {
"subject": subject,
"from_address": from_addr,
"to_addresses": to_addrs if to_addrs else None,
"cc_addresses": cc_addrs if cc_addrs else None,
"message_id_header": message_id,
"sent_at": date,
"subject": parsed.subject,
"from_address": parsed.from_address,
"to_addresses": parsed.to_addresses if parsed.to_addresses else None,
"cc_addresses": parsed.cc_addresses if parsed.cc_addresses else None,
"message_id_header": parsed.message_id,
"sent_at": parsed.date,
"pec_type": pec_type,
"body_text": body_text,
"body_html": body_html,
"has_attachments": has_attachments,
"body_text": parsed.body_text,
"body_html": parsed.body_html,
"has_attachments": parsed.has_attachments,
}
@@ -188,8 +140,6 @@ async def sync_new_messages(
search_range = f"{last_uid + 1}:*"
# ── SEARCH UID > last_sync_uid ─────────────────────────────────────────────
# aioimaplib non supporta uid('SEARCH',...) → usare search('UID', range)
# che invia "SEARCH UID n:*" e restituisce numeri di sequenza
try:
status, search_data = await imap_client.search("UID", search_range)
except Exception as e:
@@ -202,7 +152,6 @@ async def sync_new_messages(
)
return 0
# search() restituisce numeri di sequenza (non UID)
raw_seqs = b" ".join(
d if isinstance(d, bytes) else d.encode() for d in search_data
).decode("ascii", errors="ignore").split()
@@ -211,7 +160,6 @@ async def sync_new_messages(
if not seq_numbers:
return 0
# Limita il numero di fetch per ciclo
seq_numbers = seq_numbers[: settings.imap_max_fetch_per_cycle]
logger.info(
f"[{mailbox.email_address}] Trovati {len(seq_numbers)} messaggi nuovi da sincronizzare"
@@ -259,12 +207,10 @@ async def _fetch_and_save_message_by_seq(
) -> tuple[int | None, bool]:
"""
Fetcha un singolo messaggio per NUMERO DI SEQUENZA (non UID).
Include UID nella richiesta FETCH per estrarlo dalla risposta.
Returns:
(uid, saved): UID del messaggio e True se salvato, False altrimenti.
"""
# FETCH seq (UID RFC822 RFC822.SIZE)
try:
status, fetch_data = await imap_client.fetch(seq, "(UID RFC822 RFC822.SIZE)")
except Exception as e:
@@ -277,27 +223,18 @@ async def _fetch_and_save_message_by_seq(
)
return None, False
# Debug: mostra la struttura di fetch_data
items_info = [(type(x).__name__, len(x) if isinstance(x, (bytes, str)) else str(x)) for x in fetch_data]
logger.debug(f"[{mailbox.email_address}] fetch_data seq {seq}: {items_info}")
# Estrae UID, raw EML e size dalla risposta.
# NOTA CRITICA: aioimaplib restituisce il corpo EML come `bytearray` (non `bytes`)!
# [0] bytes → FETCH response header con UID e RFC822.SIZE
# [1] bytearray → raw EML (il corpo del messaggio)
# [2] bytes → ')' (chiusura)
# [3] bytes → riga OK finale
uid: int | None = None
raw_eml: bytes | None = None
size_bytes: int | None = None
for item in fetch_data:
if isinstance(item, bytearray):
# Questo è il corpo del messaggio EML
if len(item) > 200:
raw_eml = bytes(item)
elif isinstance(item, bytes):
# Risposta header estrae UID e RFC822.SIZE
item_str = item.decode("ascii", errors="ignore")
uid_match = re.search(r"UID\s+(\d+)", item_str)
if uid_match:
@@ -314,7 +251,6 @@ async def _fetch_and_save_message_by_seq(
size_bytes = int(size_match.group(1))
if uid is None or uid <= last_uid:
# Questo messaggio ha un UID <= last_uid, non va sincronizzato
return uid, False
if not raw_eml:
@@ -343,7 +279,6 @@ async def _fetch_and_save_message(
) -> bool:
"""
Fetcha un singolo messaggio per UID (usato dal job sync_mailbox one-shot).
Usa UID FETCH (aioimaplib uid() method).
"""
existing = await db.execute(
select(Message.id).where(
@@ -387,6 +322,8 @@ async def _fetch_and_save_message(
)
# ─── Save message (Fase 3 con parser completo, allegati, state machine) ────
async def _save_message(
uid: int,
raw_eml: bytes,
@@ -396,9 +333,16 @@ async def _save_message(
redis_client: aioredis.Redis,
) -> bool:
"""
Salva un messaggio EML in DB e su MinIO. Pubblica evento WebSocket.
Salva un messaggio EML in DB e su MinIO.
Fase 3 aggiornato per:
- Parser completo (body, allegati, EML-in-EML)
- Classificazione precisa tipo PEC (tutti i provider)
- Salvataggio allegati su MinIO + tabella attachments
- State machine outbound: aggiorna stato messaggio originale alla ricezione ricevuta
- Collegamento parent_message_id via X-Riferimento-Message-ID
"""
# Idempotenza
# ── Idempotenza ───────────────────────────────────────────────────────────
existing = await db.execute(
select(Message.id).where(
Message.mailbox_id == mailbox.id,
@@ -409,10 +353,25 @@ async def _save_message(
logger.debug(f"[{mailbox.email_address}] UID {uid} già in DB, skip")
return False
parsed = _parse_eml(raw_eml)
# ── Parsing completo EML ──────────────────────────────────────────────────
parsed = parse_eml(raw_eml)
pec_class = classify_pec_message(
parsed.raw_message or email.message_from_bytes(raw_eml)
)
received_at = datetime.now(UTC)
# Upload su MinIO
# ── State machine: trova e aggiorna messaggio outbound ────────────────────
parent_message_id: uuid.UUID | None = None
if pec_class.is_receipt and pec_class.riferimento_message_id:
parent_message_id = await _apply_outbound_state_machine(
riferimento_message_id=pec_class.riferimento_message_id,
pec_type=pec_class.pec_type,
tenant_id=mailbox.tenant_id,
db=db,
)
# ── Upload raw EML su MinIO ───────────────────────────────────────────────
eml_path: str | None = None
try:
eml_path = await upload_eml(
@@ -422,9 +381,9 @@ async def _save_message(
eml_bytes=raw_eml,
)
except Exception as e:
logger.error(f"[{mailbox.email_address}] Upload MinIO UID {uid}: {e}")
logger.error(f"[{mailbox.email_address}] Upload EML MinIO UID {uid}: {e}")
# Salva in DB
# ── Salva messaggio in DB ─────────────────────────────────────────────────
message = Message(
id=uuid.uuid4(),
tenant_id=mailbox.tenant_id,
@@ -433,25 +392,35 @@ async def _save_message(
imap_folder="INBOX",
direction="inbound",
state="received",
pec_type=parsed.get("pec_type", "posta_certificata"),
subject=parsed.get("subject"),
from_address=parsed.get("from_address"),
to_addresses=parsed.get("to_addresses"),
cc_addresses=parsed.get("cc_addresses"),
message_id_header=parsed.get("message_id_header"),
sent_at=parsed.get("sent_at"),
pec_type=pec_class.pec_type,
subject=parsed.subject,
from_address=parsed.from_address,
to_addresses=parsed.to_addresses if parsed.to_addresses else None,
cc_addresses=parsed.cc_addresses if parsed.cc_addresses else None,
message_id_header=parsed.message_id,
sent_at=parsed.date,
received_at=received_at,
size_bytes=size_bytes,
body_text=parsed.get("body_text"),
body_html=parsed.get("body_html"),
has_attachments=parsed.get("has_attachments", False),
body_text=parsed.body_text,
body_html=parsed.body_html,
has_attachments=parsed.has_attachments,
parent_message_id=parent_message_id,
raw_eml_path=eml_path,
is_read=False,
)
db.add(message)
await db.flush()
await db.flush() # ottieni message.id prima di salvare gli allegati
# Pubblica evento Redis per WebSocket
# ── Salva allegati su MinIO + tabella attachments ─────────────────────────
if parsed.attachments:
await _save_attachments(
attachments=parsed.attachments,
message=message,
mailbox=mailbox,
db=db,
)
# ── Pubblica evento Redis per WebSocket ───────────────────────────────────
try:
event = {
"type": "mailbox:new_message",
@@ -460,6 +429,7 @@ async def _save_message(
"subject": message.subject or "",
"from_address": message.from_address or "",
"pec_type": message.pec_type,
"is_receipt": pec_class.is_receipt,
"received_at": received_at.isoformat(),
}
await redis_client.publish(f"ws:tenant:{mailbox.tenant_id}", json.dumps(event))
@@ -468,6 +438,107 @@ async def _save_message(
logger.info(
f"[{mailbox.email_address}] Nuovo messaggio: UID={uid} "
f"subject={message.subject!r} pec_type={message.pec_type}"
f"pec_type={pec_class.pec_type!r} "
f"subject={message.subject!r} "
f"allegati={len(parsed.attachments)}"
)
return True
async def _apply_outbound_state_machine(
riferimento_message_id: str,
pec_type: str,
tenant_id: uuid.UUID,
db: AsyncSession,
) -> uuid.UUID | None:
"""
Aggiorna lo stato del messaggio outbound originale in base alla ricevuta.
Cerca il messaggio outbound con message_id_header == riferimento_message_id,
applica la transizione di stato se valida.
Returns:
UUID del messaggio originale se trovato, None altrimenti.
"""
result = await db.execute(
select(Message).where(
Message.tenant_id == tenant_id,
Message.message_id_header == riferimento_message_id,
Message.direction == "outbound",
)
)
parent_msg = result.scalar_one_or_none()
if not parent_msg:
logger.debug(
f"Messaggio outbound non trovato per riferimento={riferimento_message_id!r} "
f"(potrebbe essere stato inviato da client diverso)"
)
return None
new_state = apply_outbound_transition(parent_msg.state, pec_type)
if new_state:
old_state = parent_msg.state
parent_msg.state = new_state
parent_msg.updated_at = datetime.now(UTC)
await db.flush()
logger.info(
f"State machine outbound: {riferimento_message_id!r} "
f"{old_state!r}{new_state!r} (ricevuta: {pec_type!r})"
)
return parent_msg.id
async def _save_attachments(
attachments: list,
message: Message,
mailbox: Mailbox,
db: AsyncSession,
) -> None:
"""
Carica gli allegati su MinIO e inserisce i record in tabella attachments.
Args:
attachments: lista di AttachmentInfo dal parser EML
message: messaggio DB a cui appartengono gli allegati
mailbox: casella (per il path MinIO)
db: sessione DB
"""
for att in attachments:
storage_path: str | None = None
try:
storage_path = await upload_attachment(
tenant_id=str(mailbox.tenant_id),
mailbox_id=str(mailbox.id),
message_id=str(message.id),
filename=att.filename,
content=att.content,
content_type=att.content_type,
)
except Exception as e:
logger.error(
f"Upload allegato {att.filename!r} per messaggio {message.id}: {e}"
)
# Continua con gli altri allegati anche se uno fallisce
continue
# Inserisci record in DB
att_record = Attachment(
id=uuid.uuid4(),
tenant_id=message.tenant_id,
message_id=message.id,
filename=att.filename,
content_type=att.content_type,
size_bytes=att.size_bytes,
storage_path=storage_path,
checksum_sha256=att.checksum_sha256,
)
db.add(att_record)
# flush per persistere tutti gli allegati nella transazione corrente
try:
await db.flush()
except Exception as e:
logger.error(f"Errore flush allegati per messaggio {message.id}: {e}")