Files
Claude 82da397c96
Some checks failed
Prüfung / tests (push) Has been cancelled
Prüfung / container (push) Has been cancelled
0.47.0: Kontaktmaske, übergeordnete Kontakte, freie Rollen, Ansprechpartner im Projekt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
2026-11-08 07:29:16 +00:00

271 lines
14 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Kontakte mit dem Handy abgleichen (Henning, 04.11.2026): vCard lesen und schreiben (RFC 2426/6350, wie Apple sie liefert).
// Seit 0.47 (Henning, 08.11.2026) eine Karte je Person mit allen Telefonnummern, E-Mail-Adressen und Adressen samt Typ;
// ORG ist der erste übergeordnete Kontakt. Alles andere in der Karte (Foto, Geburtstag, Webseiten) bleibt beim
// Zurückschreiben unverändert stehen, ebenso Nummern- oder Adresszeilen, solange sich an ihnen nichts geändert hat.
import { type Anschrift, type Nummer, ADRESS_TYPEN, EMAIL_TYPEN, TELEFON_TYPEN, listenBereinigt } from "./kontaktdaten.js";
export interface KontaktFelder {
name: string;
anrede: string | null;
titel: string | null;
/** ORG: bei Personen der erste übergeordnete Kontakt (sonst die frei eingetragene Firma), bei Firmen der eigene Name */
firma: string | null;
/** TITLE; undefined: im Programm nicht gepflegt (Person ohne übergeordneten Kontakt), die Karte behält ihre Angabe */
funktion?: string | null;
/** Firmenkarte (X-ABShowAs:COMPANY) */
gruppe: boolean;
telefone: Nummer[];
emails: Nummer[];
adressen: Anschrift[];
notiz: string | null;
}
interface Zeile {
/** Gruppe wie „item1“ bei Apple */
gruppe: string;
/** Name in Großbuchstaben zum Vergleichen */
name: string;
/** Name wie in der Karte geschrieben (X-ABLabel bleibt X-ABLabel) */
roh: string;
params: string;
wert: string;
}
/** Fortsetzungszeilen zusammenführen und in Eigenschaften zerlegen */
function zeilen(text: string): Zeile[] {
const roh = text.replace(/\r\n|\r/g, "\n").replace(/\n[ \t]/g, "").split("\n").filter((z) => z.trim());
return roh.map((z) => {
const i = z.indexOf(":");
const kopf = i < 0 ? z : z.slice(0, i);
const wert = i < 0 ? "" : z.slice(i + 1);
const [nameTeil, ...params] = kopf.split(";");
const punkt = nameTeil!.lastIndexOf(".");
const n = nameTeil!.slice(punkt + 1);
return { gruppe: punkt < 0 ? "" : nameTeil!.slice(0, punkt), name: n.toUpperCase(), roh: n, params: params.join(";"), wert };
});
}
const ent = (s: string) => s.replace(/\\n/gi, "\n").replace(/\\([,;\\])/g, "$1").trim();
const esc = (s: string) => s.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/([,;])/g, "\\$1");
/** Strukturierte Werte (N, ADR, ORG) an unmaskierten Semikolons teilen */
const teile = (s: string) => s.split(/(?<!\\);/).map(ent);
const leer = (s: string | undefined | null) => (s && s.trim() ? s.trim() : null);
/** Einzelne Karten aus einer .vcf-Datei mit vielen Kontakten */
export function kartenAus(text: string): string[] {
return [...text.replace(/\r\n|\r/g, "\n").matchAll(/BEGIN:VCARD[\s\S]*?END:VCARD/gi)].map((m) => m[0]);
}
/** Kontaktgruppe (Verteiler) der Nextcloud oder von Apple, kein Kontakt */
export const istVerteiler = (karte: string) => /^(X-ADDRESSBOOKSERVER-KIND|KIND):\s*group\s*$/im.test(karte.replace(/\r/g, ""));
export function uidVon(karte: string): string | null {
return leer(zeilen(karte).find((z) => z.name === "UID")?.wert);
}
/** Letzte Änderung laut Karte (REV), falls angegeben */
export function revVon(karte: string): string | null {
const w = leer(zeilen(karte).find((z) => z.name === "REV")?.wert);
if (!w) return null;
const m = /^(\d{4})-?(\d{2})-?(\d{2})(?:T(\d{2}):?(\d{2}):?(\d{2}))?/.exec(w);
return m ? `${m[1]}-${m[2]}-${m[3]}T${m[4] ?? "00"}:${m[5] ?? "00"}:${m[6] ?? "00"}Z` : null;
}
/** type=CELL;type=pref, TYPE="work,voice", PREF=1 oder TEL;CELL (vCard 2.1) */
function typen(z: Zeile): string[] {
const t: string[] = [];
for (const p of z.params.split(";").filter(Boolean)) {
const i = p.indexOf("=");
const k = (i < 0 ? "type" : p.slice(0, i)).toLowerCase();
const v = i < 0 ? p : p.slice(i + 1);
if (k === "type") t.push(...v.replace(/"/g, "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean));
if (k === "pref") t.push("pref");
}
return t;
}
/** Apple-Bezeichnung (_$!<Mobile>!$_) oder eigene Bezeichnung wie „Rechnungen“ */
function ausBezeichnung(l: string): string | undefined {
const m = /^_\$!<(.+)>!\$_$/.exec(l);
const s = (m ? m[1]! : l).toLowerCase();
if (/fax/.test(s)) return "fax";
if (/mobil|handy|iphone|cell/.test(s)) return "mobil";
if (/rechnung|buchhaltung|invoice|billing/.test(s)) return "rechnung";
if (/zentrale|main/.test(s)) return "zentrale";
if (/home|privat|zuhause/.test(s)) return "privat";
if (/work|büro|buero|geschäft|geschaeft|arbeit|firma/.test(s)) return "geschaeftlich";
if (/other|sonstig|andere/.test(s)) return "sonstige";
return undefined;
}
function typVon(z: Zeile, alle: Zeile[]): string {
const erlaubt = z.name === "TEL" ? TELEFON_TYPEN : z.name === "EMAIL" ? EMAIL_TYPEN : ADRESS_TYPEN;
const label = z.gruppe ? alle.find((x) => x.gruppe === z.gruppe && x.name === "X-ABLABEL")?.wert : undefined;
let typ = label ? ausBezeichnung(ent(label)) : undefined;
if (!typ) {
const t = typen(z);
const tel = z.name === "TEL";
typ = tel && t.includes("fax") ? "fax" : tel && t.some((x) => ["cell", "iphone", "mobile"].includes(x)) ? "mobil" : tel && t.includes("main") ? "zentrale"
: t.includes("work") ? "geschaeftlich" : t.includes("home") ? "privat" : "sonstige";
}
return erlaubt.includes(typ) ? typ : "sonstige";
}
const bevorzugt = (z: Zeile) => typen(z).includes("pref");
const ANREDE_WORTE: Record<string, string> = { herr: "Herr", hr: "Herr", frau: "Frau", fr: "Frau", familie: "Familie", eheleute: "Eheleute" };
export function felderAus(karte: string): KontaktFelder {
const z = zeilen(karte);
const erstes = (n: string) => z.find((x) => x.name === n);
const org = leer(teile(erstes("ORG")?.wert ?? "")[0]);
const n = teile(erstes("N")?.wert ?? "");
const namen = leer([n[1], n[2], n[0], n[4]].filter((x) => x && x.trim()).join(" "));
const fn = leer(ent(erstes("FN")?.wert ?? ""));
const gruppe = /^company$/i.test(erstes("X-ABSHOWAS")?.wert.trim() ?? "") || /^org$/i.test(erstes("KIND")?.wert.trim() ?? "") || (!namen && !!org && (fn ?? org) === org);
// Namenspräfix: Anrede und Titel
const praefix = (n[3] ?? "").split(/\s+/).filter(Boolean);
const anredeWort = praefix[0] ? ANREDE_WORTE[praefix[0].replace(/\.$/, "").toLowerCase()] : undefined;
const titel = leer((anredeWort ? praefix.slice(1) : praefix).join(" "));
const listen = listenBereinigt({
telefone: z.filter((x) => x.name === "TEL").map((x) => ({ typ: typVon(x, z), wert: ent(x.wert).replace(/^tel:/i, ""), haupt: bevorzugt(x) })),
emails: z.filter((x) => x.name === "EMAIL").map((x) => ({ typ: typVon(x, z), wert: ent(x.wert).replace(/^mailto:/i, ""), haupt: bevorzugt(x) })),
adressen: z.filter((x) => x.name === "ADR").map((x) => {
const a = teile(x.wert);
const [strasse = "", ...rest] = (a[2] ?? "").split("\n");
return {
typ: typVon(x, z), postfach: a[0] ?? "", strasse, zusatz: [...rest, a[1] ?? ""].map((s) => s.trim()).filter(Boolean).join(", "),
ort: a[3] ?? "", region: a[4] ?? "", plz: a[5] ?? "", land: a[6] ?? "", haupt: bevorzugt(x),
};
}),
});
return {
name: (gruppe ? org ?? fn : namen ?? fn ?? org) ?? "(ohne Namen)",
anrede: gruppe ? null : anredeWort ?? null,
titel: gruppe ? null : titel,
firma: org,
funktion: gruppe ? undefined : leer(ent(erstes("TITLE")?.wert ?? "")),
gruppe,
...listen,
notiz: leer(ent(erstes("NOTE")?.wert ?? "")),
};
}
const s = (x: unknown) => (x ?? "").toString().replace(/\s+/g, " ").trim();
const listenText = (f: Partial<KontaktFelder>) => {
const l = listenBereinigt({ telefone: f.telefone ?? [], emails: f.emails ?? [], adressen: f.adressen ?? [] });
return {
telefone: l.telefone.map((x) => [x.typ, s(x.wert), !!x.haupt]),
emails: l.emails.map((x) => [x.typ, s(x.wert).toLowerCase(), !!x.haupt]),
adressen: l.adressen.map((a) => [a.typ, s(a.strasse), s(a.zusatz), s(a.plz), s(a.ort), s(a.region), s(a.land), s(a.postfach), !!a.haupt]),
};
};
/** Gleiche Inhalte erkennen, ohne auf Schreibweise von Leerzeichen zu achten. „v2“: seit 0.47 mit Listen. */
export function fingerabdruck(f: Partial<KontaktFelder>): string {
const l = listenText(f);
return "v2" + JSON.stringify([s(f.name), f.gruppe ? "" : s(f.anrede), f.gruppe ? "" : s(f.titel), s(f.firma), f.funktion === undefined || f.gruppe ? "–" : s(f.funktion),
!!f.gruppe, s(f.notiz), l.telefone, l.emails, l.adressen]);
}
/** Telefonnummern vergleichbar machen: nur Ziffern, +49/0049 wie 0 */
export function nummer(t: string | null | undefined): string {
const d = (t ?? "").replace(/^\+/, "00").replace(/\D/g, "");
return d.replace(/^0049/, "0");
}
const adrSchluessel = (a: Anschrift) => [a.strasse, a.plz, a.ort, a.postfach].map((x) => s(x).toLowerCase()).join("|");
function dazu<T>(alt: T[], neu: T[], schluessel: (x: T) => string): T[] {
const da = new Set(alt.map(schluessel));
return [...alt, ...neu.filter((x) => !da.has(schluessel(x))).map((x) => ({ ...x, haupt: false }))];
}
/** Programm um die Karte ergänzen: Leeres füllen, fehlende Nummern, E-Mails und Adressen anhängen; was im Programm steht, bleibt */
export function ergaenzt(k: KontaktFelder, f: KontaktFelder): KontaktFelder {
return {
...k,
anrede: k.anrede ?? f.anrede, titel: k.titel ?? f.titel, firma: k.firma ?? f.firma, notiz: k.notiz ?? f.notiz,
funktion: k.funktion === undefined ? undefined : k.funktion ?? f.funktion ?? null,
...listenBereinigt({
telefone: dazu(k.telefone, f.telefone, (x) => nummer(x.wert)),
emails: dazu(k.emails, f.emails, (x) => x.wert.trim().toLowerCase()),
adressen: dazu(k.adressen, f.adressen, adrSchluessel),
}),
};
}
const TEL_PARAMS: Record<string, string> = { mobil: "type=CELL;type=VOICE", privat: "type=HOME;type=VOICE", geschaeftlich: "type=WORK;type=VOICE", zentrale: "type=MAIN", fax: "type=WORK;type=FAX" };
const EMAIL_PARAMS: Record<string, string> = { privat: "type=INTERNET;type=HOME", geschaeftlich: "type=INTERNET;type=WORK" };
const ADR_PARAMS: Record<string, string> = { privat: "type=HOME", geschaeftlich: "type=WORK" };
/** Typen ohne eigenes vCard-Kennwort bekommen wie bei Apple eine Bezeichnung */
const BEZEICHNUNG: Record<string, Record<string, string>> = {
TEL: { sonstige: "_$!<Other>!$_" },
EMAIL: { rechnung: "Rechnungen", sonstige: "_$!<Other>!$_" },
ADR: { rechnung: "Rechnungsadresse", sonstige: "_$!<Other>!$_" },
};
/**
* Karte mit den Feldern aus dem Programm. Eine vorhandene Karte wird nur in den gepflegten Zeilen geändert;
* ohne Karte entsteht eine neue (vCard 3.0, wie Apple sie anlegt).
*/
export function karteMit(f: KontaktFelder, uid: string, alt: string | null, jetzt = new Date()): string {
let z: Zeile[] = alt ? zeilen(alt).filter((x) => !["BEGIN", "END"].includes(x.name)) : [{ gruppe: "", name: "VERSION", roh: "VERSION", params: "", wert: "3.0" }];
const vorher = alt ? felderAus(alt) : null;
const setze = (name: string, params: string, wert: string | null) => {
const i = z.findIndex((x) => x.name === name.toUpperCase());
if (!wert) { z = z.filter((x) => x.name !== name.toUpperCase()); return; }
if (i >= 0) z[i] = { ...z[i]!, wert };
else z.push({ gruppe: "", name: name.toUpperCase(), roh: name, params, wert });
};
setze("FN", "", esc(f.name));
// N: Nachname;Vorname;weitere;Präfix;Suffix – bei Firmen leer wie bei Apple. Apples Aufteilung bleibt, solange der Name gleich ist.
const praefix = esc([f.gruppe ? "" : f.anrede, f.gruppe ? "" : f.titel].filter((x) => x && x.trim()).join(" "));
const altN = z.find((x) => x.name === "N");
if (f.gruppe) setze("N", "", ";;;;");
else if (!altN || !vorher || vorher.gruppe || vorher.name !== f.name) {
const worte = f.name.trim().split(/\s+/);
setze("N", "", worte.length > 1 ? `${esc(worte.at(-1)!)};${esc(worte.slice(0, -1).join(" "))};;${praefix};` : `${esc(f.name)};;;${praefix};`);
} else if ((vorher.anrede ?? null) !== (f.anrede ?? null) || (vorher.titel ?? null) !== (f.titel ?? null)) {
const t = altN.wert.split(/(?<!\\);/);
while (t.length < 5) t.push("");
t[3] = praefix;
setze("N", "", t.join(";"));
}
// ORG: Abteilung einer vorhandenen Karte bleibt, solange die Firma gleich ist
if (!f.firma) setze("ORG", "", null);
else if (vorher?.firma !== f.firma) setze("ORG", "", `${esc(f.firma)};`);
if (f.gruppe) setze("TITLE", "", null);
else if (f.funktion !== undefined) setze("TITLE", "", f.funktion ? esc(f.funktion) : null);
if (f.gruppe) setze("X-ABShowAs", "", "COMPANY");
else setze("X-ABShowAs", "", null);
// Nummern, E-Mails, Adressen: nur neu schreiben, was sich geändert hat
const neu = listenText(f), alteListen = vorher ? listenText(vorher) : null;
const l = listenBereinigt(f);
let item = Math.max(0, ...z.map((x) => /^item(\d+)$/i.exec(x.gruppe)?.[1]).filter(Boolean).map(Number));
const schreibe = (name: string, typ: string, params: Record<string, string>, haupt: boolean | undefined, wert: string) => {
const pref = haupt ? ";type=pref" : "";
const label = BEZEICHNUNG[name]?.[typ];
if (params[typ]) { z.push({ gruppe: "", name, roh: name, params: params[typ] + pref, wert }); return; }
const g = `item${++item}`;
z.push({ gruppe: g, name, roh: name, params: (name === "EMAIL" ? "type=INTERNET" : "") + pref, wert });
if (label) z.push({ gruppe: g, name: "X-ABLABEL", roh: "X-ABLabel", params: "", wert: esc(label) });
};
const ersetze = (name: string, gleich: boolean, neuSchreiben: () => void) => {
if (gleich) return;
const gruppen = new Set(z.filter((x) => x.name === name && x.gruppe).map((x) => x.gruppe));
z = z.filter((x) => x.name !== name && !gruppen.has(x.gruppe));
neuSchreiben();
};
const gleich = (k: "telefone" | "emails" | "adressen") => !!alteListen && JSON.stringify(alteListen[k]) === JSON.stringify(neu[k]);
ersetze("TEL", gleich("telefone"), () => l.telefone.forEach((x) => schreibe("TEL", x.typ, TEL_PARAMS, x.haupt, esc(x.wert))));
ersetze("EMAIL", gleich("emails"), () => l.emails.forEach((x) => schreibe("EMAIL", x.typ, EMAIL_PARAMS, x.haupt, esc(x.wert))));
ersetze("ADR", gleich("adressen"), () => l.adressen.forEach((a) => schreibe("ADR", a.typ, ADR_PARAMS, a.haupt,
[a.postfach ?? "", "", [a.strasse, a.zusatz].filter((x) => x && x.trim()).join("\n"), a.ort, a.region ?? "", a.plz, a.land ?? ""].map((x) => esc(x ?? "")).join(";"))));
setze("NOTE", "", f.notiz ? esc(f.notiz) : null);
setze("UID", "", uid);
setze("REV", "", jetzt.toISOString().replace(/\.\d+Z$/, "Z"));
const zeile = (x: Zeile) => `${x.gruppe ? `${x.gruppe}.` : ""}${x.roh}${x.params ? `;${x.params}` : ""}:${x.wert}`;
return ["BEGIN:VCARD", ...z.map(zeile), "END:VCARD"].join("\r\n") + "\r\n";
}