Kontakte mit dem Handy abgleichen über Nextcloud-Adressbuch, .vcf einlesen (0.44.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
This commit is contained in:
217
src/server/kontaktabgleich.ts
Normal file
217
src/server/kontaktabgleich.ts
Normal file
@@ -0,0 +1,217 @@
|
||||
// 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.
|
||||
|
||||
import type { Client, Pool } from "./db.js";
|
||||
import { transaktion } from "./db.js";
|
||||
import type { NextcloudZugang } from "./nextcloud.js";
|
||||
import { FELDER, type KontaktFelder, felderAus, fingerabdruck, karteMit, kartenAus, nummer, revVon, uidVon } from "../domain/vcard.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 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 };
|
||||
const SPALTEN = `id, ${FELDER.join(", ")}, geaendert_am`;
|
||||
const nurFelder = (k: KontaktFelder): KontaktFelder => Object.fromEntries(FELDER.map((f) => [f, k[f] ?? null])) as unknown as KontaktFelder;
|
||||
|
||||
async function kontaktSetzen(c: Client, id: string, f: KontaktFelder): Promise<void> {
|
||||
await c.query(`update kontakt set ${FELDER.map((x, i) => `${x} = $${i + 2}`).join(", ")}, geaendert_am = now() where id = $1`, [id, ...FELDER.map((x) => f[x])]);
|
||||
}
|
||||
async function kontaktNeu(c: Client, f: KontaktFelder): Promise<string> {
|
||||
return (await c.query(`insert into kontakt (${FELDER.join(", ")}) values (${FELDER.map((_, i) => `$${i + 1}`).join(", ")}) returning id`, FELDER.map((x) => f[x]))).rows[0].id;
|
||||
}
|
||||
|
||||
/** Derselbe Mensch: gleiche E-Mail, gleiche Nummer oder gleicher Name */
|
||||
export function passend<T extends KontaktFelder>(kontakte: T[], f: KontaktFelder): T | undefined {
|
||||
const mail = f.email?.toLowerCase();
|
||||
const nrn = [f.telefon, f.mobil].map(nummer).filter((n) => n.length >= 6);
|
||||
return (mail ? kontakte.find((k) => k.email?.toLowerCase() === mail) : undefined)
|
||||
?? kontakte.find((k) => [k.telefon, k.mobil].map(nummer).some((n) => n.length >= 6 && nrn.includes(n)))
|
||||
?? kontakte.find((k) => k.name.trim().toLowerCase() === f.name.trim().toLowerCase());
|
||||
}
|
||||
|
||||
/** Leere Felder im Programm aus der Karte füllen; was im Programm steht, bleibt */
|
||||
const ergaenzt = (k: KontaktFelder, f: KontaktFelder): KontaktFelder => nurFelder(Object.fromEntries(FELDER.map((x) => [x, k[x] ?? f[x]])) as unknown as KontaktFelder);
|
||||
|
||||
/** .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 c.query<Kontakt>(`select ${SPALTEN} from kontakt`)).rows;
|
||||
const e = { neu: 0, ergaenzt: 0, gleich: 0 };
|
||||
for (const karte of kartenAus(text)) {
|
||||
const f = felderAus(karte);
|
||||
const k = passend(kontakte, f);
|
||||
if (!k) { kontakte.push({ ...f, id: await kontaktNeu(c, f), geaendert_am: new Date() }); e.neu++; continue; }
|
||||
const m = ergaenzt(k, f);
|
||||
if (fingerabdruck(m) === fingerabdruck(k)) { e.gleich++; continue; }
|
||||
await kontaktSetzen(c, k.id, m);
|
||||
Object.assign(k, m);
|
||||
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)).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 pool.query<Kontakt>(`select ${SPALTEN} from kontakt`)).rows.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(nurFelder(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));
|
||||
};
|
||||
const vomHandy = async (k: Kontakt, r: Karte, uid: string) => {
|
||||
const f = felderAus(r.karte);
|
||||
await transaktion(pool, WER, (c) => kontaktSetzen(c, k.id, f));
|
||||
Object.assign(k, f);
|
||||
await speichere(r.href, k.id, uid, r.etag, r.karte, fingerabdruck(f));
|
||||
};
|
||||
|
||||
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);
|
||||
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(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) => kontaktNeu(c, f));
|
||||
const neu = { ...f, id, geaendert_am: new Date() };
|
||||
kontakte.set(id, neu);
|
||||
verknuepft.add(id);
|
||||
await speichere(r.href, id, uid, r.etag, r.karte, fingerabdruck(f));
|
||||
e.neuVomHandy++;
|
||||
continue;
|
||||
}
|
||||
verknuepft.add(k.id);
|
||||
const m = ergaenzt(k, f);
|
||||
if (fingerabdruck(m) !== fingerabdruck(k)) { await transaktion(pool, WER, (c) => kontaktSetzen(c, k.id, m)); Object.assign(k, m); }
|
||||
if (fingerabdruck(m) !== fingerabdruck(f)) await insHandy(k, r.href, uid, r);
|
||||
else await speichere(r.href, k.id, uid, r.etag, r.karte, fingerabdruck(k));
|
||||
e.zusammengefuehrt++;
|
||||
}
|
||||
|
||||
// Kontakte, die es im Handy noch nicht gibt
|
||||
for (const k of frei()) {
|
||||
await insHandy(k, `${basis}${k.id}.vcf`, k.id, null);
|
||||
e.neuInsHandy++;
|
||||
}
|
||||
return e;
|
||||
}
|
||||
Reference in New Issue
Block a user