SPB Git

Repository Public

search.ts 22.6 KB 336 lines typescript

1// SP Mail Next — recherche unifiée (une syntaxe pour les trois clients, toutes les boîtes en parallèle, fusion par date à curseur stable),2// index des pièces jointes et téléchargement groupé en ZIP. Aucune copie du courrier en base : tout est requête JMAP.3import type { FastifyInstance } from "fastify"4import { pipeline, Readable, Transform } from "node:stream"5import zlib from "node:zlib"6import { z } from "zod"7import { sql } from "../db.js"8import { downloadBlob, folders, jmapOk, type Folder } from "../mailjmap.js"9import { bad, parse, rateLimit, zUuid } from "../util.js"10import { decodeCursor, encodeCursor, filterHash } from "../v1/ids.js"11import { nextUser, userMailbox, userMailboxes, type OwnedMailbox } from "./common.js"12import { compileFilter, fold, parseQuery, resolveDate, validTz, type Filter, type Parsed, type QueryError } from "./query.js"1314// ------------------------------------------------------------------ parcours d'une boîte et fusion entre boîtes15type JEmail = Record<string, any> & { id: string }16type Cursor = { t: string; k: string; h: string }17type Row<T> = { t: number; k: string; mb: OwnedMailbox; v: T }18type Part<T> = { items: Row<T>[]; exhausted: boolean; frontier: number }19const SCAN_CAP = 300020const jmapDate = (ms: number) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z")21const afterCursor = (c: Cursor | null, t: number, k: string) => !c || t < Date.parse(c.t) || (t === Date.parse(c.t) && k > c.k)22const and = (...c: Filter[]): Filter => { const real = c.filter((x) => Object.keys(x).length); return real.length === 0 ? {} : real.length === 1 ? real[0] : { operator: "AND", conditions: real } }2324/**25 * Lit une boîte du plus récent au plus ancien et rend au moins `need` éléments situés après le curseur (ou tout ce qui reste).26 * `expand` transforme un message en zéro, un ou plusieurs éléments (un message, ou chacune de ses pièces jointes).27 * Fils regroupés (`collapse`) : le parcours repart du début à chaque page, pour qu'un fil déjà rendu ne réapparaisse jamais plus bas.28 */29async function scan<T>(mb: OwnedMailbox, filter: Filter, cursor: Cursor | null, need: number, o: { collapse?: boolean; props: string[]; expand: (e: JEmail) => { sub: string; v: T }[] }): Promise<Part<T>> {30  const ct = cursor ? Date.parse(cursor.t) : 031  const f = cursor && !o.collapse ? and(filter, { before: jmapDate(Math.floor(ct / 1000) * 1000 + 1000) }) : filter32  const items: Row<T>[] = []33  const page = Math.min(200, Math.max(50, need + 10))34  let position = 0, frontier = 0, exhausted = false35  for (;;) {36    const res = await jmapOk(mb, [37      ["Email/query", { filter: f, sort: [{ property: "receivedAt", isAscending: false }], position, limit: page, ...(o.collapse ? { collapseThreads: true } : {}) }, "q"],38      ["Email/get", { "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: o.props }, "g"],39    ])40    const ids = res[0].ids as string[]41    if (!ids.length) { exhausted = true; break }42    const byId = new Map((res[1].list as JEmail[]).map((e) => [e.id, e]))43    for (const id of ids) {44      const e = byId.get(id)45      if (!e) continue46      const t = Date.parse(e.receivedAt)47      frontier = t48      for (const x of o.expand(e)) {49        const k = `${mb.id}:${e.id}${x.sub}`50        if (afterCursor(cursor, t, k)) items.push({ t, k, mb, v: x.v })51      }52    }53    position += ids.length54    if (ids.length < page) { exhausted = true; break }55    // assez d'éléments, et toutes les égalités d'horodatage du dernier retenu ont été vues56    if (items.length >= need && frontier < items[need - 1].t) break57    if (position >= SCAN_CAP) { if (o.collapse) exhausted = true; break }58  }59  return { items, exhausted, frontier }60}6162/** Fusionne les parcours par date décroissante ; le curseur rendu désigne le dernier élément émis (ou la frontière de lecture). */63function merge<T>(parts: Part<T>[], limit: number, h: string): { out: Row<T>[]; next: string | null } {64  // On ne peut émettre que ce qui est plus récent que la frontière de lecture de chaque boîte non épuisée.65  const bound = Math.max(0, ...parts.filter((x) => !x.exhausted).map((x) => x.frontier))66  const merged = parts.flatMap((x) => x.items).sort((a, b) => b.t - a.t || (a.k < b.k ? -1 : 1))67  const anyOpen = parts.some((x) => !x.exhausted)68  const safe = anyOpen ? merged.filter((i) => i.t > bound) : merged69  const out = safe.slice(0, limit)70  let next: string | null = null71  if (safe.length > limit) next = encodeCursor({ t: new Date(out[out.length - 1].t).toISOString(), k: out[out.length - 1].k, h })72  else if (anyOpen) next = encodeCursor({ t: new Date(bound).toISOString(), k: "", h })73  return { out, next }74}75const readCursor = (raw: string | undefined, h: string) => decodeCursor<Cursor>(raw, (c) => typeof c.t === "string" && typeof c.k === "string" && c.h === h && !Number.isNaN(Date.parse(c.t)))7677/** `all` (ou vide) = toutes les boîtes lisibles ; sinon une liste d'identifiants, chacun revérifié (404 pour celui d'autrui). */78export async function selectMailboxes(userId: string, spec: string | undefined): Promise<OwnedMailbox[]> {79  const all = await userMailboxes(userId)80  const s = (spec ?? "all").trim()81  if (!s || s === "all") return all82  const ids = [...new Set(s.split(",").map((x) => x.trim()).filter(Boolean))]83  if (ids.length > 100) throw bad("invalid_request", 400, "too many mailboxes")84  return ids.map((id) => {85    const mb = zUuid.safeParse(id).success ? all.find((m) => m.id === id) : undefined86    if (!mb) throw bad("not_found", 404)87    return mb88  })89}9091// ------------------------------------------------------------------ recherche de messages92const SUMMARY_PROPS = ["threadId", "mailboxIds", "keywords", "from", "to", "subject", "preview", "receivedAt", "size", "hasAttachment"]93type JAddr = { email?: string | null; name?: string | null }94const addrs = (l: JAddr[] | null | undefined) => (l ?? []).map((a) => ({ email: String(a.email ?? ""), name: a.name ?? null }))95export function presentSummary(mb: OwnedMailbox, e: JEmail, fl: Folder[]) {96  const boxIds = Object.keys(e.mailboxIds ?? {})97  return {98    mailbox_id: mb.id, email_id: e.id, thread_id: e.threadId as string, from: addrs(e.from), to: addrs(e.to), subject: (e.subject ?? "") as string, preview: (e.preview ?? "") as string,99    received_at: e.receivedAt as string, keywords: Object.keys(e.keywords ?? {}).sort(), mailbox_ids: boxIds, has_attachment: !!e.hasAttachment, size: (e.size ?? 0) as number,100    folder_roles: [...new Set(boxIds.map((id) => fl.find((f) => f.id === id)?.role).filter((r): r is string => !!r))],101  }102}103export type MessageSummary = ReturnType<typeof presentSummary>104105async function labelMap(userId: string): Promise<Map<string, string>> {106  return new Map((await sql`select name, keyword from labels where user_id = ${userId}`).map((l) => [fold(l.name as string), l.keyword as string]))107}108109export type SearchOptions = { q: string; mailboxes?: string; limit: number; cursor?: string; threads?: boolean; tz?: string }110/** Recherche dans les boîtes choisies, en parallèle. Sert aussi aux dossiers intelligents et au tableau de bord. */111export async function searchMessages(userId: string, o: SearchOptions): Promise<{ data: MessageSummary[]; next_cursor: string | null; parsed: Parsed }> {112  const boxes = await selectMailboxes(userId, o.mailboxes)113  const tz = validTz(o.tz)114  const parsed = parseQuery(o.q, { tz })115  const labels = await labelMap(userId)116  const collapse = !!o.threads117  // Le curseur est lié à la requête (texte, boîtes, regroupement) : il est refusé pour toute autre.118  const h = filterHash({ q: o.q, boxes: boxes.map((b) => b.id), collapse, tz })119  const cursor = readCursor(o.cursor, h)120  const plans = await Promise.all(boxes.map(async (mb) => {121    const fl = await folders(mb)122    return { mb, fl, ...compileFilter(parsed.terms, { folders: fl, labels }) }123  }))124  // Erreurs de résolution : étiquette inconnue (une fois) ; dossier inconnu seulement si AUCUNE boîte ne le possède.125  const errors: QueryError[] = [...parsed.errors]126  const seen = new Set<string>()127  for (const p of plans) for (const e of p.errors) {128    const key = `${e.code}:${e.start}`129    if (seen.has(key) || (e.code === "unknown_folder" && !plans.every((x) => x.errors.some((y) => y.code === e.code && y.start === e.start)))) continue130    seen.add(key)131    errors.push(e)132  }133  const needNames = plans.some((p) => p.post)134  const parts = await Promise.all(plans.map((p) => p.filter === null ? Promise.resolve<Part<JEmail>>({ items: [], exhausted: true, frontier: 0 }) : scan<JEmail>(p.mb, p.filter, cursor, o.limit + 1, {135    collapse, props: needNames ? [...SUMMARY_PROPS, "attachments"] : SUMMARY_PROPS, expand: (e) => (!p.post || p.post(e as { attachments?: { name?: string | null }[] }) ? [{ sub: "", v: e }] : []),136  })))137  const { out, next } = merge(parts, o.limit, h)138  const flOf = new Map(plans.map((p) => [p.mb.id, p.fl]))139  return { data: out.map((r) => presentSummary(r.mb, r.v, flOf.get(r.mb.id) ?? [])), next_cursor: next, parsed: { terms: parsed.terms, filters: parsed.filters, errors } }140}141142// ------------------------------------------------------------------ index des pièces jointes143export const ATTACHMENT_KINDS = ["image", "pdf", "document", "spreadsheet", "archive", "audio", "video", "other"] as const144export type AttachmentKind = (typeof ATTACHMENT_KINDS)[number]145const EXT: Record<string, AttachmentKind> = {146  png: "image", jpg: "image", jpeg: "image", gif: "image", webp: "image", heic: "image", heif: "image", bmp: "image", tif: "image", tiff: "image", svg: "image", avif: "image",147  pdf: "pdf",148  doc: "document", docx: "document", odt: "document", rtf: "document", txt: "document", md: "document", pages: "document", ppt: "document", pptx: "document", odp: "document", key: "document", tex: "document", html: "document", htm: "document",149  xls: "spreadsheet", xlsx: "spreadsheet", ods: "spreadsheet", csv: "spreadsheet", tsv: "spreadsheet", numbers: "spreadsheet",150  zip: "archive", gz: "archive", tgz: "archive", tar: "archive", bz2: "archive", xz: "archive", "7z": "archive", rar: "archive",151  mp3: "audio", m4a: "audio", wav: "audio", flac: "audio", ogg: "audio", aac: "audio", opus: "audio",152  mp4: "video", mov: "video", mkv: "video", webm: "video", avi: "video", m4v: "video",153}154/** Famille d'une pièce jointe d'après son type MIME, puis son extension quand le type est générique. */155export function attachmentKind(type: string, name: string): AttachmentKind {156  const t = type.toLowerCase()157  if (t.startsWith("image/")) return "image"158  if (t === "application/pdf") return "pdf"159  if (t.startsWith("audio/")) return "audio"160  if (t.startsWith("video/")) return "video"161  if (/spreadsheet|ms-excel|^text\/csv$|^text\/tab-separated-values$|numbers/.test(t)) return "spreadsheet"162  if (/wordprocessing|msword|opendocument\.text|presentation|powerpoint|^application\/rtf$|^text\/|pages|keynote/.test(t)) return "document"163  if (/zip|gzip|x-tar|x-7z|x-rar|x-bzip|x-xz|compressed/.test(t)) return "archive"164  return EXT[name.toLowerCase().split(".").pop() ?? ""] ?? "other"165}166const INLINE_OK = /^image\/(png|jpeg|gif|webp)$/ // les seuls types que la route de téléchargement accepte d'afficher (jmap.ts)167type JPart = { partId?: string; blobId: string; name?: string | null; type?: string | null; size?: number; cid?: string | null; disposition?: string | null }168/** Vraies pièces jointes d'un message : les images incorporées au corps (cid, en ligne) n'en sont pas. */169export const realAttachments = (e: JEmail): JPart[] => ((e.attachments ?? []) as JPart[]).filter((a) => a.blobId && !(a.cid && a.disposition !== "attachment" && String(a.type ?? "").startsWith("image/")))170function presentAttachment(mb: OwnedMailbox, e: JEmail, a: JPart) {171  const name = a.name || "attachment"172  const type = (a.type || "application/octet-stream").toLowerCase()173  return {174    mailbox_id: mb.id, email_id: e.id, thread_id: e.threadId as string, blob_id: a.blobId, part_id: a.partId ?? null, name, type, size: a.size ?? 0, kind: attachmentKind(type, name),175    from: addrs(e.from), subject: (e.subject ?? "") as string, received_at: e.receivedAt as string,176    download_url: `/api/jmap/${mb.id}/download/${encodeURIComponent(mb.stalwart_id)}/${encodeURIComponent(a.blobId)}/${encodeURIComponent(name)}?accept=${encodeURIComponent(type)}`,177    inline_ok: INLINE_OK.test(type),178  }179}180export type AttachmentItem = ReturnType<typeof presentAttachment>181export type AttachmentOptions = { mailboxes?: string; kinds?: AttachmentKind[]; minSize?: number; maxSize?: number; q?: string; from?: string; after?: string; before?: string; limit: number; cursor?: string; tz?: string }182183function dateBound(op: "before" | "after", v: string | undefined, tz: string): string | undefined {184  if (!v) return undefined185  const t = resolveDate(op, v, new Date(), tz) ?? (Number.isNaN(Date.parse(v)) ? null : Date.parse(v))186  if (t === null) throw bad("invalid_request", 400, `${op}: expected YYYY-MM-DD, an ISO 8601 date or a duration such as 30d`)187  return jmapDate(t)188}189/** Pièces jointes des boîtes choisies, de la plus récente à la plus ancienne (corbeille et indésirables exclus). */190export async function listAttachments(userId: string, o: AttachmentOptions): Promise<{ data: AttachmentItem[]; next_cursor: string | null }> {191  const boxes = await selectMailboxes(userId, o.mailboxes)192  const tz = validTz(o.tz)193  const base: Filter[] = [{ hasAttachment: true }]194  if (o.from) base.push({ from: o.from })195  const after = dateBound("after", o.after, tz), before = dateBound("before", o.before, tz)196  if (after) base.push({ after })197  if (before) base.push({ before })198  const needle = o.q ? fold(o.q) : ""199  const h = filterHash({ a: 1, boxes: boxes.map((b) => b.id), kinds: o.kinds ?? null, min: o.minSize ?? null, max: o.maxSize ?? null, q: needle, from: o.from ?? null, after: o.after ?? null, before: o.before ?? null, tz })200  const cursor = readCursor(o.cursor, h)201  const parts = await Promise.all(boxes.map(async (mb) => {202    const hidden = (await folders(mb)).filter((f) => f.role === "trash" || f.role === "junk").map((f) => f.id)203    return scan<AttachmentItem>(mb, and(...base, hidden.length ? { inMailboxOtherThan: hidden } : {}), cursor, o.limit + 1, {204      props: ["threadId", "from", "subject", "receivedAt", "attachments"],205      expand: (e) => realAttachments(e).map((a, i) => ({ sub: `:${String(i).padStart(3, "0")}`, v: presentAttachment(mb, e, a) }))206        .filter((x) => (!o.kinds?.length || o.kinds.includes(x.v.kind)) && (o.minSize === undefined || x.v.size >= o.minSize) && (o.maxSize === undefined || x.v.size <= o.maxSize) && (!needle || fold(x.v.name).includes(needle))),207    })208  }))209  const { out, next } = merge(parts, o.limit, h)210  return { data: out.map((r) => r.v), next_cursor: next }211}212213// ------------------------------------------------------------------ archive ZIP en flux (sans dépendance : node:zlib)214export const ZIP_MAX_ITEMS = 50215export const ZIP_MAX_BYTES = 200 * 1024 * 1024216/** Nom d'entrée sûr : ni chemin, ni caractère de contrôle ; les doublons reçoivent « (2) », « (3) »… */217export function zipNames(names: string[]): string[] {218  const used = new Set<string>()219  return names.map((raw) => {220    const clean = (raw.normalize("NFC").replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/:*?"<>|]/g, "_").replace(/^\.+/, "").trim() || "attachment").slice(0, 180)221    const dot = clean.lastIndexOf(".")222    const [stem, ext] = dot > 0 ? [clean.slice(0, dot), clean.slice(dot)] : [clean, ""]223    let name = clean224    for (let i = 2; used.has(name.toLowerCase()); i++) name = `${stem} (${i})${ext}`225    used.add(name.toLowerCase())226    return name227  })228}229/**230 * Écrit une archive ZIP entrée par entrée, sans rien tamponner : en-tête local, données compressées (deflate), descripteur de données231 * (CRC et tailles connus seulement après lecture), puis répertoire central. Noms en UTF-8 (drapeau 11).232 */233export async function* zipStream(entries: { name: string; open: () => Promise<Readable> }[]): AsyncGenerator<Buffer> {234  const central: Buffer[] = []235  let offset = 0236  const now = new Date()237  const time = (now.getHours() << 11) | (now.getMinutes() << 5) | (now.getSeconds() >> 1)238  const date = ((Math.max(1980, now.getFullYear()) - 1980) << 9) | ((now.getMonth() + 1) << 5) | now.getDate()239  for (const en of entries) {240    const name = Buffer.from(en.name, "utf8")241    const local = Buffer.alloc(30)242    local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0808, 6); local.writeUInt16LE(8, 8)243    local.writeUInt16LE(time, 10); local.writeUInt16LE(date, 12); local.writeUInt16LE(name.length, 26)244    const start = offset245    yield local246    yield name247    offset += 30 + name.length248    let crc = 0, size = 0, packed = 0249    const tap = new Transform({ transform(chunk: Buffer, _enc, cb) { crc = zlib.crc32(chunk, crc); size += chunk.length; cb(null, chunk) } })250    const deflate = pipeline(await en.open(), tap, zlib.createDeflateRaw({ level: 1 }), () => {})251    for await (const chunk of deflate) { packed += (chunk as Buffer).length; yield chunk as Buffer }252    const desc = Buffer.alloc(16)253    desc.writeUInt32LE(0x08074b50, 0); desc.writeUInt32LE(crc >>> 0, 4); desc.writeUInt32LE(packed, 8); desc.writeUInt32LE(size, 12)254    yield desc255    offset += packed + 16256    const c = Buffer.alloc(46)257    c.writeUInt32LE(0x02014b50, 0); c.writeUInt16LE(0x0314, 4); c.writeUInt16LE(20, 6); c.writeUInt16LE(0x0808, 8); c.writeUInt16LE(8, 10)258    c.writeUInt16LE(time, 12); c.writeUInt16LE(date, 14); c.writeUInt32LE(crc >>> 0, 16); c.writeUInt32LE(packed, 20); c.writeUInt32LE(size, 24)259    c.writeUInt16LE(name.length, 28); c.writeUInt32LE((0o100644 << 16) >>> 0, 38); c.writeUInt32LE(start, 42)260    central.push(c, name)261  }262  const dir = Buffer.concat(central)263  const end = Buffer.alloc(22)264  end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(entries.length, 8); end.writeUInt16LE(entries.length, 10); end.writeUInt32LE(dir.length, 12); end.writeUInt32LE(offset, 16)265  yield dir266  yield end267}268269// ------------------------------------------------------------------ routes270const zFlag = z.enum(["0", "1", "true", "false"]).transform((v) => v === "1" || v === "true")271const zSize = z.coerce.number().int().min(0).max(1e12)272273export function searchRoutes(app: FastifyInstance) {274  app.get("/api/next/search", async (req) => {275    const a = await nextUser(req, "next-search", 240)276    const q = parse(z.object({277      q: z.string().max(4000).default(""), mailboxes: z.string().max(4000).optional(), limit: z.coerce.number().int().min(1).max(100).default(50),278      cursor: z.string().max(2000).optional(), threads: zFlag.optional(), tz: z.string().max(64).optional(),279    }), req.query)280    return searchMessages(a.userId, q)281  })282283  // Forme analysée d'une requête (pastilles, validation en cours de frappe). Ne refuse jamais une entrée : les défauts sont dans `errors`.284  app.post("/api/next/search/parse", async (req) => {285    const a = await nextUser(req, "next-search", 240)286    const body = (req.body && typeof req.body === "object" ? req.body : {}) as { q?: unknown; tz?: unknown }287    const parsed = parseQuery(body.q, { tz: typeof body.tz === "string" ? body.tz : undefined })288    const labels = await labelMap(a.userId)289    const unknown = compileFilter(parsed.terms.filter((t) => t.op === "label"), { folders: [], labels }).errors290    return { terms: parsed.terms, filters: parsed.filters, errors: [...parsed.errors, ...unknown] }291  })292293  app.get("/api/next/attachments", async (req) => {294    const a = await nextUser(req, "next-search", 240)295    const q = parse(z.object({296      mailboxes: z.string().max(4000).optional(), kind: z.string().max(200).optional(), min_size: zSize.optional(), max_size: zSize.optional(), q: z.string().trim().max(200).optional(),297      from: z.string().trim().max(200).optional(), after: z.string().max(40).optional(), before: z.string().max(40).optional(),298      limit: z.coerce.number().int().min(1).max(200).default(50), cursor: z.string().max(2000).optional(), tz: z.string().max(64).optional(),299    }), req.query)300    const kinds = (q.kind ?? "").split(",").map((k) => k.trim()).filter(Boolean)301    if (kinds.some((k) => !(ATTACHMENT_KINDS as readonly string[]).includes(k))) throw bad("invalid_request", 400, `kind: one of ${ATTACHMENT_KINDS.join(", ")}`)302    return listAttachments(a.userId, { mailboxes: q.mailboxes, kinds: kinds as AttachmentKind[], minSize: q.min_size, maxSize: q.max_size, q: q.q || undefined, from: q.from || undefined, after: q.after, before: q.before, limit: q.limit, cursor: q.cursor, tz: q.tz })303  })304305  app.post("/api/next/attachments/zip", async (req, reply) => {306    const a = await nextUser(req)307    rateLimit(`next-zip:${a.userId}`, 6, 60_000)308    const b = parse(z.object({309      items: z.array(z.object({ mailbox_id: zUuid, email_id: z.string().regex(/^[A-Za-z0-9_-]{1,255}$/), blob_id: z.string().regex(/^[A-Za-z0-9_-]{1,600}$/), name: z.string().max(255).optional() }).strict()).min(1).max(ZIP_MAX_ITEMS),310      filename: z.string().trim().min(1).max(100).optional(),311    }).strict(), req.body)312    // Chaque élément est revérifié : la boîte est lisible par l'utilisateur ET le blob est bien une pièce jointe de ce message.313    const boxes = new Map<string, OwnedMailbox>()314    for (const it of b.items) if (!boxes.has(it.mailbox_id)) boxes.set(it.mailbox_id, await userMailbox(a.userId, it.mailbox_id))315    const parts = new Map<string, JPart[]>()316    await Promise.all([...boxes.values()].map(async (mb) => {317      const ids = [...new Set(b.items.filter((i) => i.mailbox_id === mb.id).map((i) => i.email_id))]318      const [r] = await jmapOk(mb, [["Email/get", { ids, properties: ["attachments"] }]])319      for (const e of r.list as JEmail[]) parts.set(`${mb.id}:${e.id}`, (e.attachments ?? []) as JPart[])320    }))321    let total = 0322    const found = b.items.map((it) => {323      const part = parts.get(`${it.mailbox_id}:${it.email_id}`)?.find((p) => p.blobId === it.blob_id)324      if (!part) throw bad("not_found", 404, "An item is not an attachment of that message")325      total += part.size ?? 0326      return { mb: boxes.get(it.mailbox_id)!, part, name: it.name || part.name || "attachment" }327    })328    if (total > ZIP_MAX_BYTES) throw bad("too_large", 413, `The selected attachments exceed ${ZIP_MAX_BYTES / 1024 / 1024} MB`)329    const names = zipNames(found.map((f) => f.name))330    const entries = found.map((f, i) => ({ name: names[i], open: async () => Readable.fromWeb((await downloadBlob(f.mb, f.part.blobId, "blob", f.part.type || "application/octet-stream")).body as never) }))331    const file = (b.filename ?? "pieces-jointes").replace(/[^\w.\- ()À-ɏ]/g, "_").replace(/\.zip$/i, "")332    reply.header("content-type", "application/zip").header("content-disposition", `attachment; filename*=UTF-8''${encodeURIComponent(`${file}.zip`)}`).header("x-content-type-options", "nosniff")333    return reply.send(Readable.from(zipStream(entries)))334  })335}336
Files main
Menu

Theme