Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
288 lines
17 KiB
TypeScript
288 lines
17 KiB
TypeScript
// Kontakte mit dem Handy abgleichen (Henning, 04.11.2026): ein Adressbuch in der Nextcloud (CardDAV), das auch
|
|
// das iPhone als CardDAV-Account abgleicht. In beide Richtungen; geändert auf beiden Seiten gilt die neuere Änderung.
|
|
// Im Handy gelöscht bleibt der Kontakt im Programm (nur markiert); im Programm gelöscht verschwindet die Karte.
|
|
// Seit 0.47: eine Karte je Person mit allen Nummern; ORG ist der erste übergeordnete Kontakt. Übergeordnete Kontakte
|
|
// bekommen eine eigene Karte, sobald sie eine eigene Nummer oder E-Mail haben.
|
|
|
|
import type { Client, Pool } from "./db.js";
|
|
import { transaktion } from "./db.js";
|
|
import { type NextcloudZugang, abrufMitUrsache } from "./nextcloud.js";
|
|
import { type KontaktFelder, ergaenzt, felderAus, fingerabdruck, istVerteiler, karteMit, kartenAus, nummer, revVon, uidVon } from "../domain/vcard.js";
|
|
import { einzelfelder, listenBereinigt } from "../domain/kontaktdaten.js";
|
|
|
|
export interface Adressbuch { href: string; name: string }
|
|
export interface Karte { href: string; etag: string | null; karte: string }
|
|
|
|
const xml = (s: string) => s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/ /g, "\r").replace(/ /g, "\n").replace(/&/g, "&");
|
|
const tag = (teil: string, name: string) => new RegExp(`<(?:[\\w-]+:)?${name}\\b[^>]*>([\\s\\S]*?)</(?:[\\w-]+:)?${name}>`, "i").exec(teil)?.[1];
|
|
const antworten = (text: string) => [...text.matchAll(/<(?:[\w-]+:)?response\b[^>]*>([\s\S]*?)<\/(?:[\w-]+:)?response>/gi)].map((m) => m[1]!);
|
|
|
|
/** Adressbücher des Benutzers in derselben Nextcloud wie die Projektordner */
|
|
export class CardDav {
|
|
private origin: string;
|
|
readonly heim: string;
|
|
constructor(private z: NextcloudZugang, private abruf: typeof fetch = fetch) {
|
|
const u = new URL(z.url);
|
|
this.origin = u.origin;
|
|
const i = u.pathname.indexOf("/remote.php/");
|
|
const basis = i >= 0 ? u.pathname.slice(0, i) : u.pathname.replace(/\/+$/, "");
|
|
this.heim = `${basis}/remote.php/dav/addressbooks/users/${encodeURIComponent(z.benutzer)}/`;
|
|
}
|
|
|
|
private anfrage(methode: string, href: string, kopf: Record<string, string> = {}, body?: string): Promise<Response> {
|
|
return abrufMitUrsache(this.abruf, this.origin + href, {
|
|
method: methode,
|
|
headers: { authorization: `Basic ${btoa(`${this.z.benutzer}:${this.z.passwort}`)}`, ...kopf },
|
|
body,
|
|
});
|
|
}
|
|
|
|
private static fehler(r: Response, was: string): Error {
|
|
return new Error(r.status === 401 ? "Die Nextcloud lehnt die Anmeldung ab: Benutzer oder App-Passwort stimmt nicht." : `Nextcloud antwortet mit ${r.status} (${was})`);
|
|
}
|
|
|
|
async adressbuecher(): Promise<Adressbuch[]> {
|
|
const r = await this.anfrage("PROPFIND", this.heim, { depth: "1", "content-type": "application/xml; charset=utf-8" },
|
|
'<?xml version="1.0" encoding="utf-8"?><d:propfind xmlns:d="DAV:"><d:prop><d:displayname/><d:resourcetype/></d:prop></d:propfind>');
|
|
if (r.status !== 207) throw CardDav.fehler(r, "Adressbücher");
|
|
return antworten(await r.text())
|
|
.filter((t) => /<(?:[\w-]+:)?addressbook\s*\/?>/i.test(tag(t, "resourcetype") ?? ""))
|
|
.map((t) => {
|
|
const href = decodeURIComponent(tag(t, "href")!.trim());
|
|
return { href, name: xml(tag(t, "displayname") ?? "").trim() || href.split("/").filter(Boolean).at(-1)! };
|
|
});
|
|
}
|
|
|
|
async karten(adressbuch: string): Promise<Karte[]> {
|
|
const r = await this.anfrage("REPORT", adressbuch, { depth: "1", "content-type": "application/xml; charset=utf-8" },
|
|
'<?xml version="1.0" encoding="utf-8"?><card:addressbook-query xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav"><d:prop><d:getetag/><card:address-data/></d:prop></card:addressbook-query>');
|
|
if (r.status !== 207) throw CardDav.fehler(r, "Kontakte lesen");
|
|
return antworten(await r.text())
|
|
.map((t) => ({ href: decodeURIComponent(tag(t, "href")!.trim()), etag: tag(t, "getetag") ? xml(tag(t, "getetag")!).trim() : null, karte: xml(tag(t, "address-data") ?? "") }))
|
|
.filter((k) => k.karte.includes("BEGIN:VCARD"));
|
|
}
|
|
|
|
/** Karte schreiben; ohne etag nur, wenn es sie noch nicht gibt. Gibt das neue etag zurück, falls die Nextcloud es nennt. */
|
|
async schreibe(href: string, karte: string, etag: string | null): Promise<string | null> {
|
|
const r = await this.anfrage("PUT", href, { "content-type": "text/vcard; charset=utf-8", ...(etag ? { "if-match": etag } : { "if-none-match": "*" }) }, karte);
|
|
if (!(r.status === 201 || r.status === 204 || r.status === 200)) throw CardDav.fehler(r, "Kontakt schreiben");
|
|
return r.headers.get("etag");
|
|
}
|
|
|
|
async loesche(href: string): Promise<void> {
|
|
const r = await this.anfrage("DELETE", href);
|
|
if (!(r.status === 204 || r.status === 200 || r.status === 404)) throw CardDav.fehler(r, "Kontakt löschen");
|
|
}
|
|
}
|
|
|
|
type Kontakt = KontaktFelder & { id: string; geaendert_am: Date | string; art: string | null; zug_id: string | null; gruppe_id: string | null; abgleich: boolean };
|
|
|
|
const SPALTEN = `select k.id, k.name, k.anrede, k.titel, k.art, k.firma, k.notiz, k.telefone, k.emails, k.adressen, k.geaendert_am,
|
|
z.id as zug_id, z.gruppe_id, z.funktion, g.name as gruppe_name
|
|
from kontakt k
|
|
left join lateral (select id, gruppe_id, funktion from kontakt_zugehoerigkeit where person_id = k.id order by reihenfolge, angelegt_am limit 1) z on true
|
|
left join kontakt g on g.id = z.gruppe_id`;
|
|
const gleich = (a: string | null | undefined, b: string | null | undefined) => (a ?? "").trim().toLowerCase() === (b ?? "").trim().toLowerCase();
|
|
const leer = (s: string | null | undefined) => (s && s.trim() ? s.trim() : null);
|
|
|
|
/** Kontakt aus der Datenbank so, wie er im Handy stehen soll */
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
function ausZeile(r: Record<string, any>): Kontakt {
|
|
// übergeordneter Kontakt, oder ein älterer Firmenkontakt (Name = Firma): Firmenkarte
|
|
const gruppe = !!r.art || (!!r.firma && gleich(r.firma, r.name));
|
|
const telefone = r.telefone ?? [], emails = r.emails ?? [];
|
|
return {
|
|
id: r.id, geaendert_am: r.geaendert_am, art: r.art ?? null, zug_id: r.zug_id ?? null, gruppe_id: r.gruppe_id ?? null,
|
|
name: r.name, anrede: gruppe ? null : r.anrede ?? null, titel: gruppe ? null : r.titel ?? null,
|
|
firma: gruppe ? r.name : r.gruppe_name ?? r.firma ?? null,
|
|
funktion: gruppe || !r.zug_id ? undefined : r.funktion ?? null,
|
|
gruppe, telefone, emails, adressen: r.adressen ?? [], notiz: r.notiz ?? null,
|
|
// übergeordnete Kontakte kommen nur mit eigener Nummer oder E-Mail neu ins Handy
|
|
abgleich: !r.art || telefone.length > 0 || emails.length > 0,
|
|
};
|
|
}
|
|
const alleKontakte = async (c: Client | Pool) => (await c.query(SPALTEN)).rows.map(ausZeile);
|
|
const einKontakt = async (c: Client | Pool, id: string) => ausZeile((await c.query(`${SPALTEN} where k.id = $1`, [id])).rows[0]);
|
|
|
|
/** Die Karte so lesen, wie sie zu diesem Kontakt passt: die Funktion nur, wo das Programm sie pflegt */
|
|
const fuer = (k: Pick<KontaktFelder, "funktion">, f: KontaktFelder): KontaktFelder => (k.funktion === undefined ? { ...f, funktion: undefined } : f);
|
|
|
|
/** ORG aus dem Handy: einem vorhandenen übergeordneten Kontakt zuordnen, sonst als Firma eintragen (Vorschlag „Firma anlegen?“) */
|
|
async function firmaSetzen(c: Client, id: string, alt: Kontakt | null, f: KontaktFelder): Promise<void> {
|
|
const org = leer(f.firma);
|
|
if (alt && gleich(org, alt.firma)) {
|
|
if (alt.zug_id && f.funktion !== undefined && (f.funktion ?? null) !== (alt.funktion ?? null))
|
|
await c.query("update kontakt_zugehoerigkeit set funktion = $2 where id = $1", [alt.zug_id, f.funktion ?? null]);
|
|
return;
|
|
}
|
|
// ORG im Handy gelöscht: Zuordnungen bleiben, nur die frei eingetragene Firma geht
|
|
if (!org) { if (!alt?.gruppe_id) await c.query("update kontakt set firma = null where id = $1", [id]); return; }
|
|
const g = (await c.query("select id from kontakt where art is not null and id <> $2 and lower(trim(name)) = lower($1) order by angelegt_am limit 1", [org, id])).rows[0];
|
|
if (!g) { await c.query("update kontakt set firma = $2 where id = $1", [id, org]); return; }
|
|
await c.query(`insert into kontakt_zugehoerigkeit (gruppe_id, person_id, funktion, reihenfolge)
|
|
values ($1, $2, $3, coalesce((select min(reihenfolge) from kontakt_zugehoerigkeit where person_id = $2), 1) - 1)
|
|
on conflict (gruppe_id, person_id) do update set funktion = coalesce(excluded.funktion, kontakt_zugehoerigkeit.funktion), reihenfolge = excluded.reihenfolge`,
|
|
[g.id, id, f.funktion ?? null]);
|
|
}
|
|
|
|
/** Karte ins Programm schreiben (neu, wenn alt fehlt); die Einzelfelder kommen wie beim Speichern aus den Listen */
|
|
async function kontaktSchreiben(c: Client, alt: Kontakt | null, f: KontaktFelder): Promise<string> {
|
|
const l = listenBereinigt(f);
|
|
const e = einzelfelder(l);
|
|
const person = !(alt ? alt.gruppe : f.gruppe);
|
|
const sp = ["name", "anrede", "titel", "notiz", "telefone", "emails", "adressen", "telefon", "mobil", "email", "strasse", "plz", "ort"];
|
|
const werte = [f.name, person ? f.anrede : null, person ? f.titel : null, f.notiz, JSON.stringify(l.telefone), JSON.stringify(l.emails), JSON.stringify(l.adressen),
|
|
e.telefon, e.mobil, e.email, e.strasse, e.plz, e.ort];
|
|
let id: string;
|
|
if (alt) {
|
|
await c.query(`update kontakt set ${sp.map((x, i) => `${x} = $${i + 2}`).join(", ")}, geaendert_am = now() where id = $1`, [alt.id, ...werte]);
|
|
id = alt.id;
|
|
} else {
|
|
id = (await c.query(`insert into kontakt (${sp.join(", ")}, art) values (${sp.map((_, i) => `$${i + 1}`).join(", ")}, $${sp.length + 1}) returning id`,
|
|
[...werte, f.gruppe ? "firma" : null])).rows[0].id;
|
|
}
|
|
if (person) await firmaSetzen(c, id, alt, f);
|
|
return id;
|
|
}
|
|
|
|
/** Derselbe Kontakt: gleiche E-Mail oder Nummer (Person zu Person, Firma zu Firma), sonst gleicher Name */
|
|
export function passend<T extends KontaktFelder>(kontakte: T[], f: KontaktFelder): T | undefined {
|
|
const mails = f.emails.map((x) => x.wert.trim().toLowerCase()).filter(Boolean);
|
|
const nrn = f.telefone.map((x) => nummer(x.wert)).filter((n) => n.length >= 6);
|
|
const art = kontakte.filter((k) => k.gruppe === f.gruppe);
|
|
return (mails.length ? art.find((k) => k.emails.some((x) => mails.includes(x.wert.trim().toLowerCase()))) : undefined)
|
|
?? (nrn.length ? art.find((k) => k.telefone.some((x) => nrn.includes(nummer(x.wert)))) : undefined)
|
|
?? kontakte.find((k) => gleich(k.name, f.name));
|
|
}
|
|
|
|
/** .vcf-Datei einlesen (auch ohne Nextcloud): neue Kontakte anlegen, vorhandene nur ergänzen */
|
|
export async function vcfEinlesen(c: Client, text: string): Promise<{ neu: number; ergaenzt: number; gleich: number }> {
|
|
const kontakte = await alleKontakte(c);
|
|
const e = { neu: 0, ergaenzt: 0, gleich: 0 };
|
|
for (const karte of kartenAus(text).filter((k) => !istVerteiler(k))) {
|
|
const f = felderAus(karte);
|
|
const k = passend(kontakte, f);
|
|
if (!k) { kontakte.push(await einKontakt(c, await kontaktSchreiben(c, null, f))); e.neu++; continue; }
|
|
const m = ergaenzt(k, fuer(k, f));
|
|
if (fingerabdruck(m) === fingerabdruck(k)) { e.gleich++; continue; }
|
|
await kontaktSchreiben(c, k, m);
|
|
Object.assign(k, await einKontakt(c, k.id));
|
|
e.ergaenzt++;
|
|
}
|
|
return e;
|
|
}
|
|
|
|
export interface Ergebnis { vomHandy: number; insHandy: number; neuVomHandy: number; neuInsHandy: number; imHandyGeloescht: number; entfernt: number; zusammengefuehrt: number }
|
|
|
|
export const ergebnisText = (e: Ergebnis) => {
|
|
const t = [
|
|
e.neuVomHandy && `${e.neuVomHandy} neu vom Handy`, e.vomHandy && `${e.vomHandy} vom Handy übernommen`,
|
|
e.neuInsHandy && `${e.neuInsHandy} neu ins Handy`, e.insHandy && `${e.insHandy} ins Handy geschrieben`,
|
|
e.zusammengefuehrt && `${e.zusammengefuehrt} zusammengeführt`, e.imHandyGeloescht && `${e.imHandyGeloescht} im Handy gelöscht`,
|
|
e.entfernt && `${e.entfernt} aus dem Adressbuch entfernt`,
|
|
].filter(Boolean);
|
|
return t.length ? t.join(", ") : "alles gleich";
|
|
};
|
|
|
|
/** Ein Abgleich mit dem Adressbuch. Jede Änderung steht im Protokoll unter „Handy-Abgleich“. */
|
|
export async function kontakteAbgleichen(pool: Pool, cd: CardDav, adressbuch: string): Promise<Ergebnis> {
|
|
const WER = "Handy-Abgleich";
|
|
const e: Ergebnis = { vomHandy: 0, insHandy: 0, neuVomHandy: 0, neuInsHandy: 0, imHandyGeloescht: 0, entfernt: 0, zusammengefuehrt: 0 };
|
|
const basis = adressbuch.endsWith("/") ? adressbuch : `${adressbuch}/`;
|
|
const fern = new Map((await cd.karten(basis)).filter((k) => !istVerteiler(k.karte)).map((k) => [k.href, k]));
|
|
const links = (await pool.query("select * from kontakt_abgleich")).rows as { href: string; kontakt_id: string | null; uid: string; etag: string | null; karte: string; stand: string; geloescht: boolean }[];
|
|
const kontakte = new Map((await alleKontakte(pool)).map((k) => [k.id, k]));
|
|
const verknuepft = new Set<string>();
|
|
const speichere = (href: string, kontaktId: string | null, uid: string, etag: string | null, karte: string, stand: string, geloescht = false) =>
|
|
pool.query(`insert into kontakt_abgleich (href, kontakt_id, uid, etag, karte, stand, geloescht) values ($1, $2, $3, $4, $5, $6, $7)
|
|
on conflict (href) do update set kontakt_id = excluded.kontakt_id, uid = excluded.uid, etag = excluded.etag, karte = excluded.karte, stand = excluded.stand,
|
|
geloescht = excluded.geloescht, geaendert_am = now()`, [href, kontaktId, uid, etag, karte, stand, geloescht]);
|
|
const insHandy = async (k: Kontakt, href: string, uid: string, alt: Karte | null) => {
|
|
const karte = karteMit(k, uid, alt?.karte ?? null);
|
|
const etag = await cd.schreibe(href, karte, alt?.etag ?? null);
|
|
await speichere(href, k.id, uid, etag, karte, fingerabdruck(k));
|
|
};
|
|
/** m ins Programm, falls anders; was das Programm danach anders hält als die Karte (z. B. die Firma), geht ins Handy */
|
|
const zusammen = async (k: Kontakt, r: Karte, uid: string, m: KontaktFelder): Promise<boolean> => {
|
|
let geaendert = false;
|
|
if (fingerabdruck(m) !== fingerabdruck(k)) {
|
|
await transaktion(pool, WER, (c) => kontaktSchreiben(c, k, m));
|
|
Object.assign(k, await einKontakt(pool, k.id));
|
|
geaendert = true;
|
|
}
|
|
if (fingerabdruck(fuer(k, felderAus(r.karte))) !== fingerabdruck(k)) { await insHandy(k, r.href, uid, r); return true; }
|
|
await speichere(r.href, k.id, uid, r.etag, r.karte, fingerabdruck(k));
|
|
return geaendert;
|
|
};
|
|
const vomHandy = (k: Kontakt, r: Karte, uid: string) => zusammen(k, r, uid, felderAus(r.karte));
|
|
|
|
for (const l of links) {
|
|
const r = fern.get(l.href);
|
|
fern.delete(l.href);
|
|
const k = l.kontakt_id ? kontakte.get(l.kontakt_id) : undefined;
|
|
if (!k) {
|
|
// im Programm gelöscht
|
|
if (r) await cd.loesche(l.href);
|
|
await pool.query("delete from kontakt_abgleich where href = $1", [l.href]);
|
|
e.entfernt++;
|
|
continue;
|
|
}
|
|
verknuepft.add(k.id);
|
|
// erster Lauf nach 0.47: Programm und Karte einmal zusammenführen, damit keine Nummer aus dem Handy verloren geht
|
|
if (!l.stand.startsWith("v2")) {
|
|
if (r) { if (await zusammen(k, r, l.uid, ergaenzt(k, fuer(k, felderAus(r.karte))))) e.zusammengefuehrt++; }
|
|
else await pool.query("update kontakt_abgleich set stand = $2 where href = $1", [l.href, fingerabdruck(k)]);
|
|
if (r || l.geloescht) continue;
|
|
}
|
|
const lokal = fingerabdruck(k) !== l.stand;
|
|
if (!r) {
|
|
if (!l.geloescht) {
|
|
await pool.query("update kontakt_abgleich set geloescht = true, stand = $2, geaendert_am = now() where href = $1", [l.href, fingerabdruck(k)]);
|
|
e.imHandyGeloescht++;
|
|
} else if (lokal) {
|
|
// nach dem Löschen im Handy im Programm geändert: wieder ins Handy
|
|
await pool.query("delete from kontakt_abgleich where href = $1", [l.href]);
|
|
const uid = crypto.randomUUID();
|
|
await insHandy(k, `${basis}${uid}.vcf`, uid, null);
|
|
e.neuInsHandy++;
|
|
}
|
|
continue;
|
|
}
|
|
const fernGeaendert = r.etag !== l.etag;
|
|
if (!fernGeaendert && !lokal) continue;
|
|
if (fernGeaendert && fingerabdruck(fuer(k, felderAus(r.karte))) === fingerabdruck(k)) { await speichere(l.href, k.id, l.uid, r.etag, r.karte, fingerabdruck(k)); continue; }
|
|
// beide geändert: die neuere Änderung gilt; ohne Zeitstempel in der Karte das Handy
|
|
const rev = revVon(r.karte);
|
|
const handyNeuer = !lokal || (fernGeaendert && (!rev || rev >= new Date(k.geaendert_am).toISOString()));
|
|
if (handyNeuer) { await vomHandy(k, r, l.uid); e.vomHandy++; }
|
|
else { await insHandy(k, l.href, l.uid, r); e.insHandy++; }
|
|
}
|
|
|
|
// Karten, die das Programm noch nicht kennt: zu einem vorhandenen Kontakt oder neu
|
|
const frei = () => [...kontakte.values()].filter((k) => !verknuepft.has(k.id));
|
|
for (const r of fern.values()) {
|
|
const f = felderAus(r.karte);
|
|
const uid = uidVon(r.karte) ?? crypto.randomUUID();
|
|
const k = passend(frei(), f);
|
|
if (!k) {
|
|
const id = await transaktion(pool, WER, (c) => kontaktSchreiben(c, null, f));
|
|
const neu = await einKontakt(pool, id);
|
|
kontakte.set(id, neu);
|
|
verknuepft.add(id);
|
|
await zusammen(neu, r, uid, neu);
|
|
e.neuVomHandy++;
|
|
continue;
|
|
}
|
|
verknuepft.add(k.id);
|
|
await zusammen(k, r, uid, ergaenzt(k, fuer(k, f)));
|
|
e.zusammengefuehrt++;
|
|
}
|
|
|
|
// Kontakte, die es im Handy noch nicht gibt
|
|
for (const k of frei().filter((x) => x.abgleich)) {
|
|
await insHandy(k, `${basis}${k.id}.vcf`, k.id, null);
|
|
e.neuInsHandy++;
|
|
}
|
|
return e;
|
|
}
|