SPB Git

Repository Public

vcard.ts 9.0 KB 171 lines typescript

1// SP Mail Next — vCard 3.0 / 4.0 (et 2.1 toléré) : lecture et écriture PURES, sans dépendance. Champs retenus : FN, N, EMAIL, TEL, ORG, TITLE, NOTE.2// Lecture : dépliage des lignes, quoted-printable (avec retours souples), jeux de caractères UTF-8 / Latin-1, échappements. Jamais d'exception sur une entrée abîmée.34export type VCard = {5  name: string6  emails: { email: string; label: string | null }[]7  phones: { number: string; label: string | null }[]8  organization: string | null9  title: string | null10  notes: string | null11}12export const VCARD_MAX_CARDS = 500013const EMAIL_RE = /^[^\s@<>"]+@[^\s@<>"]+\.[^\s@<>"]+$/1415// ------------------------------------------------------------------ lecture16/** Octets reçus → texte : UTF-8 si valide (BOM retiré), sinon Latin-1 (anciens exports). */17export function decodeVcf(buf: Buffer): string {18  try { return new TextDecoder("utf-8", { fatal: true }).decode(buf).replace(/^\uFEFF/, "") } catch { return buf.toString("latin1") }19}20function decodeQuotedPrintable(s: string, charset: string): string {21  const bytes: number[] = []22  for (let i = 0; i < s.length; i++) {23    if (s[i] === "=" && /^[0-9A-Fa-f]{2}$/.test(s.slice(i + 1, i + 3))) { bytes.push(parseInt(s.slice(i + 1, i + 3), 16)); i += 2 }24    else for (const b of Buffer.from(s[i], "utf8")) bytes.push(b)25  }26  const buf = Buffer.from(bytes)27  if (/^(iso-8859-1|latin-?1|windows-1252|cp1252)$/i.test(charset)) return buf.toString("latin1")28  try { return new TextDecoder("utf-8", { fatal: true }).decode(buf) } catch { return buf.toString("latin1") }29}30/** Sépare sur un délimiteur non échappé, puis retire les échappements vCard (\n, \, \; \\). */31function splitEscaped(s: string, sep: string): string[] {32  const out: string[] = []33  let cur = ""34  for (let i = 0; i < s.length; i++) {35    if (s[i] === "\\" && i + 1 < s.length) { const n = s[++i]; cur += n === "n" || n === "N" ? "\n" : n }36    else if (s[i] === sep) { out.push(cur); cur = "" }37    else cur += s[i]38  }39  out.push(cur)40  return out41}42const unescape = (s: string) => splitEscaped(s, "\u0000").join("")43const clean = (s: string, max: number) => s.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "").replace(/\r/g, "").trim().slice(0, max)44const oneLine = (s: string, max: number) => clean(s, max * 2).replace(/\s+/g, " ").slice(0, max)4546type Line = { name: string; params: Map<string, string[]>; value: string }47function parseLine(raw: string): Line | null {48  // « : » qui termine le nom et ses paramètres : le premier hors guillemets49  let inQuote = false, colon = -150  for (let i = 0; i < raw.length; i++) {51    if (raw[i] === '"') inQuote = !inQuote52    else if (raw[i] === ":" && !inQuote) { colon = i; break }53  }54  if (colon < 1) return null55  const head = raw.slice(0, colon).split(";")56  const name = (head[0].includes(".") ? head[0].slice(head[0].lastIndexOf(".") + 1) : head[0]).trim().toUpperCase() // « item1.EMAIL » → EMAIL57  const params = new Map<string, string[]>()58  for (const p of head.slice(1)) {59    const eq = p.indexOf("=")60    // vCard 2.1 : paramètre nu (« TEL;WORK;VOICE », « ;QUOTED-PRINTABLE »)61    const [k, v] = eq < 0 ? [/^(QUOTED-PRINTABLE|BASE64|B)$/i.test(p.trim()) ? "ENCODING" : "TYPE", p] : [p.slice(0, eq).trim().toUpperCase(), p.slice(eq + 1)]62    const vals = v.split(",").map((x) => x.trim().replace(/^"|"$/g, "")).filter(Boolean)63    params.set(k, [...(params.get(k) ?? []), ...vals])64  }65  return { name, params, value: raw.slice(colon + 1) }66}67const LABELS: Record<string, string> = { work: "work", home: "home", cell: "mobile", mobile: "mobile", iphone: "mobile", fax: "fax", main: "main", other: "other", pager: "pager" }68function labelOf(params: Map<string, string[]>): string | null {69  for (const t of params.get("TYPE") ?? []) { const l = LABELS[t.toLowerCase()]; if (l) return l }70  return null71}7273/** Lit un fichier .vcf (une ou plusieurs fiches). Les fiches sans nom, adresse ni téléphone sont comptées dans `skipped`. */74export function parseVcards(text: string): { cards: VCard[]; skipped: number } {75  // Dépliage (RFC 6350 §3.2) : une ligne qui commence par un blanc continue la précédente.76  const physical = text.replace(/\r\n?/g, "\n").split("\n")77  const lines: string[] = []78  for (const l of physical) {79    if ((l.startsWith(" ") || l.startsWith("\t")) && lines.length) lines[lines.length - 1] += l.slice(1)80    else lines.push(l)81  }82  const cards: VCard[] = []83  let skipped = 084  let cur: VCard | null = null85  let structured = ""86  for (let i = 0; i < lines.length; i++) {87    let raw = lines[i]88    if (!raw.trim()) continue89    // Quoted-printable (vCard 2.1) : « = » en fin de ligne = retour souple, la valeur continue à la ligne suivante.90    if (/ENCODING=QUOTED-PRINTABLE|;QUOTED-PRINTABLE/i.test(raw.slice(0, raw.indexOf(":") + 1))) while (raw.endsWith("=") && i + 1 < lines.length) raw = raw.slice(0, -1) + lines[++i]91    const line = parseLine(raw)92    if (!line) continue93    if (line.name === "BEGIN" && /^vcard$/i.test(line.value.trim())) { cur = { name: "", emails: [], phones: [], organization: null, title: null, notes: null }; structured = ""; continue }94    if (line.name === "END" && /^vcard$/i.test(line.value.trim())) {95      if (cur) {96        if (!cur.name) cur.name = structured97        if (cur.name || cur.emails.length || cur.phones.length) { if (cards.length < VCARD_MAX_CARDS) cards.push(cur); else skipped++ }98        else skipped++99      }100      cur = null101      continue102    }103    if (!cur) continue104    const enc = (line.params.get("ENCODING")?.[0] ?? "").toUpperCase()105    if (enc === "B" || enc === "BASE64") continue // photo, clé… : ignorés106    const value = enc === "QUOTED-PRINTABLE" ? decodeQuotedPrintable(line.value, line.params.get("CHARSET")?.[0] ?? "utf-8") : line.value107    switch (line.name) {108      case "FN": if (!cur.name) cur.name = oneLine(unescape(value), 120); break109      case "N": {110        const [family = "", given = "", additional = "", prefix = "", suffix = ""] = splitEscaped(value, ";").map((x) => x.trim())111        structured = oneLine([prefix, given, additional, family, suffix].filter(Boolean).join(" "), 120)112        break113      }114      case "EMAIL": {115        const email = unescape(value).trim().replace(/^mailto:/i, "").toLowerCase()116        if (EMAIL_RE.test(email) && email.length <= 254 && !cur.emails.some((e) => e.email === email) && cur.emails.length < 20) cur.emails.push({ email, label: labelOf(line.params) })117        break118      }119      case "TEL": {120        const number = oneLine(unescape(value).replace(/^tel:/i, ""), 40)121        if (number && !cur.phones.some((p) => p.number === number) && cur.phones.length < 20) cur.phones.push({ number, label: labelOf(line.params) })122        break123      }124      case "ORG": if (!cur.organization) cur.organization = oneLine(splitEscaped(value, ";").map((x) => x.trim()).filter(Boolean).join(", "), 160) || null; break125      case "TITLE": if (!cur.title) cur.title = oneLine(unescape(value), 160) || null; break126      case "NOTE": if (!cur.notes) cur.notes = clean(unescape(value), 4000) || null; break127    }128  }129  return { cards, skipped }130}131132// ------------------------------------------------------------------ écriture (vCard 3.0, UTF-8)133const escape = (s: string) => s.replace(/\\/g, "\\\\").replace(/\r?\n/g, "\\n").replace(/,/g, "\\,").replace(/;/g, "\\;")134/** Pliage à 75 octets sans couper un caractère UTF-8 (RFC 2426 §2.6). */135function foldLine(line: string): string {136  const out: string[] = []137  let cur = "", bytes = 0138  for (const ch of line) {139    const n = Buffer.byteLength(ch, "utf8")140    if (bytes + n > (out.length ? 74 : 75)) { out.push(cur); cur = ""; bytes = 0 }141    cur += ch142    bytes += n143  }144  out.push(cur)145  return out.join("\r\n ")146}147const typeOf = (label: string | null | undefined, kind: "EMAIL" | "TEL") => {148  const l = (label ?? "").toLowerCase()149  const t = l === "mobile" ? "CELL" : /^[a-z]{1,12}$/.test(l) ? l.toUpperCase() : ""150  return kind === "EMAIL" ? `;TYPE=INTERNET${t ? `,${t}` : ""}` : t ? `;TYPE=${t}` : ""151}152export function writeVcards(cards: VCard[]): string {153  const out: string[] = []154  for (const c of cards) {155    const name = c.name || c.emails[0]?.email || c.phones[0]?.number || ""156    // N est obligatoire en 3.0 : dernier mot = nom de famille (approximation ; FN porte le nom exact).157    const words = c.name.trim().split(/\s+/).filter(Boolean)158    const family = words.length > 1 ? words[words.length - 1] : ""159    const given = words.length > 1 ? words.slice(0, -1).join(" ") : (words[0] ?? "")160    const lines = ["BEGIN:VCARD", "VERSION:3.0", `FN:${escape(name)}`, `N:${escape(family)};${escape(given)};;;`]161    for (const e of c.emails) lines.push(`EMAIL${typeOf(e.label, "EMAIL")}:${escape(e.email)}`)162    for (const p of c.phones) lines.push(`TEL${typeOf(p.label, "TEL")}:${escape(p.number)}`)163    if (c.organization) lines.push(`ORG:${escape(c.organization)}`)164    if (c.title) lines.push(`TITLE:${escape(c.title)}`)165    if (c.notes) lines.push(`NOTE:${escape(c.notes)}`)166    lines.push("END:VCARD")167    out.push(lines.map(foldLine).join("\r\n"))168  }169  return out.length ? `${out.join("\r\n")}\r\n` : ""170}171
Files main
Menu

Theme