feat: persist imported DMARC reports
This commit is contained in:
@@ -4,7 +4,9 @@ from typing import Any, Dict, Optional
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import SessionLocal, get_db
|
||||
from app.core.security import require_admin_auth
|
||||
from app.services.imap_client import IMAPClient
|
||||
|
||||
@@ -22,6 +24,20 @@ class IMAPTestRequest(BaseModel):
|
||||
ssl: bool = True
|
||||
|
||||
|
||||
def _fetch_imap_reports_background(days: int, delete_emails: bool) -> None:
|
||||
"""Fetch IMAP reports with a standalone DB session for background imports."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
imap_client = IMAPClient(delete_emails=delete_emails, db=db)
|
||||
imap_client.fetch_reports(days=days)
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.post("/test-connection")
|
||||
async def test_imap_connection(
|
||||
request: IMAPTestRequest,
|
||||
@@ -57,6 +73,7 @@ async def test_imap_connection(
|
||||
async def fetch_imap_reports(
|
||||
background_tasks: BackgroundTasks,
|
||||
_auth: dict = Depends(require_admin_auth),
|
||||
db: Session = Depends(get_db),
|
||||
days: int = 7,
|
||||
delete_emails: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
@@ -69,11 +86,11 @@ async def fetch_imap_reports(
|
||||
if days < 1 or days > 365:
|
||||
raise HTTPException(status_code=400, detail="Days parameter must be between 1 and 365")
|
||||
|
||||
imap_client = IMAPClient(delete_emails=delete_emails)
|
||||
imap_client = IMAPClient(delete_emails=delete_emails, db=db)
|
||||
|
||||
# Run in background if it might take a while
|
||||
if days > 14:
|
||||
background_tasks.add_task(imap_client.fetch_reports, days)
|
||||
background_tasks.add_task(_fetch_imap_reports_background, days, delete_emails)
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Background task started to fetch {days} days of reports",
|
||||
@@ -83,6 +100,7 @@ async def fetch_imap_reports(
|
||||
# Otherwise run immediately
|
||||
try:
|
||||
results = imap_client.fetch_reports(days=days)
|
||||
db.commit()
|
||||
|
||||
return {
|
||||
"success": results["success"],
|
||||
|
||||
Reference in New Issue
Block a user