SPB Git

Repository Public

composer.ts 75.0 KB 1,468 lines typescript

1// Rédaction : plusieurs brouillons ouverts (copie locale d'abord, enregistrement serveur espacé et sans doublon), pièces jointes2// et images en ligne, signatures, envoi par l'API (annulation, envoi différé, rappel), suivi de la remise par destinataire.3import DOMPurify from "dompurify"4import { addMessages, fmtDateTime, fmtFullDate, t } from "../i18n"5import { enCompose } from "../i18n/en.compose"6import { frCompose } from "../i18n/fr.compose"7import { assertSet } from "../jmap/client"8import { HttpError, JmapMethodError, JmapSetError, errorDetail, errorKind } from "../jmap/errors"9import { api, request } from "../jmap/http"10import { BODY_PROPS, FULL_PROPS, KW, type DeliveryStatus, type EmailCreate, type EmailFull, type Id, type Identity } from "../jmap/types"11import { isValidEmail, sameEmail, type Addr } from "../mail/address"12import { MAX_UPLOAD_BYTES } from "../mail/attachments"13import {14  COMPOSE_IMAGE_ATTR, COMPOSE_IMAGE_TAGS, INLINE_IMAGE_TYPES, attachmentMentions, authoredHtmlText, authoredText, buildForwardQuote, buildReplyQuote, cleanCid, createAutosaver, defaultSignatureId, demoteSignature,15  externalRecipients, forwardSubject, htmlToText, keepKnownImages, matchSensitive, newCid, protectCids, pruneInline, recipientIssues, referencedCids, replyRecipients, replySubject, restoreCids, retagSignature, signatureEdited, stripZwsp,16  textToHtml, threadHeaders, wrapOutgoingBody, wrapOutgoingHtml, type Autosaver, type ReplyLabels,17} from "../mail/compose"18import { defaultSender, findSender, replySender, senderKey, swapSignatureHtml, swapSignatureText, type Sender } from "../mail/identities"19import { sanitizeEmailHtml } from "../mail/sanitize"20import { v1, type Outbound } from "../mail/v1"21import { D, loadComposeData, resetComposeData } from "../ui/compose/data"22import { S, dismissToast, folderByRole, toast, type Delivery, type Draft, type DraftAttachment } from "./app"23import { clientFor, ensureRoleFolder, hasClient, refreshList } from "./mail"24import { isFinalOutbound, pollOutbound } from "./outbound"25import { addressesSettled, loadAddresses, ownAddresses, senderGroups } from "./senders"26import { createStore } from "./store"2728addMessages("fr", frCompose)29addMessages("en", enCompose)3031// ---------------------------------------------------------------- modèle32export interface ComposeAttachment extends DraftAttachment {33  /** image affichée dans le texte : partie « inline » référencée par `cid:` */34  inline?: boolean35  cid?: string | null36  /** fichier déjà remis à l'API pour l'envoi (réutilisé d'un essai à l'autre tant qu'il n'a pas expiré) */37  fileId?: string | null38  fileMb?: string | null39  fileExp?: number | null40}41/** Signature choisie : `sender` = celle de l'adresse (historique), `none`, ou l'identifiant d'une signature de l'utilisateur. */42export type SignatureChoice = "sender" | "none" | (string & {})43export interface ComposeDraft extends Draft {44  attachments: ComposeAttachment[]45  signatureId?: SignatureChoice46  /** réponse ou transfert (choix de la signature « des réponses ») */47  reply?: boolean48  /** change à chaque annulation d'envoi : un nouvel envoi du même texte n'est pas pris pour une répétition */49  sendSeq?: number50  /** fenêtre élargie (pleine largeur) */51  wide?: boolean52}53/** Envoi retenu par le serveur pendant la fenêtre d'annulation. */54export interface HeldSend {55  id: string56  subject: string57  until: number58}59interface ComposerState {60  drafts: ComposeDraft[]61  held: HeldSend[]62  /** change quand une image en ligne devient affichable : les éditeurs relisent leurs adresses */63  inlineRev: number64}65export const C = createStore<ComposerState>({ drafts: [], held: [], inlineRev: 0 })66export const MAX_OPEN_DRAFTS = 66768const LOCAL_KEY = "spmail.draft"69const LOCAL_MORE = "spmail.drafts"70let seq = 071const newKey = () => `${Date.now().toString(36)}-${(++seq).toString(36)}`72const parse = (html: string) => new DOMParser().parseFromString(html, "text/html")7374const upgrade = (d: Draft): ComposeDraft => d as ComposeDraft75const find = (key: string | undefined | null): ComposeDraft | undefined => (key ? C.get().drafts.find((d) => d.key === key) : undefined)76/** Brouillon affiché (non réduit) ; à défaut aucun. */77export const activeDraft = (): ComposeDraft | undefined => C.get().drafts.find((d) => !d.minimized)78const target = (key?: string): ComposeDraft | undefined => (key ? find(key) : (activeDraft() ?? upgrade(S.get().draft as Draft) ?? undefined))7980// ---------------------------------------------------------------- miroir vers l'état commun et copie locale81/**82 * `S.draft` reste la vue qu'ont les autres modules (indicateur de synchronisation, écran de connexion, boîte retirée) :83 * le brouillon affiché, sinon le premier qui attend un enregistrement, sinon le dernier ouvert.84 */85let mirroring = false86function mirror() {87  const { drafts } = C.get()88  const pick = drafts.find((d) => !d.minimized) ?? drafts.find((d) => d.save === "dirty" || d.save === "error") ?? drafts[drafts.length - 1] ?? null89  mirroring = true90  try {91    S.set({ draft: pick })92  } finally {93    mirroring = false94  }95}96/** Un autre module a posé ou retiré `S.draft` (déconnexion, essais) : la liste des brouillons suit. */97function reconcile() {98  if (mirroring) return99  const ext = S.get().draft100  const { drafts } = C.get()101  if (!ext) {102    if (!drafts.length) return103    for (const d of drafts) dropController(d.key)104    C.set({ drafts: [] })105    return106  }107  if (drafts.some((d) => d.key === ext.key)) return108  C.set({ drafts: [...drafts.map((d) => (ext.minimized ? d : { ...d, minimized: true })), upgrade(ext)] })109  if (ext.save === "dirty" || ext.save === "error") controller(ext.key).auto.touch()110}111S.subscribe(reconcile)112113function setDrafts(next: ComposeDraft[]) {114  C.set({ drafts: next })115  mirror()116}117function patchDraft(key: string, patch: Partial<ComposeDraft>): ComposeDraft | undefined {118  const cur = find(key)119  if (!cur) return undefined120  const next = { ...cur, ...patch }121  setDrafts(C.get().drafts.map((d) => (d.key === key ? next : d)))122  return next123}124125/** Efface toutes les copies locales (déconnexion). */126export function clearLocalDraft() {127  try {128    localStorage.removeItem(LOCAL_KEY)129    localStorage.removeItem(LOCAL_MORE)130  } catch {131    /* stockage indisponible */132  }133}134const isPristine = (d: ComposeDraft) => d.save === "clean" && !d.draftEmailId && !d.to.length && !d.cc.length && !d.bcc.length && !d.subject.trim() && !d.attachments.length && d.rev === 0135const forStorage = (d: ComposeDraft): ComposeDraft => ({ ...d, attachments: d.attachments.filter((a) => a.blobId), send: "idle", sendError: null, save: d.save === "saving" ? "dirty" : d.save })136let persistTimer: ReturnType<typeof setTimeout> | undefined137function writeLocal() {138  const primary = S.get().draft as ComposeDraft | null139  const others = C.get().drafts.filter((d) => d.key !== primary?.key && !isPristine(d))140  try {141    if (!primary || !find(primary.key)) localStorage.removeItem(LOCAL_KEY)142    else {143      const json = JSON.stringify(forStorage(primary))144      if (json.length < 1_500_000) localStorage.setItem(LOCAL_KEY, json)145    }146    if (!others.length) localStorage.removeItem(LOCAL_MORE)147    else {148      // chaque brouillon est borné séparément : un seul trop gros ne prive pas les autres de leur copie149      const kept = others.map((d) => JSON.stringify(forStorage(d))).filter((j) => j.length < 1_500_000)150      localStorage.setItem(LOCAL_MORE, `[${kept.join(",")}]`)151    }152  } catch {153    /* quota dépassé : le brouillon du serveur reste la référence */154  }155}156/** `now` : écriture immédiate (après un enregistrement sur le serveur, pour qu'un rechargement connaisse l'identifiant du brouillon). */157function persistLocal(now = false) {158  clearTimeout(persistTimer)159  if (now) writeLocal()160  else persistTimer = setTimeout(writeLocal, 250)161}162/** Au démarrage (ou après reconnexion) : reprend les rédactions là où elles en étaient. */163export function restoreLocalDraft() {164  reconcile()165  if (C.get().drafts.length) return166  try {167    const raw = localStorage.getItem(LOCAL_KEY)168    const more = localStorage.getItem(LOCAL_MORE)169    const list: ComposeDraft[] = []170    for (const d of [...(more ? (JSON.parse(more) as ComposeDraft[]) : []), ...(raw ? [JSON.parse(raw) as ComposeDraft] : [])]) {171      if (!d || typeof d.key !== "string" || !S.get().me?.mailboxes.some((m) => m.id === d.mb) || list.some((x) => x.key === d.key)) continue172      list.push({ ...d, send: "idle", sendError: null, rev: (d.rev ?? 0) + 1 })173    }174    if (!list.length) return clearLocalDraft()175    // une seule rédaction ouverte à la fois : la dernière non réduite176    const open = [...list].reverse().find((d) => !d.minimized)177    setDrafts(list.map((d) => (d === open ? d : { ...d, minimized: true })))178    for (const d of list) if (d.save === "dirty" || d.save === "error") controller(d.key).auto.touch()179  } catch {180    clearLocalDraft()181  }182}183184// ---------------------------------------------------------------- éditeurs montés185export interface EditorHandle {186  /** recopie tout de suite le contenu de l'éditeur dans le brouillon */187  flush(): void188  insertHtml(html: string): void189  insertText(text: string): void190  getText(): string191  focus(): void192}193const editors = new Map<string, EditorHandle>()194/** L'éditeur d'un brouillon s'inscrit ici (rend la fonction de retrait). */195export function registerEditor(key: string, handle: EditorHandle): () => void {196  editors.set(key, handle)197  return () => {198    if (editors.get(key) === handle) editors.delete(key)199  }200}201const flushEditor = (key: string) => editors.get(key)?.flush()202203// ---------------------------------------------------------------- expéditeurs et signatures204function identityOf(d: Pick<Draft, "mb" | "identityId">): Identity | undefined {205  return S.get().accounts[d.mb]?.identities.find((i) => i.id === d.identityId)206}207/** Expéditeur d'un brouillon : l'adresse choisie (boîte ou alias) ; à défaut celle de son identité JMAP. */208export function senderOf(d: Pick<Draft, "mb" | "identityId" | "from">): Sender | undefined {209  const groups = senderGroups()210  const email = d.from ?? identityOf(d)?.email211  return (email ? findSender(groups, senderKey(d.mb, email)) : undefined) ?? (d.from ? undefined : groups.find((g) => g.mb === d.mb)?.senders.find((x) => x.identityId === d.identityId))212}213/** Ligne d'adresse de l'API pour un expéditeur (null : identité JMAP seule, ou API injoignable). */214function addressRow(sender: Sender | undefined) {215  return sender ? ((S.get().addresses ?? []).find((a) => a.mailbox_id === sender.mb && sameEmail(a.address, sender.email)) ?? null) : null216}217const wrapSignature = (html: string) => (html ? `<div class="spm-signature">${html}</div>` : "")218function legacySignatureHtml(i: Sender | undefined): string {219  if (!i) return ""220  return i.signatureHtml.trim() ? sanitizeComposerHtml(sanitizeEmailHtml(i.signatureHtml, { mode: "quote" }).body) : i.signatureText.trim() ? textToHtml(i.signatureText.trim()) : ""221}222const legacySignatureText = (i: Sender | undefined): string => i?.signatureText.trim() || (i?.signatureHtml.trim() ? htmlToText(i.signatureHtml) : "")223/** Bloc HTML (enveloppé) et texte brut de la signature choisie pour cet expéditeur. */224export function signatureContent(sender: Sender | undefined, choice: SignatureChoice | undefined): { html: string; text: string } {225  if (choice === "none") return { html: "", text: "" }226  if (choice && choice !== "sender") {227    const sig = D.get().signatures.find((s) => s.id === choice)228    if (sig) {229      const html = sig.html.trim() ? sanitizeComposerHtml(sanitizeEmailHtml(sig.html, { mode: "quote" }).body) : sig.text.trim() ? textToHtml(sig.text.trim()) : ""230      return { html: wrapSignature(html), text: sig.text.trim() || htmlToText(html) }231    }232  }233  return { html: wrapSignature(legacySignatureHtml(sender)), text: legacySignatureText(sender) }234}235/** Signature par défaut d'un expéditeur : celle qui revendique son adresse, sinon la signature historique de l'adresse. */236export function defaultSignature(sender: Sender | undefined, reply: boolean): SignatureChoice {237  return defaultSignatureId(D.get().signatures, addressRow(sender)?.id, reply) ?? "sender"238}239const textBlock = (sig: string) => (sig ? `-- \n${sig}` : "")240241function labels(): ReplyLabels {242  return { wrote: (date, who) => t("compose.wrote", { date, who }), forwardedHeader: t("compose.forwardedMessage"), from: t("compose.fromLabel"), date: t("compose.dateLabel"), subject: t("compose.subjectLabel"), to: t("compose.toLabel"), cc: t("compose.ccLabel") }243}244245// données de rédaction : lues dès que la session est prête, oubliées à la déconnexion246let dataFor: string | null = null247S.subscribe(() => {248  const s = S.get()249  const user = s.phase === "ready" ? (s.me?.user.id ?? null) : null250  if (user === dataFor) return251  dataFor = user252  if (!user) return resetComposeData()253  void loadComposeData(true).then(applyLateSignatures)254})255/**256 * Les signatures arrivent parfois après l'ouverture d'un message : un brouillon dont la signature est encore celle posée257 * par défaut (jamais choisie à la main, bloc intact) reçoit alors la signature par défaut de son adresse.258 */259function applyLateSignatures() {260  for (const d of C.get().drafts) {261    if (d.signatureId !== undefined && d.signatureId !== "sender") continue262    const sender = senderOf(d)263    const want = defaultSignature(sender, !!d.reply)264    if (want === "sender") continue265    setDraftSignature(want, d.key, false)266  }267}268269// ---------------------------------------------------------------- ouverture270function baseDraft(mb: string, sender: Sender | undefined): ComposeDraft {271  return {272    key: newKey(), mb, identityId: sender?.identityId ?? null, from: sender?.email ?? null, to: [], cc: [], bcc: [], showCc: false, subject: "", mode: "html", html: "", text: "", attachments: [], inReplyTo: null, references: null,273    related: null, draftEmailId: null, save: "clean", savedAt: null, send: "idle", sendError: null, minimized: false, rev: 0, signatureId: "sender", reply: false, sendSeq: 0, wide: false,274  }275}276/** Ouvre un brouillon de plus (les autres sont réduits) ; un message vide et intact déjà affiché est simplement remplacé. */277function present(d: ComposeDraft): boolean {278  reconcile()279  const cur = C.get().drafts280  const reusable = cur.find((x) => !x.minimized && isPristine(x) && htmlToText(x.html).trim() === htmlToText(signatureContent(senderOf(x), x.signatureId).html).trim())281  const rest = cur.filter((x) => x.key !== reusable?.key)282  if (reusable) dropController(reusable.key)283  if (rest.length >= MAX_OPEN_DRAFTS) {284    toast({ kind: "info", text: t("cmp.tooManyDrafts", { n: MAX_OPEN_DRAFTS }) })285    return false286  }287  for (const x of rest) if (!x.minimized) minimizeDraft(x.key)288  setDrafts([...C.get().drafts.filter((x) => x.key !== reusable?.key).map((x) => (x.minimized ? x : { ...x, minimized: true })), { ...d, minimized: false }])289  persistLocal()290  // signatures, extraits et préférences d'envoi ont pu changer sur un autre appareil : relus à chaque ouverture291  if (S.get().phase === "ready" && S.get().online) void loadComposeData(true).then(applyLateSignatures)292  return true293}294295export function composeNew(init: Partial<Pick<Draft, "to" | "cc" | "bcc" | "subject">> = {}): string | null {296  const s = S.get()297  const mb = s.mb ?? s.me?.mailboxes[0]?.id298  if (!mb) return null299  void loadAddresses(60_000)300  const sender = defaultSender(senderGroups(), mb)301  const d = baseDraft(sender?.mb ?? mb, sender)302  d.signatureId = defaultSignature(sender, false)303  const sig = signatureContent(sender, d.signatureId)304  d.html = sig.html ? `<div><br></div><div><br></div>${sig.html}` : ""305  d.text = sig.text ? `\n\n${textBlock(sig.text)}` : ""306  Object.assign(d, init)307  if (d.cc.length || d.bcc.length) d.showCc = true308  return present(d) ? d.key : null309}310311function bodyOf(e: EmailFull): { html: string | null; text: string } {312  const htmlPart = e.htmlBody.find((p) => p.type === "text/html" && p.partId && e.bodyValues[p.partId])313  const textPart = e.textBody.find((p) => p.type === "text/plain" && p.partId && e.bodyValues[p.partId])314  const html = htmlPart?.partId ? e.bodyValues[htmlPart.partId].value : null315  const text = textPart?.partId ? e.bodyValues[textPart.partId].value : html ? htmlToText(html) : ""316  return { html, text }317}318/** HTML d'un message cité, assaini ; ses images `cid:` sont gardées (elles seront rejointes comme parties en ligne). */319function quotedHtml(html: string): string {320  return restoreCids(sanitizeEmailHtml(protectCids(html, parse), { mode: "quote" }).body, parse)321}322/** Parties d'un message d'origine reprises telles quelles : pièces jointes (transfert, brouillon) et images référencées par `cid:`. */323function inheritedParts(e: EmailFull, html: string | null, withFiles: boolean): ComposeAttachment[] {324  const used = new Set(html ? referencedCids(html) : [])325  const out: ComposeAttachment[] = []326  for (const p of e.attachments) {327    if (!p.blobId) continue328    const cid = cleanCid(p.cid)329    const inline = !!cid && used.has(cid) && INLINE_IMAGE_TYPES.test(p.type)330    if (!inline && (!withFiles || (p.disposition === "inline" && !!p.cid && !p.name))) continue331    out.push({ key: newKey(), name: p.name ?? (inline ? "image" : "fichier"), type: p.type, size: p.size, blobId: p.blobId, progress: 1, error: null, inherited: true, ...(inline ? { inline: true, cid } : {}) })332  }333  return out334}335336export function composeReply(e: EmailFull, kind: "reply" | "replyAll" | "forward", extra: { html?: string; text?: string } = {}): string | null {337  const mb = S.get().mb338  if (!mb) return null339  // « moi » = cette boîte seulement : une autre de mes boîtes (info@ ↔ contact@) est un correspondant comme un autre340  const st = S.get()341  const own = st.me?.mailboxes.find((m) => m.id === mb)?.address342  const groups = senderGroups()343  const mine = [...(own ? [own] : []), ...(st.accounts[mb]?.identities ?? []).map((i) => i.email), ...(groups.find((g) => g.mb === mb)?.senders ?? []).map((x) => x.email)]344  // l'adresse — boîte ou alias — à laquelle le message a été remis : destinataire d'enveloppe d'abord, puis À et Cc345  const envelope = (e.headers ?? []).filter((h) => h.name.toLowerCase() === "delivered-to").map((h) => h.value.trim().replace(/^<|>$/g, ""))346  const delivered = [...envelope, ...[...(e.to ?? []), ...(e.cc ?? [])].map((a) => a.email)]347  const sender = replySender(groups, mb, delivered)348  const d = baseDraft(mb, sender)349  d.reply = true350  d.signatureId = defaultSignature(sender, true)351  const { html, text } = bodyOf(e)352  const quoted = html ? quotedHtml(html) : null353  const date = fmtFullDate(e.sentAt ?? e.receivedAt)354  const signature = signatureContent(sender, d.signatureId)355  const sig = signature.html356  const sigText = textBlock(signature.text)357  const lead = extra.html ? sanitizeComposerHtml(extra.html) : extra.text ? textToHtml(extra.text) : "<div><br></div>"358  const leadText = extra.text ?? (extra.html ? htmlToText(extra.html) : "")359  if (kind === "forward") {360    const q = buildForwardQuote(e, quoted, text, date, labels())361    d.subject = forwardSubject(e.subject)362    d.html = `${lead}${sig}${q.html}`363    d.text = `${leadText}${sigText ? `\n\n${sigText}` : ""}${q.text}`364    d.related = { emailId: e.id, kind: "forward" }365    // un transfert conserve les pièces jointes d'origine et les images du texte366    d.attachments = inheritedParts(e, quoted, true)367  } else {368    const r = replyRecipients(e, mine, kind === "replyAll")369    const q = buildReplyQuote(e, quoted, text, date, labels())370    d.to = r.to.map((a) => ({ name: a.name ?? undefined, email: a.email }))371    d.cc = r.cc.map((a) => ({ name: a.name ?? undefined, email: a.email }))372    d.showCc = d.cc.length > 0373    d.subject = replySubject(e.subject)374    const th = threadHeaders(e)375    d.inReplyTo = th.inReplyTo376    d.references = th.references377    d.html = `${lead}${sig}${q.html}`378    d.text = `${leadText}${sigText ? `\n\n${sigText}` : ""}${q.text}`379    d.related = { emailId: e.id, kind: "reply" }380    // la citation garde ses images : elles repartent en ligne tant que la citation reste dans le message381    d.attachments = inheritedParts(e, quoted, false)382  }383  d.save = "dirty"384  if (!present(d)) return null385  controller(d.key).auto.touch()386  return d.key387}388389/** Rouvre un brouillon enregistré sur le serveur. */390export async function composeFromDraft(emailId: Id) {391  const mb = S.get().mb392  if (!mb) return393  reconcile()394  const open = C.get().drafts.find((d) => d.draftEmailId === emailId && d.mb === mb)395  if (open) return activateDraft(open.key)396  try {397    const r = await clientFor(mb).call("Email/get", { ids: [emailId], properties: FULL_PROPS, bodyProperties: BODY_PROPS, fetchHTMLBodyValues: true, fetchTextBodyValues: true, maxBodyValueBytes: 2_000_000 })398    const e = r.list[0]399    if (!e) throw new JmapMethodError("Email/get", "notFound")400    const sender = replySender(senderGroups(), mb, (e.from ?? []).map((a) => a.email))401    const d = baseDraft(mb, sender)402    const { html, text } = bodyOf(e)403    const norm = (l: EmailFull["to"]): Addr[] => (l ?? []).map((a) => ({ name: a.name ?? undefined, email: a.email }))404    const attachments = inheritedParts(e, html ? quotedHtml(html) : null, true)405    const known = new Set(attachments.filter((a) => a.inline && a.cid).map((a) => a.cid!))406    d.reply = !!e.inReplyTo?.length407    d.signatureId = defaultSignature(sender, d.reply)408    let body = html ? sanitizeComposerHtml(quotedHtml(html), known) : textToHtml(text)409    // les classes n'ont pas survécu à l'enregistrement : la signature est retrouvée par son texte410    const sig = signatureContent(sender, d.signatureId).html411    if (html && sig) body = retagSignature(body, sig, parse)412    Object.assign(d, {413      to: norm(e.to), cc: norm(e.cc), bcc: norm(e.bcc), showCc: !!(e.cc?.length || e.bcc?.length), subject: e.subject ?? "", mode: html ? "html" : "text",414      html: body, text, inReplyTo: e.inReplyTo, references: e.references, draftEmailId: e.id, save: "saved", savedAt: Date.now(), attachments,415    } satisfies Partial<ComposeDraft>)416    if (present(d)) controller(d.key).print = fingerprint(d)417  } catch (e) {418    toast({ kind: "error", text: t("compose.openDraftFailed"), detail: errorDetail(e) || undefined })419  }420}421422// ---------------------------------------------------------------- fenêtres423/** Affiche ce brouillon ; celui qui était affiché est réduit (et enregistré). */424export function activateDraft(key: string) {425  reconcile()426  if (!find(key)) return427  for (const d of C.get().drafts) if (d.key !== key && !d.minimized) minimizeDraft(d.key)428  patchDraft(key, { minimized: false })429  persistLocal()430}431/** Réduit sans rien fermer ni abandonner (Échap, bouton « Réduire ») ; les modifications partent vers le serveur. */432export function minimizeDraft(key?: string) {433  const d = target(key)434  if (!d) return435  flushEditor(d.key)436  patchDraft(d.key, { minimized: true })437  persistLocal(true)438  const cur = find(d.key)439  if (cur && (cur.save === "dirty" || cur.save === "error")) void saveDraft(cur.key)440}441export function setDraftWide(wide: boolean, key?: string) {442  const d = target(key)443  if (d) patchDraft(d.key, { wide })444}445446// ---------------------------------------------------------------- édition447export function updateDraft(patch: Partial<ComposeDraft>, dirty = true, key?: string) {448  reconcile()449  const d = target(key)450  if (!d) return451  if (patch.minimized === false) return activateDraft(d.key)452  if (patch.minimized === true) return minimizeDraft(d.key)453  patchDraft(d.key, { ...patch, ...(dirty ? { save: "dirty" as const } : {}) })454  persistLocal()455  if (dirty) controller(d.key).auto.touch()456}457458/** Remplace le bloc de signature du brouillon par la signature choisie (jamais doublée ; un bloc réécrit à la main est gardé). */459export function setDraftSignature(choice: SignatureChoice, key?: string, dirty = true) {460  const d = target(key)461  if (!d) return462  flushEditor(d.key)463  const cur = find(d.key)!464  const sender = senderOf(cur)465  const prev = signatureContent(sender, cur.signatureId)466  const next = signatureContent(sender, choice)467  // choix fait à la main : la nouvelle signature est posée même si l'ancien bloc a été réécrit (il est alors gardé, au-dessus)468  const html = swapSignatureHtml(cur.html, next.html, parse, prev.html)469  const text = swapSignatureText(cur.text, prev.text, next.text)470  if (!dirty) {471    // pose automatique (signatures arrivées après l'ouverture) : jamais si la personne a touché au bloc472    if (signatureEdited(cur.html, prev.html, parse)) return473474    patchDraft(cur.key, { signatureId: choice, html, text, rev: cur.rev + 1 })475    return persistLocal()476  }477  updateDraft({ signatureId: choice, html, text, rev: cur.rev + 1 }, true, cur.key)478}479480/**481 * Change d'expéditeur (boîte ou alias) : le bloc de signature est remplacé par celui de la nouvelle adresse — jamais482 * dupliqué, le texte tapé est conservé ; si la boîte change, les pièces jointes y sont recopiées.483 */484export async function setDraftSender(senderKeyValue: string, key?: string) {485  const d0 = target(key)486  const next = findSender(senderGroups(), senderKeyValue)487  if (!d0 || !next) return488  flushEditor(d0.key)489  const d = find(d0.key)!490  const prev = senderOf(d)491  if (prev?.key === next.key) return492  const mb = next.mb493  const identityId = next.identityId494  const before = signatureContent(prev, d.signatureId)495  // signature réécrite ou retirée par la personne : elle n'est ni remplacée ni doublée — c'est désormais son texte, et le496  // brouillon n'a plus de signature automatique (les changements d'expéditeur suivants n'en ajoutent pas non plus)497  const edited = d.signatureId !== "none" && (d.mode === "text" ? !!before.text && !d.text.includes(before.text) : signatureEdited(d.html, before.html, parse))498  // « aucune signature » choisie à la main reste le choix ; sinon la signature par défaut de la nouvelle adresse499  const choice: SignatureChoice = d.signatureId === "none" || edited ? "none" : defaultSignature(next, !!d.reply)500  const after = signatureContent(next, choice)501  const html = edited ? demoteSignature(d.html, parse) : swapSignatureHtml(d.html, after.html, parse, before.html)502  const text = edited ? d.text : swapSignatureText(d.text, before.text, after.text)503  if (mb === d.mb) return updateDraft({ identityId, from: next.email, html, text, signatureId: choice, rev: d.rev + 1 }, true, d.key)504  // autre boîte : les blobs appartiennent au compte d'origine → copie par téléchargement / téléversement505  const from = clientFor(d.mb)506  const to = clientFor(mb)507  const oldDraftId = d.draftEmailId508  const oldMb = d.mb509  controller(d.key).print = null510  updateDraft({ mb, identityId, from: next.email, html, text, signatureId: choice, rev: d.rev + 1, draftEmailId: null, attachments: d.attachments.map((a) => ({ ...a, progress: a.blobId ? 0 : a.progress, inherited: false, fileId: null })) }, true, d.key)511  for (const a of d.attachments) {512    if (!a.blobId) continue513    try {514      const bytes = localBlobs.get(a.key) ?? new Blob([(await from.downloadBytes(a.blobId, a.type)) as BlobPart], { type: a.type })515      const up = await to.upload(bytes, a.type, (l, tot) => patchAttachment(d.key, a.key, { progress: tot ? l / tot : 0 }))516      patchAttachment(d.key, a.key, { blobId: up.blobId, progress: 1 })517    } catch (e) {518      patchAttachment(d.key, a.key, { blobId: null, error: errorDetail(e) || t("compose.uploadFailed") })519    }520  }521  if (oldDraftId) void clientFor(oldMb).call("Email/set", { destroy: [oldDraftId] }).catch(() => {})522  controller(d.key).auto.touch()523}524525// ---------------------------------------------------------------- pièces jointes526const uploads = new Map<string, AbortController>()527/** Octets encore en mémoire des fichiers ajoutés pendant cette visite (aperçu immédiat, envoi sans retéléchargement). */528const localBlobs = new Map<string, Blob>()529const localUrls = new Map<string, string>()530function forget(att: ComposeAttachment) {531  uploads.get(att.key)?.abort()532  localBlobs.delete(att.key)533  const url = localUrls.get(att.key)534  if (url) {535    // l'éditeur peut encore afficher l'image le temps d'un « annuler » : l'adresse est libérée plus tard536    setTimeout(() => URL.revokeObjectURL(url), 60_000)537    localUrls.delete(att.key)538  }539}540function patchAttachment(key: string, attKey: string, patch: Partial<ComposeAttachment>) {541  const d = find(key)542  if (!d || !d.attachments.some((a) => a.key === attKey)) return543  const done = patch.blobId !== undefined544  patchDraft(key, { attachments: d.attachments.map((a) => (a.key === attKey ? { ...a, ...patch } : a)), ...(done ? { save: "dirty" as const } : {}) })545  if (done) {546    persistLocal()547    controller(key).auto.touch()548  }549}550/** Poids des pièces jointes (les images en ligne comptent : elles voyagent dans le même message). */551export const attachmentsTotal = (d: Draft) => d.attachments.reduce((n, a) => n + a.size, 0)552553/** Adresse affichable d'une pièce (aperçu d'image, image en ligne) : le fichier local, sinon le blob par la passerelle. */554export function attachmentUrl(d: Pick<Draft, "mb">, a: ComposeAttachment): string | undefined {555  if (!INLINE_IMAGE_TYPES.test(a.type)) return undefined556  const local = localUrls.get(a.key)557  if (local) return local558  return a.blobId && hasClient(d.mb) ? clientFor(d.mb).downloadUrl(a.blobId, a.name, a.type, true) : undefined559}560/** Adresse d'une image en ligne d'après son Content-ID. */561export function inlineUrl(key: string, cid: string): string | undefined {562  const d = find(key)563  const a = d?.attachments.find((x) => x.inline && x.cid === cid)564  return d && a ? attachmentUrl(d, a) : undefined565}566567export interface AddedFile {568  key: string569  cid: string | null570  url: string | undefined571}572/** Ajoute des fichiers (téléversés une fois dans la boîte du brouillon). `inline` : images affichées dans le texte, référencées par `cid:`. */573export function addFiles(files: (File | Blob)[], key?: string, opts: { inline?: boolean; names?: string[] } = {}): AddedFile[] {574  const d = target(key)575  if (!d || !files.length) return []576  let total = attachmentsTotal(d)577  const added: ComposeAttachment[] = []578  const out: AddedFile[] = []579  const toUpload: { att: ComposeAttachment; file: Blob }[] = []580  files.forEach((f, i) => {581    const name = opts.names?.[i] || (f as File).name || "fichier"582    if (f.size > MAX_UPLOAD_BYTES || total + f.size > MAX_UPLOAD_BYTES) {583      toast({ kind: "error", text: t("compose.tooLarge", { name }) })584      return585    }586    total += f.size587    const type = f.type || "application/octet-stream"588    const inline = !!opts.inline && INLINE_IMAGE_TYPES.test(type)589    const att: ComposeAttachment = { key: newKey(), name, type, size: f.size, blobId: null, progress: 0, error: null, ...(inline ? { inline: true, cid: newCid() } : {}) }590    localBlobs.set(att.key, f)591    if (INLINE_IMAGE_TYPES.test(type) && typeof URL !== "undefined" && typeof URL.createObjectURL === "function") localUrls.set(att.key, URL.createObjectURL(f))592    added.push(att)593    toUpload.push({ att, file: f })594    out.push({ key: att.key, cid: att.cid ?? null, url: localUrls.get(att.key) })595  })596  if (!added.length) return []597  patchDraft(d.key, { attachments: [...d.attachments, ...added] })598  for (const { att, file } of toUpload) {599    const ctrl = new AbortController()600    uploads.set(att.key, ctrl)601    clientFor(d.mb)602      .upload(file, att.type, (l, tot) => patchAttachment(d.key, att.key, { progress: tot ? Math.min(0.99, l / tot) : 0 }), ctrl.signal)603      .then((r) => patchAttachment(d.key, att.key, { blobId: r.blobId, progress: 1, size: r.size }))604      .catch((e: unknown) => {605        if (e instanceof DOMException && e.name === "AbortError") return606        patchAttachment(d.key, att.key, { error: errorKind(e) === "tooLarge" ? t("compose.tooLarge", { name: att.name }) : errorDetail(e) || t("compose.uploadFailed") })607      })608      .finally(() => uploads.delete(att.key))609  }610  return out611}612export function removeAttachment(attKey: string, key?: string) {613  const d = target(key)614  const att = d?.attachments.find((a) => a.key === attKey)615  if (!d || !att) return616  forget(att)617  updateDraft({ attachments: d.attachments.filter((a) => a.key !== attKey) }, true, d.key)618}619/** Déplace une pièce jointe dans la liste (glisser-déposer, clavier). */620export function moveAttachment(attKey: string, toIndex: number, key?: string) {621  const d = target(key)622  if (!d) return623  const from = d.attachments.findIndex((a) => a.key === attKey)624  if (from < 0) return625  const list = [...d.attachments]626  const [item] = list.splice(from, 1)627  list.splice(Math.max(0, Math.min(list.length, toIndex)), 0, item)628  if (list.every((a, i) => a === d.attachments[i])) return629  updateDraft({ attachments: list }, true, d.key)630}631export interface ExistingAttachment {632  /** boîte SP Mail (identifiant `/api/me`) qui détient le blob */633  mailboxId: string634  blobId: string635  name: string636  type: string637  size: number638}639/**640 * Joint au brouillon affiché (ou à un nouveau message) un fichier déjà présent sur le serveur — galerie des pièces jointes —641 * sans le téléverser de nouveau : le blob est référencé tel quel. Seul un blob d'une autre boîte que celle du brouillon est recopié.642 */643export async function addExistingAttachment(file: ExistingAttachment, key?: string): Promise<boolean> {644  reconcile()645  let d = target(key)646  if (!d) {647    const opened = composeNew()648    d = opened ? find(opened) : undefined649  }650  if (!d) return false651  if (d.minimized) activateDraft(d.key)652  if (attachmentsTotal(d) + file.size > MAX_UPLOAD_BYTES) {653    toast({ kind: "error", text: t("compose.tooLarge", { name: file.name }) })654    return false655  }656  const att: ComposeAttachment = { key: newKey(), name: file.name || "fichier", type: file.type || "application/octet-stream", size: file.size, blobId: file.mailboxId === d.mb ? file.blobId : null, progress: file.mailboxId === d.mb ? 1 : 0, error: null, inherited: true }657  const draftKey = d.key658  if (file.mailboxId === d.mb) {659    updateDraft({ attachments: [...d.attachments, att] }, true, draftKey)660    return true661  }662  patchDraft(draftKey, { attachments: [...d.attachments, att] })663  try {664    const bytes = await clientFor(file.mailboxId).downloadBytes(file.blobId, att.type)665    const up = await clientFor(find(draftKey)?.mb ?? d.mb).upload(new Blob([bytes as BlobPart], { type: att.type }), att.type, (l, tot) => patchAttachment(draftKey, att.key, { progress: tot ? Math.min(0.99, l / tot) : 0 }))666    patchAttachment(draftKey, att.key, { blobId: up.blobId, progress: 1 })667    return true668  } catch (e) {669    patchAttachment(draftKey, att.key, { error: errorDetail(e) || t("compose.uploadFailed") })670    return false671  }672}673674// ---------------------------------------------------------------- construction du message675/**676 * Le HTML rédigé (ou collé) repasse par une liste blanche avant d'être enregistré ou envoyé. Les images ne sont gardées677 * que si leur source est le `cid:` d'une image en ligne de ce brouillon (`cids`) : jamais d'adresse distante, `data:` ni `blob:`.678 */679export function sanitizeComposerHtml(html: string, cids: ReadonlySet<string> = NO_CIDS, win?: Parameters<typeof DOMPurify>[0]): string {680  const root = (win ? DOMPurify(win) : DOMPurify).sanitize(stripZwsp(html), {681    ALLOWED_TAGS: COMPOSE_IMAGE_TAGS, ALLOWED_ATTR: COMPOSE_IMAGE_ATTR, ALLOW_DATA_ATTR: false, ALLOWED_URI_REGEXP: /^(?:https?:|mailto:|tel:|cid:)/i, RETURN_DOM: true,682  }) as unknown as HTMLElement683  keepKnownImages(root, cids)684  // `cid:` n'a de sens que pour une image685  for (const a of Array.from(root.querySelectorAll("a[href]"))) if (/^cid:/i.test(a.getAttribute("href") ?? "")) a.removeAttribute("href")686  return root.innerHTML687}688const NO_CIDS: ReadonlySet<string> = new Set()689const inlineCids = (d: ComposeDraft): Set<string> => new Set(d.attachments.filter((a) => a.inline && a.cid && !a.error).map((a) => a.cid!))690/** HTML du brouillon tel qu'il part : assaini, images limitées à celles du brouillon. */691const outgoingHtml = (d: ComposeDraft): string => sanitizeComposerHtml(d.html, inlineCids(d))692/** Pièces qui voyagent : téléversées, et — pour les images en ligne — encore référencées par le texte. */693const outgoingParts = (d: ComposeDraft, html: string | null): ComposeAttachment[] => pruneInline(d.attachments.filter((a) => a.blobId), html)694695function fromOf(d: ComposeDraft) {696  const ident = identityOf(d)697  const sender = senderOf(d)698  const address = S.get().me?.mailboxes.find((m) => m.id === d.mb)699  return sender ? [{ name: sender.name || null, email: sender.email }] : ident ? [{ name: ident.name || null, email: ident.email }] : address ? [{ name: address.display_name || null, email: address.address }] : []700}701function buildEmail(d: ComposeDraft, draftsId: Id): EmailCreate {702  const ident = identityOf(d)703  const norm = (l: Addr[]) => l.map((a) => ({ name: a.name?.trim() || null, email: a.email }))704  const html = d.mode === "html" ? outgoingHtml(d) : null705  const email: EmailCreate = {706    mailboxIds: { [draftsId]: true }, keywords: { [KW.draft]: true, [KW.seen]: true }, from: fromOf(d), to: norm(d.to), cc: norm(d.cc), bcc: norm(d.bcc), subject: d.subject,707    attachments: outgoingParts(d, html).map((a) => (a.inline && a.cid ? { blobId: a.blobId!, type: a.type, name: a.name, disposition: "inline" as const, cid: a.cid } : { blobId: a.blobId!, type: a.type, name: a.name, disposition: "attachment" as const })),708  }709  if (ident?.replyTo?.length) email.replyTo = ident.replyTo710  if (d.inReplyTo?.length) email.inReplyTo = d.inReplyTo711  if (d.references?.length) email.references = d.references712  if (html !== null) {713    email.bodyValues = { t: { value: htmlToText(html) }, h: { value: wrapOutgoingHtml(html) } }714    email.textBody = [{ partId: "t", type: "text/plain" }]715    email.htmlBody = [{ partId: "h", type: "text/html" }]716  } else {717    email.bodyValues = { t: { value: d.text } }718    email.textBody = [{ partId: "t", type: "text/plain" }]719  }720  return email721}722/** Empreinte du contenu enregistrable : deux brouillons de même empreinte donneraient le même message sur le serveur. */723function fingerprint(d: ComposeDraft): string {724  const e = buildEmail(d, "-")725  return JSON.stringify([d.mb, e.from, e.to, e.cc, e.bcc, e.subject, e.attachments, e.replyTo ?? null, e.inReplyTo ?? null, e.references ?? null, e.bodyValues])726}727728// ---------------------------------------------------------------- enregistrement automatique729interface Controller {730  auto: Autosaver731  /** empreinte de la version détenue par le serveur */732  print: string | null733}734const controllers = new Map<string, Controller>()735function controller(key: string): Controller {736  let c = controllers.get(key)737  if (!c) {738    c = { auto: createAutosaver(() => saveNow(key)), print: null }739    controllers.set(key, c)740  }741  return c742}743function dropController(key: string) {744  controllers.get(key)?.auto.cancel()745  controllers.delete(key)746}747748/**749 * Enregistre un brouillon dans « Brouillons » en remplaçant la version précédente (les messages JMAP sont immuables : chaque750 * enregistrement crée un message et détruit l'ancien). Rien n'est envoyé si le contenu est celui que le serveur détient déjà.751 * Rend faux si la version courante n'est pas sur le serveur.752 */753async function saveNow(key: string): Promise<boolean> {754  flushEditor(key)755  const d = find(key)756  if (!d) return true757  if (d.send === "sending") return true758  if (d.save !== "dirty" && d.save !== "error") return true759  if (!hasClient(d.mb) || S.get().phase !== "ready") return false760  if (d.attachments.some((a) => !a.blobId && !a.error)) return false // téléversement en cours : il relancera l'enregistrement761  const ctl = controller(key)762  let print = fingerprint(d)763  if (d.draftEmailId && ctl.print === print) {764    patchDraft(key, { save: "saved" })765    persistLocal(true)766    return true767  }768  patchDraft(key, { save: "saving" })769  try {770    const draftsId = await ensureRoleFolder(d.mb, "drafts")771    const old = d.draftEmailId772    const client = clientFor(d.mb)773    // la nouvelle version d'abord, l'ancienne retirée ensuite seulement : un refus du serveur ne coûte jamais la copie qu'il détient774    let r = await client.call("Email/set", { create: { d: buildEmail(d, draftsId) } })775    if (r.notCreated?.d && isBlobError(r.notCreated.d) && (await repairBlobs(key, r.notCreated.d))) {776      // une pièce n'existait plus sur le serveur (brouillon remplacé ailleurs) : remise depuis cet appareil, ou retirée — second essai777      const fixed = find(key)778      if (fixed) {779        print = fingerprint(fixed)780        r = await client.call("Email/set", { create: { d: buildEmail(fixed, draftsId) } })781      }782    }783    assertSet("Email/set", { notCreated: r.notCreated }, "d")784    const id = r.created!.d.id785    const gone = old ? await client.call("Email/set", { destroy: [old] }).catch(() => null) : null786    const cur = find(key)787    if (!cur) {788      // la rédaction a été abandonnée ou envoyée entre-temps : ne pas laisser de brouillon orphelin789      void client.call("Email/set", { destroy: [id] }).catch(() => {})790      return true791    }792    // l'ancienne version n'existait plus : le brouillon a été repris (ou supprimé) sur un autre appareil — les deux versions restent793    const replacedElsewhere = !!old && !!gone?.notDestroyed?.[old]794    ctl.print = print795    patchDraft(key, { draftEmailId: id, save: cur.save === "saving" ? "saved" : cur.save, savedAt: Date.now() })796    persistLocal(true)797    if (replacedElsewhere) toast({ kind: "info", text: t("cmp.draftConflict"), timeout: 8000 })798    return find(key)?.save === "saved"799  } catch (e) {800    const cur = find(key)801    if (cur) patchDraft(key, { save: errorKind(e) === "unauthorized" ? "dirty" : "error" })802    return false803  }804}805type BlobError = { type: string; description?: string | null; properties?: string[]; notFound?: string[] }806const isBlobError = (e: BlobError) => e.type === "blobNotFound" || ((e.type === "invalidProperties" || e.type === "notFound") && /blob|attachment/i.test(`${e.description ?? ""} ${(e.properties ?? []).join(" ")}`))807/**808 * Des pièces du brouillon n'existent plus sur le serveur (il y a été remplacé ou supprimé depuis un autre appareil, et leurs809 * blobs avec lui). Celles dont cet appareil a encore les octets sont téléversées de nouveau ; une image du texte devenue810 * introuvable est retirée (avec son emplacement) ; une pièce jointe introuvable est signalée dans le plateau, à rejoindre.811 * Rend vrai si le brouillon a pu être remis en état d'être enregistré.812 */813async function repairBlobs(key: string, err: BlobError): Promise<boolean> {814  const d = find(key)815  if (!d) return false816  const client = clientFor(d.mb)817  const named = Array.isArray(err.notFound) && err.notFound.length ? new Set(err.notFound) : null818  let changed = false819  let lostImage = false820  for (const a of d.attachments) {821    if (!a.blobId || a.error) continue822    if (named && !named.has(a.blobId)) continue823    const bytes = localBlobs.get(a.key)824    if (bytes) {825      try {826        const up = await client.upload(bytes, a.type)827        patchAttachmentQuiet(key, a.key, { blobId: up.blobId, fileId: null })828        changed = true829      } catch {830        return false // réseau : l'enregistrement sera retenté tel quel831      }832      continue833    }834    if (!named) {835      // le serveur n'a pas dit lesquelles : chacune est vérifiée836      const ok = await request(client.downloadUrl(a.blobId, "blob", a.type), { headers: { accept: "*/*", range: "bytes=0-0" } }).then(() => true, (e: unknown) => !(e instanceof HttpError && e.status === 404))837      if (ok) continue838    }839    const cur = find(key)840    if (!cur) return false841    changed = true842    if (a.inline && a.cid) {843      lostImage = true844      const doc = parse(`<body>${cur.html}</body>`)845      for (const img of Array.from(doc.body.querySelectorAll("img"))) if (img.getAttribute("src") === `cid:${a.cid}`) img.remove()846      flushEditor(key)847      patchDraft(key, { attachments: cur.attachments.filter((x) => x.key !== a.key), html: doc.body.innerHTML, rev: cur.rev + 1 })848    } else patchAttachmentQuiet(key, a.key, { blobId: null, fileId: null, error: t("cmp.att.gone") })849  }850  if (lostImage) toast({ kind: "info", text: t("cmp.att.imageGone"), timeout: 8000 })851  return changed852}853854/** Enregistre maintenant (bouton « Réessayer », fermeture, réduction). Sans clé : le brouillon affiché. */855export async function saveDraft(key?: string): Promise<void> {856  reconcile()857  const d = target(key)858  if (!d) return859  const ctl = controller(d.key)860  flushEditor(d.key)861  const cur = find(d.key)862  if (cur && (cur.save === "dirty" || cur.save === "error")) ctl.auto.touch()863  await ctl.auto.flush()864}865if (typeof window !== "undefined") {866  // retour du réseau : tout ce qui attendait part ; page masquée ou quittée : les copies locales sont à jour867  window.addEventListener("online", () => {868    for (const d of C.get().drafts) if (d.save === "dirty" || d.save === "error") void saveDraft(d.key)869  })870  window.addEventListener("pagehide", () => {871    for (const d of C.get().drafts) flushEditor(d.key)872    writeLocal()873  })874}875876function removeDraft(key: string) {877  const d = find(key)878  if (!d) return879  dropController(key)880  for (const a of d.attachments) forget(a)881  setDrafts(C.get().drafts.filter((x) => x.key !== key))882  persistLocal(true)883}884885/**886 * Ferme la fenêtre de rédaction en gardant le brouillon. La copie locale n'est effacée que si le serveur détient bien la887 * dernière version : si l'enregistrement a échoué ou n'a pas pu se faire (hors ligne, session perdue, téléversement en cours),888 * la rédaction est seulement réduite — elle reste dans l'état et dans la copie locale, et sera enregistrée au retour du réseau.889 * Rend vrai si la rédaction est réellement fermée.890 */891export async function closeDraft(key?: string): Promise<boolean> {892  reconcile()893  const d = target(key)894  if (!d) return true895  await saveDraft(d.key)896  const cur = find(d.key)897  if (!cur) return true898  if (cur.save !== "saved" && cur.save !== "clean") {899    // rien n'est perdu : le texte reste ici (réduit) et dans la copie locale, relue au prochain démarrage900    patchDraft(cur.key, { minimized: true })901    persistLocal(true)902    toast({ kind: "info", text: t("compose.keptLocally") })903    return false904  }905  removeDraft(cur.key)906  return true907}908909/** Abandonne : supprime aussi la version enregistrée. */910export async function discardDraft(key?: string) {911  reconcile()912  const d = target(key)913  if (!d) return914  for (const a of d.attachments) uploads.get(a.key)?.abort()915  const ctl = controllers.get(d.key)916  const busy = ctl?.auto.busy ? ctl.auto.flush().catch(() => {}) : null917  ctl?.auto.cancel()918  const latest = () => find(d.key)?.draftEmailId ?? d.draftEmailId919  if (busy) {920    await busy921  }922  const id = latest()923  removeDraft(d.key)924  if (id && hasClient(d.mb)) await clientFor(d.mb).call("Email/set", { destroy: [id] }).catch(() => {})925  toast({ kind: "info", text: t("compose.discarded") })926}927928// ---------------------------------------------------------------- contrôles avant l'envoi929export type SendProblem = "noRecipient" | "invalidRecipient" | "uploading" | "uploadError" | "noIdentity" | null930export function sendProblem(d: Draft): SendProblem {931  const all = [...d.to, ...d.cc, ...d.bcc]932  if (!all.length) return "noRecipient"933  if (all.some((a) => !isValidEmail(a.email))) return "invalidRecipient"934  if (d.attachments.some((a) => a.error)) return "uploadError"935  if (d.attachments.some((a) => !a.blobId)) return "uploading"936  // une adresse connue de l'API part par /api/v1 (le serveur construit l'expéditeur) : pas besoin d'identité JMAP937  if (!hasUsableSender(d)) return "noIdentity"938  return null939}940function hasUsableSender(d: Draft): boolean {941  const sender = senderOf(d)942  return !!(addressRow(sender) || sender?.via === "api" || d.identityId)943}944/**945 * L'expéditeur n'est pas encore connu parce que la boîte (identités JMAP) ou les adresses de l'API sont encore en cours de946 * lecture — brouillon rouvert juste après un rechargement. L'envoi attend alors, avec sa raison ; ce n'est pas un refus.947 */948export function senderPending(d: Draft): boolean {949  if (hasUsableSender(d)) return false950  const a = S.get().accounts[d.mb]951  return !a || a.status === "loading" || !addressesSettled()952}953/**954 * Les identités arrivent parfois après l'ouverture d'un brouillon : celui qui n'avait pas d'expéditeur (ou seulement son955 * adresse, sans identité JMAP) reçoit alors l'expéditeur par défaut de sa boîte, ou l'identité de son adresse.956 */957function applyLateSenders() {958  const groups = senderGroups()959  if (!groups.length) return960  for (const d of C.get().drafts) {961    if (d.identityId) continue962    const known = d.from ? findSender(groups, senderKey(d.mb, d.from)) : undefined963    const sender = known ?? (d.from ? undefined : defaultSender(groups, d.mb))964    if (!sender || sender.mb !== d.mb || (!sender.identityId && d.from)) continue965    patchDraft(d.key, { identityId: sender.identityId, from: sender.email })966  }967}968let senderSig: unknown = null969S.subscribe(() => {970  const s = S.get()971  if (s.phase !== "ready" || !C.get().drafts.length) return972  const groups = senderGroups(s)973  if (groups === senderSig) return974  senderSig = groups975  applyLateSenders()976})977export type SendWarning =978  | { kind: "noSubject" }979  | { kind: "missingAttachment"; phrases: string[] }980  | { kind: "duplicates"; addresses: string[] }981  | { kind: "sensitive"; addresses: string[] }982  | { kind: "external"; addresses: string[] }983/** Ce qui mérite une confirmation avant l'envoi (rien ne bloque : la personne décide). */984export function sendWarnings(d: ComposeDraft): SendWarning[] {985  const out: SendWarning[] = []986  const prefs = D.get().prefs987  const recipients = [...d.to, ...d.cc, ...d.bcc].map((a) => a.email)988  if (!d.subject.trim()) out.push({ kind: "noSubject" })989  if (prefs.warn_missing_attachment && !d.attachments.some((a) => !a.inline)) {990    const body = d.mode === "html" ? authoredHtmlText(d.html, parse) : authoredText(d.text)991    const phrases = attachmentMentions(d.subject, body)992    if (phrases.length) out.push({ kind: "missingAttachment", phrases })993  }994  const dup = recipientIssues(d.to, d.cc, d.bcc).duplicates995  if (dup.length) out.push({ kind: "duplicates", addresses: dup })996  const sensitive = matchSensitive(recipients, prefs.sensitive)997  if (sensitive.length) out.push({ kind: "sensitive", addresses: sensitive })998  if (prefs.warn_external) {999    const ext = externalRecipients(recipients, ownAddresses())1000    if (ext.length) out.push({ kind: "external", addresses: ext })1001  }1002  return out1003}10041005// ---------------------------------------------------------------- envoi1006export interface SendOptions {1007  /** envoi différé (au plus 30 jours) */1008  sendAt?: Date1009  /** rappel si personne n'a répondu à cette date */1010  remindAt?: Date1011  remindIfNoReply?: boolean1012  /** la personne a confirmé l'envoi aux destinataires sensibles */1013  confirmSensitive?: boolean1014  /** envoi d'un modèle enregistré tel quel (mise en page du modèle) à la place du texte rédigé */1015  template?: { id: string; variables: Record<string, string> }1016}1017export type SendResult = { ok: true } | { ok: false; reason: "problem" | "error" | "busy" } | { ok: false; reason: "confirmSensitive"; recipients: string[] }10181019const OUTBOUND_STATE: Record<string, DeliveryStatus["delivered"]> = { delivered: "yes", bounced: "no", failed: "no", cancelled: "no" }1020/** États par destinataire d'un envoi suivi par l'API, dans la forme qu'affiche le suivi des envois. */1021export function outboundDeliveryStatus(o: Pick<Outbound, "recipients">): Record<string, DeliveryStatus> {1022  const out: Record<string, DeliveryStatus> = {}1023  for (const r of o.recipients) out[r.address] = { delivered: OUTBOUND_STATE[r.status] ?? "queued", smtpReply: r.smtp_reply ?? "", displayed: "unknown" }1024  return out1025}1026function dedupe(lists: Addr[][]): Addr[][] {1027  const seen = new Set<string>()1028  return lists.map((l) => l.filter((a) => (seen.has(a.email.toLowerCase()) ? false : (seen.add(a.email.toLowerCase()), true))))1029}1030function hash(s: string): string {1031  let h = 0x811c9dc51032  for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193) >>> 01033  return h.toString(36)1034}10351036/**1037 * Envoi. Règle de l'interface : rien n'est annoncé « envoyé » avant que le serveur ait pris le message en charge ; pendant la1038 * fenêtre d'annulation le message est seulement retenu ; l'acceptation n'est pas la remise — le suivi lit ensuite l'état réel1039 * par destinataire. Tout expéditeur connu de l'API (boîte ou alias) part par POST /api/v1/messages/send : même contrôle de1040 * l'adresse, même annulation, même envoi différé, même rappel. Seule une identité JMAP sans ligne d'adresse garde la soumission JMAP.1041 */1042export async function sendDraft(key?: string, opts: SendOptions = {}): Promise<SendResult> {1043  reconcile()1044  const d0 = target(key)1045  if (!d0) return { ok: false, reason: "problem" }1046  flushEditor(d0.key)1047  const ctl = controller(d0.key)1048  if (ctl.auto.busy) await ctl.auto.flush().catch(() => {})1049  const d = find(d0.key)1050  if (!d || sendProblem(d)) return { ok: false, reason: "problem" }1051  if (d.send === "sending") return { ok: false, reason: "busy" }1052  patchDraft(d.key, { send: "sending", sendError: null })1053  const fail = (message: string, keepDraftId?: Id | null): SendResult => {1054    if (find(d.key)) patchDraft(d.key, { send: "error", sendError: message, ...(keepDraftId !== undefined ? { draftEmailId: keepDraftId } : {}) })1055    return { ok: false, reason: "error" }1056  }1057  const sender = senderOf(d)1058  if (sender && (addressRow(sender) || sender.via === "api")) return sendViaApi(d, sender, opts, fail)1059  if (opts.sendAt || opts.remindAt || opts.template) return fail(t("cmp.send.needsAddress"))1060  return sendViaJmap(d, fail)1061}10621063/** Soumission JMAP : identité ajoutée à la main, sans ligne d'adresse (ou API des adresses injoignable). Ni annulation ni envoi différé. */1064async function sendViaJmap(d: ComposeDraft, fail: (message: string, keepDraftId?: Id | null) => SendResult): Promise<SendResult> {1065  try {1066    const c = clientFor(d.mb)1067    const draftsId = await ensureRoleFolder(d.mb, "drafts")1068    const sentId = await ensureRoleFolder(d.mb, "sent")1069    const b = c.batch()1070    const [to, cc, bcc] = dedupe([d.to, d.cc, d.bcc])1071    const set = b.add("Email/set", { create: { m: buildEmail({ ...d, to, cc, bcc }, draftsId) }, ...(d.draftEmailId ? { destroy: [d.draftEmailId] } : {}) })1072    const sub = b.add("EmailSubmission/set", {1073      create: { s: { identityId: d.identityId!, emailId: "#m" } },1074      onSuccessUpdateEmail: { "#s": { [`mailboxIds/${draftsId}`]: null, [`mailboxIds/${sentId}`]: true, [`keywords/${KW.draft}`]: null } },1075    })1076    await b.send()1077    const created = set.result.created?.m1078    if (!created) throw new JmapSetError("Email/set", set.result.notCreated?.m ?? { type: "serverFail" })1079    const accepted = sub.error ? undefined : sub.result.created?.s1080    if (!accepted) {1081      // le message existe comme brouillon mais le serveur de soumission l'a refusé : rien n'est parti1082      const err = sub.error ?? new JmapSetError("EmailSubmission/set", sub.result.notCreated?.s ?? { type: "serverFail" })1083      controller(d.key).print = null1084      return fail(submissionErrorMessage(err), created.id)1085    }1086    const recipients = [...to, ...cc, ...bcc].map((a) => a.email)1087    const delivery: Delivery = { key: newKey(), mb: d.mb, submissionId: accepted.id, subject: d.subject, recipients, status: null, polling: true, acceptedAt: Date.now() }1088    removeDraft(d.key)1089    S.set((s) => ({ deliveries: [...s.deliveries.slice(-4), delivery] }))1090    void pollDelivery(delivery.key)1091    markRelated(d)1092    if (S.get().mb === d.mb) void refreshList()1093    return { ok: true }1094  } catch (e) {1095    if (errorKind(e) === "unauthorized") {1096      if (find(d.key)) patchDraft(d.key, { send: "idle", save: "dirty" })1097      return { ok: false, reason: "error" }1098    }1099    return fail(submissionErrorMessage(e))1100  }1101}1102function markRelated(d: ComposeDraft) {1103  if (!d.related || !hasClient(d.mb)) return1104  void clientFor(d.mb).call("Email/set", { update: { [d.related.emailId]: { [`keywords/${d.related.kind === "reply" ? KW.answered : KW.forwarded}`]: true } } }).catch(() => {})1105}11061107interface FileRef {1108  file_id: string1109  filename: string1110  inline?: boolean1111  cid?: string1112}1113/**1114 * L'API attend des fichiers (`file_…`) : chaque pièce y est remise UNE fois par brouillon — depuis les octets encore en1115 * mémoire s'ils y sont, sinon depuis le blob — et son identifiant est gardé sur la pièce : un nouvel essai, ou un envoi après1116 * annulation, ne retéléverse rien tant que le fichier n'a pas expiré.1117 */1118async function fileRefs(d: ComposeDraft, parts: ComposeAttachment[], sender: Sender): Promise<FileRef[]> {1119  const out: FileRef[] = []1120  for (const a of parts) {1121    let id = a.fileId && a.fileMb === d.mb && (a.fileExp ?? 0) > Date.now() + 120_000 ? a.fileId : null1122    if (!id) {1123      const type = /^[a-z0-9.+-]+\/[a-z0-9.+-]+$/i.test(a.type) ? a.type : "application/octet-stream"1124      const body = localBlobs.get(a.key) ?? new Blob([(await clientFor(d.mb).downloadBytes(a.blobId!, a.type)) as BlobPart])1125      const r = await request(`/api/v1/files?filename=${encodeURIComponent(a.name.slice(0, 200))}&address=${encodeURIComponent(sender.email)}`, { method: "POST", body, headers: { "content-type": type } })1126      const f = (await r.json()) as { id: string; expires_at: string }1127      id = f.id1128      patchAttachmentQuiet(d.key, a.key, { fileId: f.id, fileMb: d.mb, fileExp: Date.parse(f.expires_at) || Date.now() + 3600_000 })1129    }1130    out.push(a.inline && a.cid ? { file_id: id, filename: a.name.slice(0, 200), inline: true, cid: a.cid } : { file_id: id, filename: a.name.slice(0, 200) })1131  }1132  return out1133}1134/** Note sur une pièce une information qui ne change pas le contenu du brouillon (identifiant de fichier de l'API). */1135function patchAttachmentQuiet(key: string, attKey: string, patch: Partial<ComposeAttachment>) {1136  const d = find(key)1137  if (!d) return1138  patchDraft(key, { attachments: d.attachments.map((a) => (a.key === attKey ? { ...a, ...patch } : a)) })1139  persistLocal()1140}11411142async function sendViaApi(d: ComposeDraft, sender: Sender, opts: SendOptions, fail: (message: string, keepDraftId?: Id | null) => SendResult): Promise<SendResult> {1143  try {1144    const html = d.mode === "html" && !opts.template ? outgoingHtml(d) : null1145    const attachments = await fileRefs(d, outgoingParts(d, html), sender)1146    const norm = (l: Addr[]) => l.map((a) => (a.name?.trim() ? { email: a.email, name: a.name.trim() } : { email: a.email }))1147    const [to, cc, bcc] = dedupe([d.to, d.cc, d.bcc])1148    const prefs = D.get().prefs1149    const undo = opts.sendAt ? 0 : prefs.undo_seconds1150    const replyTo = identityOf(d)?.replyTo?.map((a) => a.email).filter(isValidEmail) ?? []1151    const json = {1152      from: sender.email, to: norm(to), cc: norm(cc), bcc: norm(bcc), subject: d.subject,1153      ...(opts.template ? { template_id: opts.template.id, variables: opts.template.variables } : html !== null ? { html: wrapOutgoingBody(html), text: htmlToText(html) } : { text: d.text }),1154      ...(attachments.length ? { attachments } : {}),1155      ...(d.inReplyTo?.[0] ? { in_reply_to: d.inReplyTo[0] } : {}),1156      ...(d.references?.length ? { references: d.references.slice(-50) } : {}),1157      ...(replyTo.length ? { headers: { "Reply-To": replyTo.join(", ") } } : {}),1158      ...(opts.sendAt ? { send_at: opts.sendAt.toISOString() } : {}),1159      ...(undo > 0 ? { undo_seconds: undo } : {}),1160      ...(opts.remindAt ? { remind_at: opts.remindAt.toISOString(), remind_if_no_reply: opts.remindIfNoReply !== false } : {}),1161      ...(opts.confirmSensitive ? { confirm_sensitive: true } : {}),1162    }1163    const o = await v1<Outbound & { undo_until?: string | null }>("/messages/send", {1164      method: "POST",1165      // même clé pour un nouvel essai du même contenu : un envoi déjà accepté n'est jamais doublé ; un contenu corrigé,1166      // ou un envoi repris après annulation, est une autre demande1167      headers: { "idempotency-key": `web-${d.key}-${d.sendSeq ?? 0}-${hash(JSON.stringify(json))}` },1168      json,1169    })1170    if (o.status === "failed" || o.status === "cancelled") return fail(`${t("send.failed")}${o.last_error ? ` — ${o.last_error}` : ""}`)1171    // ---- pris en charge par l'API : retenu (annulation), programmé, remis à la file du serveur de courrier, ou mis en file par SP Mail1172    const sent: ComposeDraft = { ...(find(d.key) ?? d), to, cc, bcc, send: "idle", sendError: null }1173    const oldDraftId = sent.draftEmailId1174    removeDraft(d.key)1175    // le brouillon enregistré est remplacé par le message que l'API a créé (retenu dans « Brouillons », puis classé dans « Envoyés »)1176    if (oldDraftId && hasClient(d.mb)) void clientFor(d.mb).call("Email/set", { destroy: [oldDraftId] }).catch(() => {})1177    if (o.status === "scheduled" && o.undo_until) holdSend(sent, o, Date.parse(o.undo_until))1178    else if (o.status === "scheduled") {1179      toast({ kind: "success", text: t("cmp.send.scheduled", { when: fmtDateTime(o.send_at) }), actionLabel: t("cmp.send.cancelScheduled"), action: () => void undoSend(o.id, sent), timeout: 10_000 })1180      markRelated(sent)1181    } else {1182      trackOutbound(sent, o)1183      markRelated(sent)1184    }1185    if (opts.remindAt && o.status !== "scheduled") toast({ kind: "info", text: t("cmp.send.reminderSet", { when: fmtDateTime(opts.remindAt.toISOString()) }) })1186    if (S.get().mb === d.mb) void refreshList()1187    return { ok: true }1188  } catch (e) {1189    if (errorKind(e) === "unauthorized") {1190      if (find(d.key)) patchDraft(d.key, { send: "idle", save: "dirty" })1191      return { ok: false, reason: "error" }1192    }1193    if (e instanceof HttpError) {1194      if (e.code === "confirmation_required") {1195        // rien n'a été mis en file : la personne confirme, puis l'envoi est refait avec `confirm_sensitive`1196        if (find(d.key)) patchDraft(d.key, { send: "idle" })1197        const recipients = (e.details as { recipients?: unknown } | undefined)?.recipients1198        return { ok: false, reason: "confirmSensitive", recipients: Array.isArray(recipients) ? recipients.map(String) : [] }1199      }1200      if (e.code === "address_inactive") return fail(t("send.addressInactive", { address: sender.email }))1201      if (e.code === "address_cannot_send" || e.code === "from_not_allowed") return fail(t("send.addressCannotSend", { address: sender.email }))1202      if (e.code === "unknown_file" || e.code === "file_expired" || e.code === "file_wrong_mailbox") {1203        // fichier expiré côté API : oublié, il sera remis au prochain essai1204        const cur = find(d.key)1205        if (cur) patchDraft(d.key, { attachments: cur.attachments.map((a) => ({ ...a, fileId: null })) })1206        return fail(t("cmp.send.fileExpired"))1207      }1208      const kind = errorKind(e)1209      return fail(kind === "unknown" || kind === "invalid" || kind === "forbidden" || kind === "conflict" ? `${t("send.failed")} — ${errorDetail(e)}` : t(`error.${kind}`))1210    }1211    return fail(submissionErrorMessage(e))1212  }1213}12141215/** Suivi de la remise d'un envoi pris en charge par l'API. */1216function trackOutbound(d: Pick<ComposeDraft, "mb" | "subject" | "to" | "cc" | "bcc">, o: Outbound) {1217  const recipients = [...d.to, ...d.cc, ...d.bcc].map((a) => a.email)1218  const delivery: Delivery = { key: newKey(), mb: d.mb, submissionId: "", outboundId: o.id, subject: d.subject, recipients, status: outboundDeliveryStatus(o), polling: !isFinalOutbound(o), acceptedAt: Date.now() }1219  S.set((s) => ({ deliveries: [...s.deliveries.slice(-4), delivery] }))1220  if (!isFinalOutbound(o)) void pollOutbound(o.id, (cur) => patchDelivery(delivery.key, { status: outboundDeliveryStatus(cur), polling: !isFinalOutbound(cur) })).then(() => patchDelivery(delivery.key, { polling: false }))1221}12221223// ---------------------------------------------------------------- annulation d'envoi (retenue côté serveur)1224interface Hold {1225  id: string1226  draft: ComposeDraft1227  until: number1228  toastId: number1229  tick: ReturnType<typeof setInterval>1230}1231const holds = new Map<string, Hold>()1232const publishHolds = () => C.set({ held: [...holds.values()].map((h) => ({ id: h.id, subject: h.draft.subject, until: h.until })) })1233const holdText = (h: Pick<Hold, "until">) => t("cmp.undo.countdown", { n: Math.max(0, Math.ceil((h.until - Date.now()) / 1000)) })1234/**1235 * Le serveur retient le message jusqu'à `until` : la notification compte les secondes et propose « Annuler ». Aucune horloge1236 * du navigateur n'est crue pour l'envoi lui-même — à l'échéance on lit l'état réel du message.1237 */1238function holdSend(draft: ComposeDraft, o: Outbound, until: number) {1239  const id = o.id1240  const toastId = toast({ kind: "info", text: holdText({ until }), actionLabel: t("cmp.undo.action"), action: () => void undoSend(id), timeout: Math.max(1000, until - Date.now()) + 400 })1241  const tick = setInterval(() => {1242    const h = holds.get(id)1243    if (!h) return clearInterval(tick)1244    if (Date.now() >= h.until) return releaseHold(id)1245    const text = holdText(h)1246    S.set((s) => (s.toasts.some((x) => x.id === toastId && x.text !== text) ? { toasts: s.toasts.map((x) => (x.id === toastId ? { ...x, text } : x)) } : {}))1247  }, 250)1248  holds.set(id, { id, draft, until, toastId, tick })1249  publishHolds()1250}1251/** Fin de la fenêtre : le message part ; le suivi de remise commence. */1252function releaseHold(id: string) {1253  const h = holds.get(id)1254  if (!h) return1255  clearInterval(h.tick)1256  holds.delete(id)1257  publishHolds()1258  dismissToast(h.toastId)1259  markRelated(h.draft)1260  const o: Outbound = { id, status: "queued", from: h.draft.from ?? "", message_id: null, recipients: [...h.draft.to, ...h.draft.cc, ...h.draft.bcc].map((a) => ({ address: a.email.toLowerCase(), status: "queued", smtp_reply: null })), external: false, send_at: null, attempts: 0, last_error: null, submitted_at: null, final_at: null, created_at: "", updated_at: "" }1261  trackOutbound(h.draft, o)1262  if (S.get().mb === h.draft.mb) setTimeout(() => void refreshList(), 1500)1263}1264interface HeldContent {1265  id: string1266  mailbox_id: string1267  email_id: string1268  from: { email: string; name: string | null }1269  to: { email: string; name: string | null }[]1270  cc: { email: string; name: string | null }[]1271  bcc: { email: string; name: string | null }[]1272  subject: string1273  html: string | null1274  text: string | null1275  attachments: { blob_id: string; name: string | null; type: string; size: number; cid: string | null; inline: boolean }[]1276  in_reply_to: string[]1277  references: string[]1278}1279/** Reconstitue un brouillon depuis le message retenu (envoi fait dans une autre fenêtre, ou programmé plus tôt). */1280function draftFromHeld(c: HeldContent): ComposeDraft | null {1281  if (!S.get().me?.mailboxes.some((m) => m.id === c.mailbox_id)) return null1282  const sender = replySender(senderGroups(), c.mailbox_id, [c.from.email])1283  const d = baseDraft(c.mailbox_id, sender)1284  const norm = (l: HeldContent["to"]): Addr[] => l.map((a) => ({ name: a.name ?? undefined, email: a.email }))1285  const html = c.html ? quotedHtml(c.html) : null1286  const used = new Set(html ? referencedCids(html) : [])1287  d.attachments = c.attachments.map((a) => {1288    const cid = cleanCid(a.cid)1289    const inline = a.inline && !!cid && used.has(cid)1290    return { key: newKey(), name: a.name ?? "fichier", type: a.type, size: a.size, blobId: a.blob_id, progress: 1, error: null, inherited: true, ...(inline ? { inline: true, cid } : {}) }1291  })1292  d.reply = c.in_reply_to.length > 01293  d.signatureId = defaultSignature(sender, d.reply)1294  let body = html ? sanitizeComposerHtml(html, inlineCids(d)) : textToHtml(c.text ?? "")1295  const sig = signatureContent(sender, d.signatureId).html1296  if (sig) body = retagSignature(body, sig, parse)1297  Object.assign(d, { to: norm(c.to), cc: norm(c.cc), bcc: norm(c.bcc), showCc: c.cc.length + c.bcc.length > 0, subject: c.subject, mode: html ? "html" : "text", html: body, text: c.text ?? "", inReplyTo: c.in_reply_to.length ? c.in_reply_to : null, references: c.references.length ? c.references : null } satisfies Partial<ComposeDraft>)1298  return d1299}1300/**1301 * Rattache les pièces du brouillon envoyé à celles du message gardé par le serveur (l'ordre des parties d'un message n'est1302 * pas celui de l'envoi : les images en ligne se retrouvent par leur Content-ID, les fichiers par leur nom et leur type).1303 */1304function rebind(d: ComposeDraft, c: HeldContent): ComposeAttachment[] {1305  const pool = [...c.attachments]1306  return outgoingParts(d, d.mode === "html" ? outgoingHtml(d) : null).map((a) => {1307    let i = a.inline && a.cid ? pool.findIndex((x) => cleanCid(x.cid) === a.cid) : pool.findIndex((x) => !x.inline && (x.name ?? "") === a.name && x.type === a.type)1308    if (i < 0 && !a.inline) i = pool.findIndex((x) => !x.inline && (x.name ?? "") === a.name)1309    if (i < 0) return a1310    const [hit] = pool.splice(i, 1)1311    return { ...a, blobId: hit.blob_id, inherited: true }1312  })1313}1314/**1315 * Annule un envoi retenu (ou programmé) : le serveur garde le message — pièces jointes comprises — dans « Brouillons », et la1316 * rédaction se rouvre dessus avec tout son contenu. S'il est trop tard, on le dit et le suivi de remise prend le relais.1317 */1318export async function undoSend(id?: string, snapshot?: ComposeDraft): Promise<boolean> {1319  const hold = id ? holds.get(id) : [...holds.values()].pop()1320  const outboundId = id ?? hold?.id1321  if (!outboundId) return false1322  if (hold) {1323    clearInterval(hold.tick)1324    dismissToast(hold.toastId)1325  }1326  try {1327    const content = await api<HeldContent>(`/api/next/compose/undo/${encodeURIComponent(outboundId)}`, { method: "POST" })1328    holds.delete(outboundId)1329    publishHolds()1330    const kept = hold?.draft ?? snapshot1331    // les pièces du brouillon gardé par le serveur sont celles de l'envoi (même ordre) : la rédaction s'y rattache1332    const base = kept ? { ...kept, attachments: rebind(kept, content) } : draftFromHeld(content)1333    if (!base) return false1334    // la rédaction reprend sur le brouillon gardé par le serveur ; un nouvel envoi est une nouvelle demande1335    const d: ComposeDraft = { ...base, key: newKey(), draftEmailId: content.email_id, save: "saved", savedAt: Date.now(), send: "idle", sendError: null, minimized: false, sendSeq: (base.sendSeq ?? 0) + 1, rev: base.rev + 1 }1336    if (!present(d)) return false1337    toast({ kind: "info", text: t("cmp.undo.done") })1338    if (S.get().mb === d.mb) void refreshList()1339    return true1340  } catch (e) {1341    if (e instanceof HttpError && (e.code === "not_cancellable" || e.status === 404)) {1342      toast({ kind: "error", text: t("cmp.undo.tooLate") })1343      if (hold) releaseHold(outboundId)1344      return false1345    }1346    toast({ kind: "error", text: t("cmp.undo.failed"), detail: errorDetail(e) || undefined, actionLabel: t("cmp.undo.action"), action: () => void undoSend(outboundId, snapshot) })1347    // la retenue court toujours côté serveur : à l'échéance, le suivi reprend1348    if (hold) {1349      const tick = setInterval(() => (Date.now() >= hold.until ? releaseHold(outboundId) : undefined), 250)1350      holds.set(outboundId, { ...hold, tick })1351    }1352    return false1353  }1354}13551356function submissionErrorMessage(e: unknown): string {1357  const type = e instanceof JmapSetError ? e.error.type : e instanceof JmapMethodError ? e.type : ""1358  const detail = errorDetail(e)1359  switch (type) {1360    case "invalidRecipients":1361    case "noRecipients":1362      return t("send.invalidRecipients") + (detail ? ` (${detail})` : "")1363    case "forbiddenFrom":1364    case "forbiddenMailFrom":1365      return t("send.forbiddenFrom")1366    case "tooLarge":1367      return t("send.tooLarge")1368    case "overQuota":1369    case "maxQuotaReached":1370      return t("error.quota")1371    default: {1372      const kind = errorKind(e)1373      return kind === "unknown" || kind === "invalid" ? `${t("send.failed")}${detail ? ` — ${detail}` : ""}` : t(`error.${kind}`)1374    }1375  }1376}13771378const POLL_DELAYS = [500, 1000, 2000, 3000, 5000, 8000, 15000, 30000, 60000, 60000, 120000]1379async function pollDelivery(key: string) {1380  for (const delay of POLL_DELAYS) {1381    await new Promise((r) => setTimeout(r, delay))1382    const cur = S.get().deliveries.find((x) => x.key === key)1383    if (!cur || cur.outboundId || !hasClient(cur.mb)) return1384    try {1385      const r = await clientFor(cur.mb).call("EmailSubmission/get", { ids: [cur.submissionId] })1386      const sub = r.list[0]1387      if (!sub) break1388      const status = sub.deliveryStatus1389      const pendingLeft = !status || Object.values(status).some((x) => x.delivered === "queued") || sub.undoStatus === "pending"1390      patchDelivery(key, { status, polling: pendingLeft })1391      if (!pendingLeft) return1392    } catch (e) {1393      if (errorKind(e) === "unauthorized") return1394    }1395  }1396  patchDelivery(key, { polling: false })1397}1398function patchDelivery(key: string, patch: Partial<Delivery>) {1399  S.set((s) => ({ deliveries: s.deliveries.map((x) => (x.key === key ? { ...x, ...patch } : x)) }))1400}1401export function dismissDelivery(key: string) {1402  S.set((s) => ({ deliveries: s.deliveries.filter((x) => x.key !== key) }))1403}14041405// ---------------------------------------------------------------- petite API pour les autres modules (assistant, productivité)1406export interface OpenComposerInit {1407  to?: (string | Addr)[]1408  cc?: (string | Addr)[]1409  bcc?: (string | Addr)[]1410  subject?: string1411  /** contenu initial, placé au-dessus de la signature (HTML assaini à l'entrée, ou texte brut) */1412  html?: string1413  text?: string1414  /** message auquel répondre (ou à transférer) : destinataires, objet, fil et citation en découlent */1415  replyTo?: EmailFull1416  replyKind?: "reply" | "replyAll" | "forward"1417}1418const toAddrs = (l: (string | Addr)[] | undefined): Addr[] => (l ?? []).map((a) => (typeof a === "string" ? { email: a.trim() } : { name: a.name ?? undefined, email: a.email.trim() })).filter((a) => a.email)1419/** Ouvre une rédaction préremplie ; rend la clé du brouillon (null si rien n'a pu s'ouvrir). */1420export function openComposer(init: OpenComposerInit = {}): string | null {1421  if (init.replyTo) {1422    const key = composeReply(init.replyTo, init.replyKind ?? "reply", { html: init.html, text: init.text })1423    if (key && init.subject !== undefined) updateDraft({ subject: init.subject }, true, key)1424    return key1425  }1426  const key = composeNew({ to: toAddrs(init.to), cc: toAddrs(init.cc), bcc: toAddrs(init.bcc), subject: init.subject ?? "" })1427  const d = find(key)1428  if (!d) return null1429  if (init.html || init.text) {1430    const lead = init.html ? sanitizeComposerHtml(init.html) : textToHtml(init.text ?? "")1431    const sig = signatureContent(senderOf(d), d.signatureId)1432    updateDraft({ html: `${lead}${sig.html ? `<div><br></div>${sig.html}` : ""}`, text: `${init.text ?? htmlToText(lead)}${sig.text ? `\n\n${textBlock(sig.text)}` : ""}`, rev: d.rev + 1 }, true, d.key)1433  }1434  return d.key1435}1436/** Insère du texte (ou du HTML, assaini) à l'endroit du curseur du brouillon affiché ; faux si aucune rédaction n'est ouverte. */1437export function insertIntoActiveDraft(content: string | { html: string } | { text: string }): boolean {1438  const d = activeDraft()1439  if (!d) return false1440  const text = typeof content === "string" ? content : "text" in content ? content.text : null1441  const html = typeof content !== "string" && "html" in content ? sanitizeComposerHtml(content.html) : null1442  const editor = editors.get(d.key)1443  if (d.mode === "html" && editor) {1444    if (html !== null) editor.insertHtml(html)1445    else editor.insertText(text ?? "")1446    return true1447  }1448  if (d.mode === "html") updateDraft({ html: `${html ?? textToHtml(text ?? "")}${d.html}`, rev: d.rev + 1 }, true, d.key)1449  else updateDraft({ text: `${text ?? htmlToText(html ?? "")}${d.text ? `\n${d.text}` : ""}` }, true, d.key)1450  return true1451}1452/** Texte du brouillon affiché (version brute de ce qui est rédigé, citation comprise) ; null si aucune rédaction n'est ouverte. */1453export function getActiveDraftText(): string | null {1454  const d = activeDraft()1455  if (!d) return null1456  if (d.mode === "text") return d.text1457  flushEditor(d.key)1458  return htmlToText(find(d.key)?.html ?? d.html)1459}1460export function setActiveDraftSubject(subject: string): boolean {1461  const d = activeDraft()1462  if (!d) return false1463  updateDraft({ subject: subject.slice(0, 500) }, true, d.key)1464  return true1465}14661467export { folderByRole }1468
Files main
Menu

Theme