Repository Public
1// SP Mail Next — pièces jointes : formes de /api/next/attachments, aides pures (famille → glyphe, vignette sûre, filtres, limites du ZIP), état de la galerie et de l'aperçu.2import { createStore } from "../state/store"3import type { IconName } from "../ui/kit"4import { isAbort, nx, toNextError, type NextErrorKind, type Params } from "./api"5import type { Party } from "./types"67// ---------------------------------------------------------------- formes (server/src/next/search.ts fait foi)8export const ATTACHMENT_KINDS = ["image", "pdf", "document", "spreadsheet", "archive", "audio", "video", "other"] as const9export type AttachmentKind = (typeof ATTACHMENT_KINDS)[number]10export interface AttachmentItem {11 mailbox_id: string12 email_id: string13 thread_id: string14 blob_id: string15 part_id: string | null16 name: string17 type: string18 size: number19 kind: AttachmentKind20 from: Party[]21 subject: string22 received_at: string23 download_url: string24 inline_ok: boolean25}2627const str = (v: unknown): string => (typeof v === "string" ? v : "")28const INLINE_SAFE = /^image\/(png|jpeg|gif|webp)$/29/** Les seuls types que la passerelle accepte d'afficher (`inline=1`) : images matricielles. Jamais SVG ni HTML. */30export const isInlineSafe = (type: string): boolean => INLINE_SAFE.test(type.trim().toLowerCase())31/** L'adresse de téléchargement doit rester dans la passerelle JMAP du webmail (même origine, chemin attendu). */32export const isGatewayUrl = (url: string): boolean => /^\/api\/jmap\/[0-9a-f-]{36}\/download\/[^?#]+\?accept=[^#]*$/i.test(url) && !url.includes("..")3334/** Ne garde d'une entrée reçue que ce qui a la forme attendue ; `null` si elle est inutilisable. */35export function normalizeAttachment(raw: unknown): AttachmentItem | null {36 if (!raw || typeof raw !== "object") return null37 const r = raw as Record<string, unknown>38 const url = str(r.download_url)39 if (!str(r.mailbox_id) || !str(r.email_id) || !str(r.blob_id) || !isGatewayUrl(url)) return null40 const type = (str(r.type) || "application/octet-stream").toLowerCase()41 return {42 mailbox_id: str(r.mailbox_id), email_id: str(r.email_id), thread_id: str(r.thread_id), blob_id: str(r.blob_id), part_id: typeof r.part_id === "string" ? r.part_id : null,43 name: str(r.name) || "attachment", type, size: typeof r.size === "number" && r.size >= 0 ? r.size : 0,44 kind: (ATTACHMENT_KINDS as readonly string[]).includes(str(r.kind)) ? (r.kind as AttachmentKind) : "other",45 from: Array.isArray(r.from) ? (r.from as Party[]).filter((p) => p && typeof p.email === "string").map((p) => ({ email: p.email, name: typeof p.name === "string" ? p.name : null })) : [],46 subject: str(r.subject), received_at: str(r.received_at), download_url: url,47 // le serveur l'annonce, le type le confirme : une vignette n'est jamais demandée pour autre chose qu'une image sûre48 inline_ok: r.inline_ok === true && isInlineSafe(type),49 }50}51export const attachmentKey = (a: Pick<AttachmentItem, "mailbox_id" | "email_id" | "blob_id">): string => `${a.mailbox_id}:${a.email_id}:${a.blob_id}`5253const GLYPH: Record<AttachmentKind, IconName> = { image: "image", pdf: "file", document: "text", spreadsheet: "grid", archive: "zip", audio: "music", video: "film", other: "file" }54export const kindGlyph = (kind: AttachmentKind): IconName => GLYPH[kind] ?? "file"55/** Adresse d'affichage en ligne (vignette, aperçu) : seulement pour une image sûre, sinon `null`. */56export const inlineUrl = (a: Pick<AttachmentItem, "download_url" | "inline_ok" | "type">): string | null => (a.inline_ok && isInlineSafe(a.type) ? `${a.download_url}&inline=1` : null)5758/** Extension en majuscules pour la tuile (« PDF », « XLSX ») ; vide si le nom n'en a pas de courte. */59export function extensionLabel(name: string): string {60 const m = /\.([A-Za-z0-9]{1,5})$/.exec(name.trim())61 return m ? m[1].toUpperCase() : ""62}6364// ---------------------------------------------------------------- aperçu65export type PreviewMode = "image" | "pdf" | "text" | "none"66const TEXT_TYPES = /^(text\/(plain|csv|tab-separated-values|markdown|x-markdown|calendar|vcard|x-vcard|x-log|x-diff|x-patch)|application\/(json|x-ndjson|x-yaml|yaml|toml))$/67const TEXT_EXT = /\.(txt|text|log|md|markdown|csv|tsv|json|ndjson|ya?ml|toml|ini|conf|cfg|ics|vcf|diff|patch|tex|bib|srt|sql)$/i68const ACTIVE_EXT = /\.(html?|xhtml|xht|shtml|mht|mhtml|svgz?|xml|xsl)$/i69/**70 * Ce que le dialogue sait montrer : image sûre, PDF (téléchargement seulement : la CSP de l'application interdit toute visionneuse dans la page), texte brut (rendu comme texte, jamais interprété).71 * HTML, SVG et XML ne sont jamais affichés, quel que soit le type annoncé.72 */73export function previewMode(type: string, name: string): PreviewMode {74 const t = type.trim().toLowerCase()75 if (/html|svg|xml|javascript|ecmascript/.test(t) || ACTIVE_EXT.test(name.trim())) return "none"76 if (isInlineSafe(t)) return "image"77 if (t === "application/pdf") return "pdf"78 if (TEXT_TYPES.test(t)) return "text"79 if ((t === "application/octet-stream" || t.startsWith("text/")) && TEXT_EXT.test(name.trim())) return "text"80 return "none"81}82export const TEXT_PREVIEW_BYTES = 256 * 102483/** Pièce montrée par le dialogue d'aperçu : vient de la galerie ou du lecteur. */84export interface PreviewItem {85 key: string86 name: string87 type: string88 size: number89 mailboxId: string90 emailId: string91 threadId: string | null92 blobId: string93 downloadUrl: string94 /** affichage en ligne par la passerelle (images sûres seulement) */95 inlineUrl: string | null96 mode: PreviewMode97 from?: string98 subject?: string99 receivedAt?: string100}101export const previewOf = (a: AttachmentItem): PreviewItem => ({102 key: attachmentKey(a), name: a.name, type: a.type, size: a.size, mailboxId: a.mailbox_id, emailId: a.email_id, threadId: a.thread_id || null, blobId: a.blob_id,103 downloadUrl: a.download_url, inlineUrl: inlineUrl(a), mode: previewMode(a.type, a.name), from: a.from[0]?.name || a.from[0]?.email, subject: a.subject, receivedAt: a.received_at,104})105/** Décode au plus `limit` octets en texte ; `truncated` si le fichier est plus long. Les octets invalides deviennent « � ». */106export function decodeTextPreview(bytes: Uint8Array, total: number, limit = TEXT_PREVIEW_BYTES): { text: string; truncated: boolean } {107 const cut = bytes.length > limit ? bytes.subarray(0, limit) : bytes108 const text = new TextDecoder("utf-8", { fatal: false }).decode(cut).replace(/^/, "")109 return { text: text.replace(/\u0000/g, "�"), truncated: bytes.length > limit || total > cut.length }110}111112// ---------------------------------------------------------------- filtres → paramètres113export type SizeFilter = "any" | "small" | "medium" | "large" | "huge"114export type DateFilter = "any" | "7d" | "30d" | "90d" | "1y"115export interface GalleryFilter {116 q: string117 kinds: AttachmentKind[]118 size: SizeFilter119 from: string120 date: DateFilter121 /** identifiant de boîte ; null = toutes */122 mailbox: string | null123}124export const emptyGalleryFilter = (): GalleryFilter => ({ q: "", kinds: [], size: "any", from: "", date: "any", mailbox: null })125export const isFiltered = (f: GalleryFilter): boolean => !!(f.q.trim() || f.kinds.length || f.size !== "any" || f.from.trim() || f.date !== "any" || f.mailbox)126const MB = 1024 * 1024127/** Bornes de taille (octets) : petit < 100 Ko, moyen 100 Ko – 1 Mo, grand 1 – 10 Mo, très grand > 10 Mo. */128export function sizeBounds(s: SizeFilter): { min_size?: number; max_size?: number } {129 switch (s) {130 case "small": return { max_size: 100 * 1024 - 1 }131 case "medium": return { min_size: 100 * 1024, max_size: MB - 1 }132 case "large": return { min_size: MB, max_size: 10 * MB - 1 }133 case "huge": return { min_size: 10 * MB }134 default: return {}135 }136}137export const GALLERY_PAGE = 60138export function galleryParams(f: GalleryFilter, tz: string, cursor?: string | null, limit = GALLERY_PAGE): Params {139 return {140 mailboxes: f.mailbox ?? undefined, kind: f.kinds.length ? [...new Set(f.kinds)].join(",") : undefined, ...sizeBounds(f.size),141 q: f.q.trim().slice(0, 200), from: f.from.trim().slice(0, 200), after: f.date === "any" ? undefined : f.date, limit, cursor, tz,142 }143}144145// ---------------------------------------------------------------- sélection et archive ZIP146export const ZIP_MAX_ITEMS = 50147export const ZIP_MAX_BYTES = 200 * 1024 * 1024148export type ZipProblem = "empty" | "too_many" | "too_large" | null149export function zipProblem(items: Pick<AttachmentItem, "size">[]): ZipProblem {150 if (!items.length) return "empty"151 if (items.length > ZIP_MAX_ITEMS) return "too_many"152 if (items.reduce((n, a) => n + a.size, 0) > ZIP_MAX_BYTES) return "too_large"153 return null154}155export const zipBody = (items: AttachmentItem[], filename?: string) => ({156 items: items.map((a) => ({ mailbox_id: a.mailbox_id, email_id: a.email_id, blob_id: a.blob_id, name: a.name.slice(0, 255) })),157 ...(filename ? { filename: filename.slice(0, 100) } : {}),158})159/** Nom de fichier d'un en-tête Content-Disposition (`filename*=UTF-8''…` d'abord, puis `filename="…"`), sans chemin. */160export function filenameFromDisposition(header: string | null | undefined, fallback: string): string {161 const h = header ?? ""162 let name = ""163 const star = /filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(h)164 if (star) {165 try {166 name = decodeURIComponent(star[1].trim())167 } catch {168 name = ""169 }170 }171 if (!name) name = /filename\s*=\s*"([^"]*)"/.exec(h)?.[1] ?? /filename\s*=\s*([^;\s]+)/.exec(h)?.[1] ?? ""172 name = name.replace(/[\u0000-\u001f\u007f]/g, "").split(/[\\/]/).pop()?.trim() ?? ""173 return name || fallback174}175/** Remet un fichier au navigateur (téléchargement) à partir d'octets déjà reçus. */176export function saveBlob(blob: Blob, filename: string) {177 const url = URL.createObjectURL(blob)178 const a = document.createElement("a")179 a.href = url180 a.download = filename181 a.rel = "noopener"182 document.body.appendChild(a)183 a.click()184 a.remove()185 setTimeout(() => URL.revokeObjectURL(url), 30_000)186}187/** Demande l'archive et la remet au navigateur ; rend son nom. Les erreurs (413, 404, 429) sont classées par `NextError`. */188export async function downloadZip(items: AttachmentItem[]): Promise<string> {189 const r = await nx.raw("attachments/zip", { method: "POST", json: zipBody(items), headers: { accept: "application/zip" } })190 const name = filenameFromDisposition(r.headers.get("content-disposition"), "pieces-jointes.zip")191 saveBlob(new Blob([await r.arrayBuffer()], { type: "application/zip" }), name)192 return name193}194195// ---------------------------------------------------------------- état de la galerie196export interface GalleryState {197 filter: GalleryFilter198 items: AttachmentItem[]199 next: string | null200 status: "idle" | "loading" | "ready" | "error"201 error: NextErrorKind | null202 loadingMore: boolean203 selected: ReadonlySet<string>204}205const initial = (): GalleryState => ({ filter: emptyGalleryFilter(), items: [], next: null, status: "idle", error: null, loadingMore: false, selected: new Set() })206export const GA = createStore<GalleryState>(initial())207let gen = 0208let abort: AbortController | null = null209const userTz = (): string => {210 try {211 return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"212 } catch {213 return "UTC"214 }215}216type Page = { data: unknown; next_cursor: string | null }217const pageOf = (r: Page) => ({ items: (Array.isArray(r.data) ? r.data : []).map(normalizeAttachment).filter((a): a is AttachmentItem => a !== null), next: typeof r.next_cursor === "string" ? r.next_cursor : null })218219export async function loadGallery(): Promise<void> {220 const my = ++gen221 abort?.abort()222 const ctrl = (abort = new AbortController())223 GA.set({ status: GA.get().items.length ? GA.get().status : "loading", error: null, loadingMore: false })224 try {225 const p = pageOf(await nx.get<Page>("attachments", galleryParams(GA.get().filter, userTz()), ctrl.signal))226 if (my !== gen) return227 // la sélection ne garde que ce qui est encore affiché228 const keys = new Set(p.items.map(attachmentKey))229 GA.set({ items: p.items, next: p.next, status: "ready", error: null, selected: new Set([...GA.get().selected].filter((k) => keys.has(k))) })230 } catch (e) {231 if (my !== gen || isAbort(e)) return232 GA.set({ status: "error", error: toNextError(e).kind })233 }234}235export async function loadMoreGallery(): Promise<void> {236 const s = GA.get()237 if (!s.next || s.loadingMore || s.status !== "ready") return238 const my = gen239 GA.set({ loadingMore: true })240 try {241 const p = pageOf(await nx.get<Page>("attachments", galleryParams(s.filter, userTz(), s.next)))242 if (my !== gen) return243 const have = new Set(GA.get().items.map(attachmentKey))244 GA.set({ items: [...GA.get().items, ...p.items.filter((a) => !have.has(attachmentKey(a)))], next: p.next, loadingMore: false })245 } catch (e) {246 if (my !== gen) return247 GA.set({ loadingMore: false, error: toNextError(e).kind })248 }249}250export function setGalleryFilter(patch: Partial<GalleryFilter>) {251 GA.set({ filter: { ...GA.get().filter, ...patch }, items: [], next: null, status: "loading", selected: new Set() })252 void loadGallery()253}254export function toggleKind(kind: AttachmentKind) {255 const cur = GA.get().filter.kinds256 setGalleryFilter({ kinds: cur.includes(kind) ? cur.filter((k) => k !== kind) : [...cur, kind] })257}258export function toggleSelected(key: string) {259 const next = new Set(GA.get().selected)260 if (next.has(key)) next.delete(key)261 else next.add(key)262 GA.set({ selected: next })263}264export const clearSelected = () => GA.set({ selected: new Set() })265export const selectedItems = (s: GalleryState = GA.get()): AttachmentItem[] => s.items.filter((a) => s.selected.has(attachmentKey(a)))266export function resetGallery() {267 gen++268 abort?.abort()269 GA.set(initial())270}271272// ---------------------------------------------------------------- aperçu (un seul dialogue pour la galerie et le lecteur)273export const PV = createStore<{ items: PreviewItem[]; index: number; open: boolean }>({ items: [], index: 0, open: false })274export function openPreview(items: PreviewItem[], index: number) {275 if (!items.length) return276 PV.set({ items, index: Math.min(Math.max(0, index), items.length - 1), open: true })277}278export const closePreview = () => PV.set({ items: [], index: 0, open: false })279/** Pièce suivante / précédente, sans boucler. */280export function stepPreview(delta: number) {281 const s = PV.get()282 const index = Math.min(Math.max(0, s.index + delta), s.items.length - 1)283 if (index !== s.index) PV.set({ index })284}285286