Two-way draft sync, signatures, sent/bcc fixes, and mail-list UI
Backend - Sent copies: persist locally on send + periodic multi-folder CONDSTORE poll (Sent/Archive/Trash/Junk) so they thread and show without an IDLE-only INBOX. - Bcc: transmitted copy omits Bcc, Sent copy keeps it; store/display bcc_addr. - Drafts: mirror local drafts to the IMAP Drafts folder (append/replace/expunge); inbound sync of foreign drafts (un-threaded) with adopt-to-edit + dedup by UID. - Per-user storage quota (5 GiB default) and manual "sync all folders" action. - Account editing (display/color/server/password) and per-account HTML signature. - Account view scoped to that account's inbox; new migrations 0006–0009. Frontend - Mail-list pagination, folder filters (All/Unread/Pinned), sort toggle, refresh. - Aligned + widened mail-list margins; reading-pane bars fixed height. - Rich-text composer: color palette, highlight, image; attachments; expand/pop-out. - Signatures: auto-insert for new mail, replace on From change, reply insert. - Restore/Delete actions per folder; drafts view merges local + remote, date-sorted. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -32,6 +32,7 @@ from app.identity.deps import CurrentUser, require_csrf
|
||||
from app.models import Account
|
||||
from app.queue import get_arq_pool
|
||||
from app.redis_client import get_redis
|
||||
from app.security.crypto import encrypt_secret
|
||||
|
||||
router = APIRouter(prefix="/accounts", tags=["accounts"])
|
||||
|
||||
@@ -75,12 +76,27 @@ async def list_accounts(user: CurrentUser, db: DbSession) -> list[AccountOut]:
|
||||
)
|
||||
return [
|
||||
AccountOut(
|
||||
id=a.id, email=a.email, display_name=a.display_name, color=a.color, state=a.state
|
||||
id=a.id,
|
||||
email=a.email,
|
||||
display_name=a.display_name,
|
||||
color=a.color,
|
||||
state=a.state,
|
||||
signature=a.signature,
|
||||
)
|
||||
for a in accounts
|
||||
]
|
||||
|
||||
|
||||
@router.post("/sync", dependencies=[Depends(require_csrf)])
|
||||
async def sync_all_accounts(user: CurrentUser, db: DbSession) -> dict[str, str]:
|
||||
"""Poll every folder of each of the user's accounts (manual Refresh)."""
|
||||
account_ids = list(await db.scalars(select(Account.id).where(Account.user_id == user.id)))
|
||||
pool = await get_arq_pool()
|
||||
for account_id in account_ids:
|
||||
await pool.enqueue_job("refresh_account_job", str(account_id))
|
||||
return {"status": "queued"}
|
||||
|
||||
|
||||
@router.post("/discover", response_model=DiscoverResponse, dependencies=[Depends(require_csrf)])
|
||||
async def discover_account(body: DiscoverRequest, user: CurrentUser) -> DiscoverResponse:
|
||||
await _rate_limit_discover(user.id)
|
||||
@@ -135,6 +151,25 @@ async def create_new_account(
|
||||
return _detail(account)
|
||||
|
||||
|
||||
@router.get("/{account_id}", response_model=AccountDetailOut)
|
||||
async def get_account(account_id: uuid.UUID, user: CurrentUser, db: DbSession) -> AccountDetailOut:
|
||||
account = await db.scalar(
|
||||
select(Account).where(Account.id == account_id, Account.user_id == user.id)
|
||||
)
|
||||
if account is None:
|
||||
raise_api_error(404, "not_found", "account not found")
|
||||
return _detail(account)
|
||||
|
||||
|
||||
def _server_from_config(cfg: dict[str, object]) -> ServerConfig:
|
||||
return ServerConfig(
|
||||
str(cfg["host"]),
|
||||
int(str(cfg["port"])),
|
||||
str(cfg.get("tls", "ssl")),
|
||||
str(cfg.get("auth", "password")),
|
||||
)
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/{account_id}", response_model=AccountDetailOut, dependencies=[Depends(require_csrf)]
|
||||
)
|
||||
@@ -150,7 +185,51 @@ async def update_account(
|
||||
account.display_name = body.display_name
|
||||
if body.color is not None:
|
||||
account.color = body.color
|
||||
if body.signature is not None:
|
||||
account.signature = body.signature
|
||||
|
||||
# Connection settings and/or password: re-validate against the servers, then
|
||||
# re-encrypt the secret and re-sync. The password must be supplied (§10.2: the
|
||||
# stored secret is only decrypted in the worker, never here).
|
||||
conn_change = body.imap is not None or body.smtp is not None or body.password is not None
|
||||
if conn_change:
|
||||
if not body.password:
|
||||
raise_api_error(
|
||||
400,
|
||||
"password_required",
|
||||
"the mailbox password is required to change server settings",
|
||||
)
|
||||
imap = (
|
||||
_to_server_config(body.imap) if body.imap else _server_from_config(account.imap_config)
|
||||
)
|
||||
smtp = (
|
||||
_to_server_config(body.smtp) if body.smtp else _server_from_config(account.smtp_config)
|
||||
)
|
||||
try:
|
||||
await test_account(imap=imap, smtp=smtp, username=account.email, password=body.password)
|
||||
except AccountTestError as exc:
|
||||
raise_api_error(400, exc.code, exc.detail)
|
||||
account.imap_config = {
|
||||
"host": imap.host,
|
||||
"port": imap.port,
|
||||
"tls": imap.tls,
|
||||
"auth": imap.auth,
|
||||
}
|
||||
account.smtp_config = {
|
||||
"host": smtp.host,
|
||||
"port": smtp.port,
|
||||
"tls": smtp.tls,
|
||||
"auth": smtp.auth,
|
||||
}
|
||||
account.secret_ct = encrypt_secret(body.password.encode("utf-8"))
|
||||
account.state = "backfilling"
|
||||
|
||||
await db.commit()
|
||||
|
||||
if conn_change:
|
||||
pool = await get_arq_pool()
|
||||
await pool.enqueue_job("sync_bootstrap_account", str(account.id))
|
||||
|
||||
return _detail(account)
|
||||
|
||||
|
||||
@@ -171,6 +250,7 @@ def _detail(account: Account) -> AccountDetailOut:
|
||||
color=account.color,
|
||||
state=account.state,
|
||||
state_detail=account.state_detail,
|
||||
signature=account.signature,
|
||||
imap_config=account.imap_config,
|
||||
smtp_config=account.smtp_config,
|
||||
)
|
||||
|
||||
+122
-2
@@ -16,8 +16,14 @@ from app.config import get_settings
|
||||
from app.db import get_session
|
||||
from app.identity.deps import CurrentUser, require_csrf
|
||||
from app.indexer import blobstore
|
||||
from app.models import ComposeAttachment, Draft
|
||||
from app.outbox.schemas import DraftIn, DraftOut, SendRequest, SendResponse
|
||||
from app.models import BodyPart, ComposeAttachment, Draft, Mailbox, Message
|
||||
from app.outbox.schemas import (
|
||||
DraftIn,
|
||||
DraftOut,
|
||||
RemoteDraftOut,
|
||||
SendRequest,
|
||||
SendResponse,
|
||||
)
|
||||
from app.outbox.service import DraftError, cancel_outbox, create_outbox, upsert_draft
|
||||
from app.queue import get_arq_pool
|
||||
|
||||
@@ -102,6 +108,104 @@ async def list_drafts(user: CurrentUser, db: DbSession) -> list[DraftOut]:
|
||||
return [_draft_out(d) for d in drafts]
|
||||
|
||||
|
||||
def _fmt_addr(addr: dict[str, str]) -> str:
|
||||
email = addr.get("email", "")
|
||||
name = addr.get("name", "")
|
||||
return f"{name} <{email}>" if name else email
|
||||
|
||||
|
||||
async def _own_draft_uids(db: AsyncSession, user_id: uuid.UUID) -> set[tuple[uuid.UUID, int]]:
|
||||
"""(account_id, imap_uid) of drafts we mirrored — excluded from the remote list."""
|
||||
rows = await db.execute(
|
||||
select(Draft.account_id, Draft.imap_uid).where(
|
||||
Draft.user_id == user_id, Draft.imap_uid.isnot(None)
|
||||
)
|
||||
)
|
||||
return {(r.account_id, r.imap_uid) for r in rows}
|
||||
|
||||
|
||||
@router.get("/drafts/remote", response_model=list[RemoteDraftOut])
|
||||
async def list_remote_drafts(user: CurrentUser, db: DbSession) -> list[RemoteDraftOut]:
|
||||
"""Drafts sitting in the IMAP Drafts folder that we haven't already adopted."""
|
||||
own = await _own_draft_uids(db, user.id)
|
||||
messages = await db.scalars(
|
||||
select(Message)
|
||||
.join(Mailbox, Mailbox.id == Message.mailbox_id)
|
||||
.where(Message.user_id == user.id, Mailbox.special_use == "drafts")
|
||||
.order_by(Message.internal_date.desc())
|
||||
)
|
||||
out: list[RemoteDraftOut] = []
|
||||
for m in messages:
|
||||
if (m.account_id, m.uid) in own:
|
||||
continue
|
||||
out.append(
|
||||
RemoteDraftOut(
|
||||
message_id=m.id,
|
||||
account_id=m.account_id,
|
||||
imap_uid=m.uid,
|
||||
subject=m.subject,
|
||||
to=[_fmt_addr(a) for a in m.to_addr],
|
||||
cc=[_fmt_addr(a) for a in m.cc_addr],
|
||||
bcc=[_fmt_addr(a) for a in m.bcc_addr],
|
||||
snippet=m.snippet,
|
||||
updated_at=(m.date_hdr or m.internal_date).isoformat(),
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/drafts/adopt/{message_id}", response_model=DraftOut)
|
||||
async def adopt_remote_draft(
|
||||
message_id: uuid.UUID, user: CurrentUser, db: DbSession
|
||||
) -> DraftOut:
|
||||
"""Turn a Drafts-folder message into an editable local draft (linked by UID)."""
|
||||
msg = await db.scalar(
|
||||
select(Message)
|
||||
.join(Mailbox, Mailbox.id == Message.mailbox_id)
|
||||
.where(
|
||||
Message.id == message_id,
|
||||
Message.user_id == user.id,
|
||||
Mailbox.special_use == "drafts",
|
||||
)
|
||||
)
|
||||
if msg is None:
|
||||
raise_api_error(404, "not_found", "draft message not found")
|
||||
|
||||
# Idempotent: if already adopted (a local draft links this UID), return it.
|
||||
existing = await db.scalar(
|
||||
select(Draft).where(
|
||||
Draft.user_id == user.id,
|
||||
Draft.account_id == msg.account_id,
|
||||
Draft.imap_uid == msg.uid,
|
||||
)
|
||||
)
|
||||
if existing is not None:
|
||||
return _draft_out(existing)
|
||||
|
||||
parts = list(await db.scalars(select(BodyPart).where(BodyPart.message_id == msg.id)))
|
||||
html = next((p.content for p in parts if p.kind == "html_sanitized"), "")
|
||||
text = next((p.content for p in parts if p.kind == "text"), "")
|
||||
payload = {
|
||||
"to": [_fmt_addr(a) for a in msg.to_addr],
|
||||
"cc": [_fmt_addr(a) for a in msg.cc_addr],
|
||||
"bcc": [_fmt_addr(a) for a in msg.bcc_addr],
|
||||
"subject": msg.subject,
|
||||
"html": html,
|
||||
"text": text,
|
||||
"attachment_ids": [],
|
||||
}
|
||||
draft = Draft(
|
||||
user_id=user.id,
|
||||
account_id=msg.account_id,
|
||||
kind="new",
|
||||
payload=payload,
|
||||
imap_uid=msg.uid,
|
||||
)
|
||||
db.add(draft)
|
||||
await db.commit()
|
||||
return _draft_out(draft)
|
||||
|
||||
|
||||
@router.post("/drafts", response_model=DraftOut)
|
||||
async def create_draft(body: DraftIn, user: CurrentUser, db: DbSession) -> DraftOut:
|
||||
try:
|
||||
@@ -125,13 +229,29 @@ async def update_draft(
|
||||
return _draft_out(draft)
|
||||
|
||||
|
||||
@router.post("/drafts/{draft_id}/publish")
|
||||
async def publish_draft(draft_id: uuid.UUID, user: CurrentUser, db: DbSession) -> dict[str, str]:
|
||||
"""Mirror the draft to the account's IMAP Drafts folder (continue on any client)."""
|
||||
draft = await db.scalar(select(Draft).where(Draft.id == draft_id, Draft.user_id == user.id))
|
||||
if draft is None:
|
||||
raise_api_error(404, "not_found", "draft not found")
|
||||
pool = await get_arq_pool()
|
||||
await pool.enqueue_job("push_draft_to_imap_job", str(draft_id))
|
||||
return {"status": "queued"}
|
||||
|
||||
|
||||
@router.delete("/drafts/{draft_id}")
|
||||
async def delete_draft(draft_id: uuid.UUID, user: CurrentUser, db: DbSession) -> dict[str, str]:
|
||||
draft = await db.scalar(select(Draft).where(Draft.id == draft_id, Draft.user_id == user.id))
|
||||
if draft is None:
|
||||
raise_api_error(404, "not_found", "draft not found")
|
||||
account_id, imap_uid = draft.account_id, draft.imap_uid
|
||||
await db.delete(draft)
|
||||
await db.commit()
|
||||
# Remove the mirrored copy from the server Drafts folder too.
|
||||
if imap_uid:
|
||||
pool = await get_arq_pool()
|
||||
await pool.enqueue_job("remove_imap_draft_job", str(account_id), imap_uid)
|
||||
return {"status": "deleted"}
|
||||
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ class MessageEnvelope(BaseModel):
|
||||
from_addr: list[Address]
|
||||
to_addr: list[Address]
|
||||
cc_addr: list[Address]
|
||||
bcc_addr: list[Address]
|
||||
date: dt.datetime
|
||||
flags: list[str]
|
||||
is_unread: bool
|
||||
@@ -79,6 +80,7 @@ class AccountOut(BaseModel):
|
||||
display_name: str
|
||||
color: str
|
||||
state: str
|
||||
signature: str = ""
|
||||
|
||||
|
||||
class SearchThreadHit(BaseModel):
|
||||
|
||||
@@ -6,11 +6,12 @@ from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db import get_session
|
||||
from app.identity.deps import CurrentUser, require_csrf
|
||||
from app.models import User
|
||||
from app.models import Message, User
|
||||
|
||||
router = APIRouter(prefix="/settings", tags=["settings"])
|
||||
|
||||
@@ -30,6 +31,11 @@ class SettingsPatch(BaseModel):
|
||||
tz: str | None = None
|
||||
|
||||
|
||||
class QuotaOut(BaseModel):
|
||||
used_bytes: int
|
||||
quota_bytes: int
|
||||
|
||||
|
||||
def allowed_image_senders(user: User) -> set[str]:
|
||||
value = user.settings.get("allowed_image_senders", [])
|
||||
if isinstance(value, list):
|
||||
@@ -59,6 +65,15 @@ async def get_settings_endpoint(user: CurrentUser) -> SettingsOut:
|
||||
return _settings_out(user)
|
||||
|
||||
|
||||
@router.get("/quota", response_model=QuotaOut)
|
||||
async def get_quota(user: CurrentUser, db: DbSession) -> QuotaOut:
|
||||
"""Storage quota and current usage (sum of stored message sizes)."""
|
||||
used = await db.scalar(
|
||||
select(func.coalesce(func.sum(Message.size_bytes), 0)).where(Message.user_id == user.id)
|
||||
)
|
||||
return QuotaOut(used_bytes=int(used or 0), quota_bytes=user.quota_bytes)
|
||||
|
||||
|
||||
@router.patch("", response_model=SettingsOut, dependencies=[Depends(require_csrf)])
|
||||
async def patch_settings(body: SettingsPatch, user: CurrentUser, db: DbSession) -> SettingsOut:
|
||||
updates = dict(user.settings)
|
||||
|
||||
@@ -56,6 +56,7 @@ def _envelope(msg: Message) -> MessageEnvelope:
|
||||
from_addr=_addresses(msg.from_addr),
|
||||
to_addr=_addresses(msg.to_addr),
|
||||
cc_addr=_addresses(msg.cc_addr),
|
||||
bcc_addr=_addresses(msg.bcc_addr),
|
||||
date=msg.date_hdr or msg.internal_date,
|
||||
flags=list(msg.flags),
|
||||
is_unread="\\Seen" not in msg.flags,
|
||||
|
||||
Reference in New Issue
Block a user