mail-agent/src/api/accounts.py

102 lines
2.6 KiB
Python

"""Account management API endpoints."""
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional
from ..config import get_config, AccountConfig
from ..models import Account, Mailbox
from ..imap import ImapClient
router = APIRouter(prefix="/accounts", tags=["accounts"])
class AccountCreate(BaseModel):
id: str
host: str
port: int = 993
username: str
password: str
tls: str = "ssl"
@router.get("")
async def list_accounts() -> list[Account]:
"""List all configured accounts."""
config = get_config()
accounts = []
for account_id, acc_config in config.accounts.items():
# Try to connect to check status
connected = False
last_error = None
try:
client = ImapClient(account_id, acc_config)
client.connect()
client.disconnect()
connected = True
except Exception as e:
last_error = str(e)
accounts.append(Account(
id=account_id,
host=acc_config.host,
port=acc_config.port,
username=acc_config.username,
tls=acc_config.tls,
connected=connected,
last_error=last_error,
))
return accounts
@router.get("/{account_id}")
async def get_account(account_id: str) -> Account:
"""Get account details."""
config = get_config()
if account_id not in config.accounts:
raise HTTPException(status_code=404, detail="Account not found")
acc_config = config.accounts[account_id]
connected = False
last_error = None
try:
client = ImapClient(account_id, acc_config)
client.connect()
client.disconnect()
connected = True
except Exception as e:
last_error = str(e)
return Account(
id=account_id,
host=acc_config.host,
port=acc_config.port,
username=acc_config.username,
tls=acc_config.tls,
connected=connected,
last_error=last_error,
)
@router.get("/{account_id}/mailboxes")
async def list_mailboxes(account_id: str) -> list[Mailbox]:
"""List mailboxes/folders for an account."""
config = get_config()
if account_id not in config.accounts:
raise HTTPException(status_code=404, detail="Account not found")
acc_config = config.accounts[account_id]
try:
client = ImapClient(account_id, acc_config)
with client.session():
return client.list_mailboxes()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))