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:
@@ -12,6 +12,7 @@ import { uebersicht } from "./uebersicht.js";
|
||||
import { aufgabenKalender, baustellenKalender } from "./kalender.js";
|
||||
import { nummernAufraeumen, projektNummerVorbereiten } from "./nummern.js";
|
||||
import { Nextcloud, STATUSORDNER, ordnerAbgleichen, webdavBasis } from "./nextcloud.js";
|
||||
import { CardDav, ergebnisText, kontakteAbgleichen, vcfEinlesen } from "./kontaktabgleich.js";
|
||||
import { NUR_SICHERUNG, TABELLEN } from "./tabellen.js";
|
||||
import { EinstellungenSchema, type Einstellungen } from "./einstellungen.js";
|
||||
import { liquiditaet } from "../domain/liquiditaet.js";
|
||||
@@ -49,6 +50,8 @@ export interface Optionen {
|
||||
anmeldung?: Anmeldeart;
|
||||
/** Nur auf dem Server: Code, mit dem der erste Benutzer (Inhaber) angelegt wird */
|
||||
einrichtungsCode?: string;
|
||||
/** Nur auf dem Server: Kontakte so oft (ms) mit dem Handy-Adressbuch abgleichen, wenn eingeschaltet */
|
||||
kontaktTakt?: number;
|
||||
}
|
||||
|
||||
/** Wer angemeldet ist, steht im Änderungsprotokoll */
|
||||
@@ -189,6 +192,80 @@ export async function baueApp(o: Optionen): Promise<FastifyInstance> {
|
||||
return { ok, fehler };
|
||||
});
|
||||
|
||||
// Kontakte mit dem Handy abgleichen (Henning, 04.11.2026): Adressbuch in derselben Nextcloud wie die Projektordner
|
||||
async function cardDav(): Promise<CardDav | undefined> {
|
||||
const nc = await nextcloud();
|
||||
return nc ? new CardDav(nc.z, nc.abruf) : undefined;
|
||||
}
|
||||
let laeuft: Promise<unknown> | null = null;
|
||||
async function kontakteLauf(): Promise<{ ok: boolean; meldung: string }> {
|
||||
const e = (await ladeEinstellungen()).kontakteAbgleich;
|
||||
const cd = await cardDav();
|
||||
if (!cd) return { ok: false, meldung: "Für den Abgleich fehlt der Nextcloud-Zugang." };
|
||||
if (!e.adressbuch) return { ok: false, meldung: "Bitte zuerst das Adressbuch wählen." };
|
||||
const stand = (meldung: string | null, fehler: string | null) => pool.query(`insert into abgleich_stand (art, zuletzt, meldung, fehler) values ('kontakte', now(), $1, $2)
|
||||
on conflict (art) do update set zuletzt = now(), meldung = coalesce(excluded.meldung, abgleich_stand.meldung), fehler = excluded.fehler`, [meldung, fehler]);
|
||||
try {
|
||||
const meldung = ergebnisText(await kontakteAbgleichen(pool, cd, e.adressbuch));
|
||||
await stand(meldung, null);
|
||||
return { ok: true, meldung };
|
||||
} catch (err) {
|
||||
await stand(null, (err as Error).message);
|
||||
return { ok: false, meldung: (err as Error).message };
|
||||
}
|
||||
}
|
||||
/** nie zwei Läufe gleichzeitig */
|
||||
const kontakteEinmal = async () => {
|
||||
while (laeuft) await laeuft.catch(() => {});
|
||||
const p = kontakteLauf();
|
||||
laeuft = p;
|
||||
try { return await p; } finally { laeuft = null; }
|
||||
};
|
||||
if (o.kontaktTakt) {
|
||||
const takt = setInterval(() => {
|
||||
void (async () => { if ((await ladeEinstellungen()).kontakteAbgleich.an) await kontakteEinmal(); })().catch((err) => app.log.error(err));
|
||||
}, o.kontaktTakt);
|
||||
app.addHook("onClose", async () => clearInterval(takt));
|
||||
}
|
||||
app.get("/api/kontakte-abgleich", async () => {
|
||||
const e = (await ladeEinstellungen()).kontakteAbgleich;
|
||||
const stand = (await pool.query("select zuletzt, meldung, fehler from abgleich_stand where art = 'kontakte'")).rows[0] ?? null;
|
||||
const n = (await pool.query("select count(*) filter (where not geloescht) as verknuepft, count(*) filter (where geloescht) as geloescht from kontakt_abgleich")).rows[0];
|
||||
return { ...e, moeglich: !!(await cardDav()), stand, verknuepft: Number(n.verknuepft), geloescht: Number(n.geloescht) };
|
||||
});
|
||||
app.get("/api/kontakte-abgleich/adressbuecher", async (_req, reply) => {
|
||||
const cd = await cardDav();
|
||||
if (!cd) return reply.status(409).send({ fehler: einrichtbar || o.nextcloud ? "Bitte zuerst den Nextcloud-Zugang eintragen." : "Der Abgleich mit dem Handy geht erst auf dem Server." });
|
||||
try { return await cd.adressbuecher(); } catch (err) { return reply.status(502).send({ fehler: (err as Error).message }); }
|
||||
});
|
||||
app.put("/api/kontakte-abgleich", async (req) => {
|
||||
const d = z.object({ adressbuch: z.string().trim().max(500), an: z.boolean() }).parse(req.body);
|
||||
const e = await ladeEinstellungen();
|
||||
const neu = EinstellungenSchema.parse({ ...e, kontakteAbgleich: d });
|
||||
await transaktion(pool, benutzer(req), async (c) => {
|
||||
await c.query("update einstellungen set daten = $1", [neu]);
|
||||
// anderes Adressbuch: Zuordnung neu aufbauen (der erste Lauf führt gleiche Kontakte zusammen)
|
||||
if (d.adressbuch !== e.kontakteAbgleich.adressbuch) {
|
||||
await c.query("delete from kontakt_abgleich");
|
||||
await c.query("delete from abgleich_stand where art = 'kontakte'");
|
||||
}
|
||||
});
|
||||
return { ok: true };
|
||||
});
|
||||
app.post("/api/kontakte-abgleich/jetzt", async (_req, reply) => {
|
||||
const r = await kontakteEinmal();
|
||||
return r.ok ? r : reply.status(409).send({ fehler: r.meldung });
|
||||
});
|
||||
/** welche Kontakte im Handy stehen, für die Markierung in der Kontaktliste */
|
||||
app.get("/api/kontakte-abgleich/kontakte", async () =>
|
||||
(await pool.query("select kontakt_id, geloescht from kontakt_abgleich where kontakt_id is not null")).rows);
|
||||
// .vcf-Datei einlesen (Apple: Kontakte auswählen → Exportieren); geht auch in der Testversion
|
||||
app.post("/api/kontakte/vcf", async (req, reply) => {
|
||||
const d = z.object({ text: z.string().max(20 * 1024 * 1024) }).parse(req.body);
|
||||
if (!/BEGIN:VCARD/i.test(d.text)) return reply.status(400).send({ fehler: "Das ist keine Kontaktdatei (vCard, .vcf)." });
|
||||
return transaktion(pool, benutzer(req), (c) => vcfEinlesen(c, d.text));
|
||||
});
|
||||
|
||||
// Ablage auf der Projektseite (Henning, 20.10.2026): Inhalt des Nextcloud-Projektordners anzeigen und Dateien öffnen
|
||||
const AblageAnfrage = z.object({ pfad: z.string().max(500).default("") })
|
||||
.refine((q) => !q.pfad.split("/").some((t) => t === ".." || t === "."), { message: "Pfad ungültig" });
|
||||
|
||||
@@ -58,6 +58,13 @@ export const EinstellungenSchema = z.object({
|
||||
// geheimer Teil der Kalender-Links (T11); Outlook classic kann sich nicht anmelden
|
||||
kalenderToken: z.string().min(20).nullable().default(null),
|
||||
// P10: Nextcloud-Zugang für die Projektordner (Henning, 23.10.2026); das App-Passwort steht nicht hier, sondern in nextcloud_zugang
|
||||
// Kontakte mit dem Handy abgleichen (Henning, 04.11.2026): Adressbuch (CardDAV-Adresse) in derselben Nextcloud
|
||||
kontakteAbgleich: z
|
||||
.object({
|
||||
adressbuch: z.string().trim().max(500).default(""),
|
||||
an: z.boolean().default(false),
|
||||
})
|
||||
.prefault({}),
|
||||
nextcloud: z
|
||||
.object({
|
||||
adresse: z.string().trim().max(300).default(""),
|
||||
|
||||
@@ -35,7 +35,7 @@ if (Number((await pool.query("select count(*) as n from benutzer")).rows[0].n) =
|
||||
einrichtungsCode ||= randomBytes(6).toString("hex");
|
||||
console.log(`Noch kein Benutzer angelegt. Einrichtungscode für den Inhaber: ${einrichtungsCode}`);
|
||||
}
|
||||
const app = await baueApp({ pool, logger: true, nextcloud, anmeldung: "passwort", einrichtungsCode });
|
||||
const app = await baueApp({ pool, logger: true, nextcloud, anmeldung: "passwort", einrichtungsCode, kontaktTakt: 5 * 60 * 1000 });
|
||||
const port = Number(process.env.PORT ?? 3000);
|
||||
await app.listen({ host: "0.0.0.0", port });
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
31
src/server/migrations/028_kontakte_abgleich.sql
Normal file
31
src/server/migrations/028_kontakte_abgleich.sql
Normal file
@@ -0,0 +1,31 @@
|
||||
-- Kontakte mit dem Handy abgleichen über ein Adressbuch in der Nextcloud (Henning, 04.11.2026).
|
||||
-- Der Kontakt bekommt Mobilnummer und Adresse, wie sie im Handy stehen.
|
||||
alter table kontakt
|
||||
add column mobil text,
|
||||
add column strasse text,
|
||||
add column plz text,
|
||||
add column ort text;
|
||||
|
||||
-- Je Karte im Adressbuch: zu welchem Kontakt sie gehört und welcher Stand zuletzt auf beiden Seiten gleich war.
|
||||
-- Ohne Änderungsprotokoll und nicht in der Sicherungsdatei: der Abgleich baut sie neu auf.
|
||||
create table kontakt_abgleich (
|
||||
href text primary key,
|
||||
-- null: im Programm gelöscht, die Karte wird beim nächsten Abgleich im Adressbuch entfernt
|
||||
kontakt_id uuid unique references kontakt (id) on delete set null,
|
||||
uid text not null,
|
||||
etag text,
|
||||
karte text not null,
|
||||
-- Fingerabdruck der gepflegten Felder beim letzten Abgleich
|
||||
stand text not null,
|
||||
-- im Handy gelöscht; der Kontakt bleibt im Programm
|
||||
geloescht boolean not null default false,
|
||||
geaendert_am timestamptz not null default now()
|
||||
);
|
||||
|
||||
-- letzter Lauf je Abgleich, ohne Protokoll (läuft alle paar Minuten)
|
||||
create table abgleich_stand (
|
||||
art text primary key,
|
||||
zuletzt timestamptz,
|
||||
meldung text,
|
||||
fehler text
|
||||
);
|
||||
@@ -52,7 +52,7 @@ export function webdavBasis(z: { adresse: string; benutzer: string; ordner: stri
|
||||
const kodiert = (pfad: string) => pfad.split("/").map(encodeURIComponent).join("/");
|
||||
|
||||
export class Nextcloud {
|
||||
constructor(private z: NextcloudZugang, private abruf: typeof fetch = fetch) {}
|
||||
constructor(readonly z: NextcloudZugang, readonly abruf: typeof fetch = fetch) {}
|
||||
|
||||
private adresse(pfad: string): string {
|
||||
return `${this.z.url.replace(/\/+$/, "")}/${kodiert(pfad)}`;
|
||||
|
||||
@@ -59,7 +59,11 @@ export const TABELLEN: Tabelle[] = [
|
||||
firma: optText,
|
||||
rolle: z.enum(["bauherr", "subunternehmer", "lieferant", "planer", "mitarbeiter", "sonstige"]).optional(),
|
||||
telefon: optText,
|
||||
mobil: optText,
|
||||
email: optText,
|
||||
strasse: optText,
|
||||
plz: optText,
|
||||
ort: optText,
|
||||
gewerk: optText,
|
||||
notiz: optText,
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user