"""Connection test endpoints — IMAP, SMTP, BizDocs.""" import imaplib import smtplib import httpx import logging from fastapi import APIRouter from ..schemas import TestPayload, ConnectionTestResult router = APIRouter(prefix="/connection", tags=["connection"]) log = logging.getLogger(__name__) def _test_imap(payload: TestPayload) -> tuple[bool, str | None]: try: if payload.imap_port in (993, 995) or True: # always try SSL first imap = imaplib.IMAP4_SSL(payload.imap_host, payload.imap_port) else: imap = imaplib.IMAP4(payload.imap_host, payload.imap_port) imap.login(payload.imap_user, payload.imap_password) imap.logout() return True, None except Exception as exc: return False, str(exc) def _test_smtp(payload: TestPayload) -> tuple[bool, str | None]: if not payload.smtp_host or not payload.smtp_user or not payload.smtp_password: return True, None # SMTP not configured — skip try: with smtplib.SMTP(payload.smtp_host, payload.smtp_port or 587, timeout=10) as smtp: smtp.ehlo() smtp.starttls() smtp.login(payload.smtp_user, payload.smtp_password) return True, None except Exception as exc: return False, str(exc) def _test_bizdocs(payload: TestPayload) -> tuple[bool, str | None]: if not payload.bizdocs_api_key: return True, None # not configured — skip try: with httpx.Client(timeout=10) as client: # Generic check: hit the API root or /health resp = client.get( "https://app.bizdocs.pt/api/health", headers={"Authorization": f"Bearer {payload.bizdocs_api_key}"}, ) if resp.status_code in (200, 204, 401, 403): # 401/403 means we reached the API (key may be wrong but endpoint responded) return resp.status_code not in (401, 403), ( None if resp.status_code not in (401, 403) else f"HTTP {resp.status_code}" ) resp.raise_for_status() return True, None except Exception as exc: return False, str(exc) def _run_test(payload: TestPayload) -> ConnectionTestResult: imap_ok, imap_err = _test_imap(payload) smtp_ok, smtp_err = _test_smtp(payload) bdocs_ok, bdocs_err = _test_bizdocs(payload) return ConnectionTestResult( imap_ok=imap_ok, imap_error=imap_err, smtp_ok=smtp_ok, smtp_error=smtp_err, bizdocs_ok=bdocs_ok, bizdocs_error=bdocs_err, ) @router.post("/test", response_model=ConnectionTestResult) def test_connection(payload: TestPayload): return _run_test(payload)