Compare commits

...
12 Commits
Author SHA1 Message Date
duffyduckandClaude Opus 5 6ecd5d7fa3 Fonaria als zweite Anlage neben Starface
Die SyncEngine kennt jetzt nur noch IContactBackend. Was dahinter steckt,
entscheidet das Profil — der Ablauf mit getrennten Baselines, Wiederzuordnung
und Konfliktaufloesung bleibt unangetastet. In ihm steckt die Erfahrung, die
man nicht zweimal machen will.

FonariaApiClient spricht deren REST-API. Der Kern ist das Feld `verwaltet`,
das jeder Schreibvorgang mitschickt: Fonaria haelt den Kontakt als
vollstaendige vCard, dieses Sync-Modell bildet davon nur einen Ausschnitt ab.
Ohne diese Liste haette ein aus Outlook gespiegelter Kontakt nach dem ersten
Abgleich kein Bild, keine Kategorien und keinen Jahrestag mehr — nicht weil
jemand sie geloescht haette, sondern weil wir sie nicht kannten.

Zwei Verluste lagen darunter und sind gefunden worden, weil der Client gegen
eine echte Anlage lief:

- Die Abteilung steckt im zweiten Teil von ORG. Wer nur die Firma schickt,
  loescht sie mit.
- Neben der geschaeftlichen Anschrift kann eine private stehen. Das
  Sync-Modell traegt nur eine.

Beides wird jetzt aus dem gelesenen Stand unveraendert zurueckgeschrieben.

Umbenannt: StarfaceConnection -> SystemConnection, StarfaceAddressBook ->
RemoteAddressBook. Die JSON-Namen bleiben ueber JsonProperty erhalten, sonst
verloeren bestehende Profile ihre Verbindungsdaten. SyncMapping.StarfaceId
behaelt seinen Namen aus demselben Grund.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 22:10:43 +02:00
duffyduck 88635c04f8 Release v0.0.0.30 2026-06-08 13:53:34 +02:00
duffyduckandClaude Opus 4.8 6b025a24f0 Add autostart management (per-user / all-users) in settings
Setup setzt den Autostart weiterhin fuer alle Benutzer (HKLM); die
Task-Beschreibung im Installer stellt das jetzt klar.

In den Einstellungen neuer Abschnitt "Autostart":
- "Nur fuer diesen Benutzer" -> HKCU\...\Run
- "Fuer alle Benutzer" -> HKLM\...\Run, nur mit Admin-Rechten aenderbar
  (so laesst sich der vom Setup gesetzte All-User-Autostart auch entfernen).

Neuer AutostartManager kapselt Lesen/Setzen/Entfernen beider Run-Eintraege
und die Admin-Pruefung. Single-Instance-Mutex verhindert weiterhin einen
Doppelstart, falls beide Eintraege gesetzt sind.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:52:34 +02:00
duffyduckandClaude Opus 4.8 641267081a Add log auto-clear setting (retention in days, 0 = off)
Neue Einstellung "Protokoll auto-leeren - Eintraege aelter als (Tage)".
0 = aus (alle Eintraege bleiben), >0 entfernt aeltere Eintraege.

- UserSettings.LogRetentionDays (Standard 0).
- Logger.PruneOlderThan(days): parst den Zeitstempel-Prefix je Zeile und
  entfernt zu alte; Zeilen ohne Zeitstempel bleiben erhalten.
- Ausgefuehrt beim Start, vor jedem Sync (Coordinator), beim Oeffnen des
  Protokolls und beim Speichern der Einstellungen.
- SettingsForm: NumericUpDown (0-3650).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:47:10 +02:00
duffyduckandClaude Opus 4.8 0336530742 Unify manual and automatic sync via SyncCoordinator
Der manuelle "Synchronisieren"-Button (SyncProgressForm) lief ueber eine eigene
Engine und umging die clientuebergreifende Lock-Datei, den lokalen Guard und
einen Teil des Protokolls. Jetzt teilen sich beide Pfade einen SyncCoordinator.

- Neuer SyncCoordinator kapselt: prozessweiten Re-Entrancy-Guard (statisch, so
  koennen manueller + automatischer Sync nicht mehr gleichzeitig laufen),
  Lock-Datei (mit Warte-Status), Konflikt-Notizen anderer Arbeitsplaetze,
  Protokoll (Start/Ergebnis/Aenderungen/Konflikte/Fehler) und das Verteilen
  eigener Konflikt-Notizen. runEngine wird vom Aufrufer uebergeben, damit das
  Threading pro Pfad erhalten bleibt (UI-Thread vs. Task.Run).
- MainForm.RunSync und SyncProgressForm.RunSync nutzen den Coordinator; UI
  (Tray-Meldung vs. Fenster) bleibt jeweils beim Aufrufer.
- Lock/Notiz/Guard-Logik aus MainForm entfernt (jetzt zentral).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:43:03 +02:00
duffyduckandClaude Opus 4.8 75c0c1126e Log what changed; add notification on/off settings
Protokoll:
- SyncResult.Changes erfasst jede tatsaechliche Aenderung (erstellt/aktualisiert/
  geloescht/verknuepft/zusammengefuehrt je Kontakt) per Action()-Helfer.
- Beide Sync-Pfade (Auto/Tray via RunSync UND manueller Sync via
  SyncProgressForm) schreiben Start, Ergebnis, Aenderungen, Konflikte und Fehler
  ins persistente Protokoll.

Benachrichtigungen:
- UserSettings: NotificationsEnabled (allgemein) + NotifyWarningsErrors
  (Konflikte/Fehler), beide in der Einstellungen-Maske als Haken.
- MainForm.Balloon() zeigt Tray-Meldungen nur, wenn der passende Haken aktiv
  ist; Zusammenfassung gilt als Warnung, wenn Fehler/Konflikte auftraten.
- Protokoll wird unabhaengig von den Benachrichtigungs-Einstellungen geschrieben.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:35:55 +02:00
duffyduck 96c34e542f Release v0.0.0.29 2026-06-08 13:18:35 +02:00
duffyduckandClaude Opus 4.8 23223fe0be Add persistent log file and "Protokoll" viewer button
Tray-Meldungen verschwinden - daher ein dauerhaftes Protokoll.

- Logger: threadsicheres Datei-Log in %AppData%\StarfaceOutlookSync\sync.log
  mit Rotation bei 2 MB.
- MainForm protokolliert Sync-Start, Ergebnis, Konflikte (lokal + von anderen
  Arbeitsplaetzen), Fehler und uebersprungene Laeufe (Sperre).
- Neuer Button "Protokoll" oeffnet LogViewerForm (Aktualisieren/Leeren/Ordner
  oeffnen, scrollt ans Ende).
- README/CHANGELOG aktualisiert.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:17:53 +02:00
duffyduck b8a7fda7bf Release v0.0.0.28 2026-06-08 13:02:51 +02:00
duffyduckandClaude Opus 4.8 257b6fb33d Only notify clients actually affected by a conflict
Bisher bekam jeder Arbeitsplatz, der den Konflikt-Kontakt im Adressbuch hat,
den Hinweis - auch wenn er den Wert gar nicht selbst gepflegt hat.

Jetzt zeigt ein Client eine fremde Konflikt-Notiz nur, wenn er den Kontakt hat
UND sein eigener Feldwert vom uebernommenen (Gewinner-)Wert abweicht. Die
Pruefung laeuft VOR dem Sync (gegen den eigenen Mapping-Snapshot), bevor der
Sync den Stand auf den Gewinner-Wert angleicht.

- FieldConflict/ConflictNotice: stabiler FieldKey zusaetzlich zum Anzeige-Label.
- ContactMerger: GetValue/ValuesEqual per FieldKey (telefon-normalisiert).
- ConflictNotifier.GetPending: Filter "eigener Wert != Gewinner-Wert", bekommt
  StarfaceId -> eigener Kontaktstand.
- MainForm zeigt die Hinweise jetzt vor dem Sync und liefert den eigenen Stand
  aus den Mapping-Snapshots.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:01:02 +02:00
duffyduckandClaude Opus 4.8 cf2970a41a Add cross-client conflict notifications (step 3)
Wird ein echter Feld-Konflikt aufgeloest, erfahren jetzt auch die ANDEREN
Arbeitsplaetze davon - nicht nur der aufloesende Client.

- ConflictNotice-Modell + ConflictNotifier: schreibt pro Konflikt eine Notiz
  in <shared>/conflicts/ (nach StarfaceId), liest beim Sync ungesehene Notizen
  zu eigenen Kontakten, zeigt sie als Tray-Hinweis und merkt sich gezeigte
  lokal (seen-conflicts.json). Veraltete Notizen (>7 Tage) werden aufgeraeumt.
- MainForm: schreibt nach einem Sync mit Konflikten die Notizen und zeigt
  ausstehende Notizen anderer Clients (gefiltert auf eigene gemappte
  StarfaceIds). AcquireCrossClientLock nimmt jetzt das gemeinsame Verzeichnis
  als Parameter.
- README/CHANGELOG aktualisiert.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 12:54:01 +02:00
duffyduckandClaude Opus 4.8 5a0203e49e Document multi-client sync lock in README
Beschreibt Lock-Datei starface-sync.lock: atomares Anlegen (CreateNew),
nur waehrend des Syncs vorhanden, Inhalt (Host/User/Zeit/PID), Warte- und
Absturz-Verhalten, sowie den Hinweis auf bidirektionalen Modus im Mehrplatz.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 12:47:28 +02:00
23 changed files with 1670 additions and 193 deletions
+41
View File
@@ -38,6 +38,40 @@ Versionsschema ist `x.x.x.x` (siehe `release.sh`).
### Hinzugefuegt
- **Autostart-Verwaltung in den Einstellungen.** Neuer Abschnitt "Autostart" mit
zwei Optionen: "Nur fuer diesen Benutzer" (HKCU) und "Fuer alle Benutzer"
(HKLM). Die Option fuer alle Benutzer ist nur mit Admin-Rechten aenderbar -
darueber laesst sich auch der vom Setup gesetzte Autostart fuer alle wieder
entfernen. Das Setup setzt den Autostart weiterhin fuer alle Benutzer (HKLM),
der Hinweis im Installer wurde entsprechend klargestellt.
- **Protokoll automatisch leeren (Einstellung).** Neuer Wert "Protokoll
auto-leeren - Eintraege aelter als (Tage)". Bei 0 (Standard) bleibt alles
erhalten; bei >0 werden aeltere Eintraege automatisch entfernt (beim Start,
vor jedem Sync, beim Oeffnen des Protokolls und beim Speichern der
Einstellungen).
- **Protokoll zeigt jetzt, WAS geaendert wurde.** Pro Sync werden die einzelnen
Aktionen (erstellt / aktualisiert / geloescht / verknuepft / zusammengefuehrt je
Kontakt) ins Protokoll geschrieben - sowohl beim manuellen Sync (Fenster) als
auch bei Auto-/Tray-Sync.
- **Benachrichtigungen schaltbar (Einstellungen).** Zwei unabhaengige Haken:
"Tray-Benachrichtigungen (allgemein)" fuer Info-Meldungen (Sync laeuft/fertig)
und "Benachrichtigungen bei Warnungen/Fehlern" fuer Konflikte und Fehler. So
kann man z.B. nur noch bei Konflikten/Fehlern benachrichtigt werden - oder gar
nicht. Das Protokoll wird unabhaengig davon immer geschrieben.
- **Protokoll (Logdatei) + "Protokoll"-Button.** Syncs, Ergebnisse, Konflikte
(lokal und von anderen Arbeitsplaetzen) und Fehler werden dauerhaft in
`%AppData%\StarfaceOutlookSync\sync.log` festgehalten - so ist auch nach dem
Verschwinden einer Tray-Meldung nachvollziehbar, wer/was/wann. Im Hauptfenster
oeffnet der Button "Protokoll" einen Betrachter (Aktualisieren/Leeren/Ordner
oeffnen). Die Datei rotiert bei 2 MB.
- **Clientuebergreifende Konflikt-Hinweise (Mehrplatz).** Wird ein echter
Feld-Konflikt aufgeloest, legt der Client eine Notiz im gemeinsamen Verzeichnis
(`conflicts/`) ab - zugeordnet nach Kontakt (StarfaceId). Ein anderer
Arbeitsplatz zeigt die Meldung beim naechsten Sync nur an, wenn er den Kontakt
selbst hat UND sein eigener Feldwert vom uebernommenen Wert abweicht - so wird
der ueberschriebene Arbeitsplatz gewarnt, waehrend bereits aktuelle Clients
nicht benachrichtigt werden. Bereits gezeigte Notizen merkt sich jeder Client
lokal; alte Notizen werden nach 7 Tagen aufgeraeumt.
- **Clientuebergreifende Sync-Sperre (Mehrplatz).** In den Einstellungen laesst
sich ein gemeinsames Verzeichnis (Netzlaufwerk/UNC) hinterlegen. Synct ein
Arbeitsplatz, legt er dort eine Lock-Datei an (atomar via `CreateNew`); andere
@@ -56,6 +90,13 @@ Versionsschema ist `x.x.x.x` (siehe `release.sh`).
### Geaendert
- **Manueller und automatischer Sync vereinheitlicht.** Beide Pfade laufen jetzt
ueber einen gemeinsamen `SyncCoordinator` und nutzen damit dieselben Schutz-
und Komfortfunktionen: lokaler Re-Entrancy-Schutz (prozessweit - auch manuell
vs. automatisch koennen nicht mehr gleichzeitig laufen), clientuebergreifende
Lock-Datei, Konflikt-Notizen anderer Arbeitsplaetze und vollstaendiges
Protokoll. Vorher umging der manuelle "Synchronisieren"-Button (Fenster) die
Lock-Datei und einen Teil des Protokolls.
- **Doppelte Syncs verhindert (lokal).** Der Schutz gegen gleichzeitig laufende
Syncs (manuell + Auto-Sync-Timer) ist jetzt atomar (`Interlocked`) statt eines
nicht-atomaren `volatile bool`, bei dem beide in einem Zeitfenster
+49
View File
@@ -260,11 +260,60 @@ StarfaceOutlookSync.exe
Alle Daten werden lokal pro Benutzer gespeichert:
- `%AppData%\StarfaceOutlookSync\profiles.json` - Sync-Profile mit Zugangsdaten
- `%AppData%\StarfaceOutlookSync\mappings\` - Kontakt-Zuordnungen pro Profil
- `%AppData%\StarfaceOutlookSync\sync.log` - Protokoll (Syncs, Konflikte, Fehler);
im Hauptfenster ueber den Button **Protokoll** einsehbar
### SSL-Zertifikate
Self-signed Zertifikate der Starface werden automatisch akzeptiert. Es ist kein manueller Zertifikat-Import erforderlich.
### Mehrplatz-Betrieb / Sync-Sperre
Mehrere Arbeitsplaetze koennen dasselbe Starface-Adressbuch pflegen. Damit sich
gleichzeitig laufende Syncs nicht ins Gehege kommen (Dubletten, ueberschriebene
Aenderungen), gibt es zwei Schutzebenen:
**1. Lokal (immer aktiv):** Auf einem PC kann nie mehr als ein Sync gleichzeitig
laufen. Startet der Auto-Sync-Timer, waehrend ein manueller Sync laeuft (oder
umgekehrt), wird der zweite Lauf uebersprungen. Atomar per `Interlocked`.
**2. Clientuebergreifend (optional):** In den Einstellungen kann ein
**gemeinsames Verzeichnis** (Netzlaufwerk oder UNC-Pfad wie
`\\server\freigabe\sync`) hinterlegt werden. Funktionsweise:
- Beim Start eines Syncs legt der Client dort die Datei **`starface-sync.lock`**
an - **atomar** ueber `FileMode.CreateNew`: das Anlegen schlaegt fehl, wenn
die Datei bereits existiert. Damit kann immer nur ein Client gleichzeitig die
Sperre halten.
- Die Datei wird waehrend des gesamten Syncs **offen gehalten** und am Ende
wieder **geloescht**. Sie existiert also nur, solange tatsaechlich gerade
synchronisiert wird (bei kleinen Adressbuechern nur sehr kurz).
- Inhalt der Datei: `Rechnername | Benutzer | UTC-Zeitstempel | Prozess-ID` -
damit man sieht, wer gerade synct.
- Findet ein anderer Client die Sperre vor, **wartet** er (Abfrage alle 3
Sekunden, bis zu 2 Minuten) und synct erst danach. Wird die Sperre nicht frei,
wird der Lauf uebersprungen und beim naechsten Intervall erneut versucht.
- **Absturzsicher:** Stuerzt ein Client mitten im Sync ab, gibt Windows das
Datei-Handle frei. Die verwaiste Lock-Datei gilt nach 15 Minuten als veraltet
und wird vom naechsten Client uebernommen. Lebt der Halter noch, scheitert das
Loeschen am offenen Handle - die Sperre bleibt also korrekt bestehen.
- Ist **kein** Verzeichnis konfiguriert oder es ist nicht erreichbar, laeuft der
Sync ohne diese Sperre weiter (die lokale Sperre bleibt aktiv).
**Konflikt-Hinweise:** Wird im bidirektionalen Modus ein echter Feld-Konflikt
aufgeloest (dasselbe Feld auf beiden Seiten unterschiedlich geaendert, Outlook
gewinnt), legt der Client eine Notiz im Unterordner `conflicts/` des gemeinsamen
Verzeichnisses ab - zugeordnet ueber die StarfaceId des Kontakts. Beim naechsten
Sync zeigt ein anderer Arbeitsplatz die Meldung als Tray-Hinweis - aber **nur,
wenn er den Kontakt selbst hat UND sein eigener Feldwert vom uebernommenen Wert
abweicht** (so erfaehrt der ueberschriebene Arbeitsplatz davon, waehrend Clients,
die den Wert ohnehin schon haben, nicht benachrichtigt werden). Gezeigte Notizen
merkt sich jeder Client lokal, veraltete Notizen werden nach 7 Tagen entfernt.
> Hinweis: Im Mehrplatz-Betrieb sollte die **bidirektionale** Sync-Richtung
> verwendet werden. Die Ein-Richtungs-Modi ("Ersetzen") wuerden die von anderen
> Arbeitsplaetzen gepflegten Kontakte loeschen.
## Lizenz
Proprietaer - Alle Rechte vorbehalten.
+2 -2
View File
@@ -2,7 +2,7 @@
; Erfordert Inno Setup 6.x (https://jrsoftware.org/isinfo.php)
#define MyAppName "Starface Outlook Sync"
#define MyAppVersion "0.0.0.27"
#define MyAppVersion "0.0.0.30"
#define MyAppPublisher "HackerSoft - Hacker-Net Telekommunikation"
#define MyAppURL "https://www.hacker-net.de"
#define MyAppExeName "StarfaceOutlookSync.exe"
@@ -32,7 +32,7 @@ Name: "german"; MessagesFile: "compiler:Languages\German.isl"
[Tasks]
Name: "desktopicon"; Description: "Desktop-Verknuepfung erstellen"; GroupDescription: "Zusaetzliche Optionen:"
Name: "autostart"; Description: "Bei Windows-Anmeldung automatisch starten"; GroupDescription: "Zusaetzliche Optionen:"; Flags: checkedonce
Name: "autostart"; Description: "Bei Windows-Anmeldung automatisch starten (fuer ALLE Benutzer; einzelne Benutzer spaeter in den Einstellungen)"; GroupDescription: "Zusaetzliche Optionen:"; Flags: checkedonce
[Files]
; Hauptanwendung - Pfad anpassen nach Build
@@ -0,0 +1,26 @@
namespace StarfaceOutlookSync.Models
{
/// <summary>
/// Hinweis ueber einen aufgeloesten Feld-Konflikt, der im gemeinsamen
/// Verzeichnis abgelegt wird, damit auch andere Arbeitsplaetze (die denselben
/// Kontakt pflegen) erfahren, dass ein Wert ueberschrieben wurde.
/// </summary>
public class ConflictNotice
{
public string Id { get; set; } = "";
public string ByHost { get; set; } = "";
public string ByUser { get; set; } = "";
public string TimestampUtc { get; set; } = "";
public string StarfaceId { get; set; } = "";
public string ContactName { get; set; } = "";
public string Field { get; set; } = "";
public string FieldKey { get; set; } = "";
public string OutlookValue { get; set; } = "";
public string StarfaceValue { get; set; } = "";
public string Winner { get; set; } = "";
public override string ToString() =>
$"{ContactName}: Feld '{Field}' geaendert an Arbeitsplatz {ByHost} " +
$"(Outlook: '{OutlookValue}' / Starface: '{StarfaceValue}') -> {Winner} uebernommen";
}
}
+41 -5
View File
@@ -1,5 +1,14 @@
using Newtonsoft.Json;
namespace StarfaceOutlookSync.Models
{
/// <summary>Welche Telefonanlage auf der anderen Seite steht.</summary>
public enum PhoneSystem
{
Starface,
Fonaria
}
public enum SyncDirection
{
Both,
@@ -7,8 +16,12 @@ namespace StarfaceOutlookSync.Models
StarfaceToOutlook
}
public class StarfaceConnection
public class SystemConnection
{
// Voreinstellung Starface, damit Profile aus der Zeit vor Fonaria
// unveraendert weiterlaufen: Was im JSON fehlt, ist eine Starface.
public PhoneSystem System { get; set; } = PhoneSystem.Starface;
public string Host { get; set; } = "";
public int Port { get; set; } = 443;
public bool UseSsl { get; set; } = true;
@@ -16,7 +29,16 @@ namespace StarfaceOutlookSync.Models
public string Password { get; set; } = "";
}
public class StarfaceAddressBook
/// <summary>
/// Ein Adressbuch auf der Gegenseite.
///
/// Die Felder heissen noch nach der Starface, weil dort ihre Bedeutung
/// herkommt: <c>Type</c> unterscheidet zentrales, persoenliches und
/// Tag-Adressbuch, <c>TagId</c> traegt die Kennung. Bei Fonaria steht in
/// <c>TagId</c> schlicht die Nummer des Adressbuchs und in <c>Type</c>
/// dessen Art (private, shared, system).
/// </summary>
public class RemoteAddressBook
{
public string Type { get; set; } = "central"; // central, user, tag
public string UserId { get; set; } = "";
@@ -30,8 +52,13 @@ namespace StarfaceOutlookSync.Models
{
public string Id { get; set; } = "";
public string Name { get; set; } = "";
public StarfaceConnection StarfaceConnection { get; set; } = new StarfaceConnection();
public StarfaceAddressBook StarfaceAddressBook { get; set; } = new StarfaceAddressBook();
// Die JSON-Namen bleiben, wie sie waren — sonst verloeren alle
// bestehenden Profile beim ersten Start ihre Verbindungsdaten.
[JsonProperty("StarfaceConnection")]
public SystemConnection Connection { get; set; } = new SystemConnection();
[JsonProperty("StarfaceAddressBook")]
public RemoteAddressBook AddressBook { get; set; } = new RemoteAddressBook();
public string OutlookFolderPath { get; set; } = "";
public string OutlookFolderName { get; set; } = "Kontakte";
public SyncDirection SyncDirection { get; set; } = SyncDirection.Both;
@@ -44,6 +71,10 @@ namespace StarfaceOutlookSync.Models
{
public string ProfileId { get; set; } = "";
public string OutlookEntryId { get; set; } = "";
// Die Kennung auf der Gegenseite — bei Fonaria die Kontakt-ID. Der
// Name bleibt: Er steht in jeder bereits gespeicherten Zuordnung, und
// ein Umbenennen wuerde sie alle entwerten.
public string StarfaceId { get; set; } = "";
// Getrennte Baselines pro Seite. Outlook und Starface stellen denselben
@@ -73,6 +104,10 @@ namespace StarfaceOutlookSync.Models
public int Errors { get; set; }
public System.Collections.Generic.List<string> ErrorMessages { get; set; } = new System.Collections.Generic.List<string>();
// Was konkret veraendert wurde (erstellt/aktualisiert/geloescht je Kontakt),
// fuer das Protokoll.
public System.Collections.Generic.List<string> Changes { get; set; } = new System.Collections.Generic.List<string>();
// Echte Feld-Konflikte (dasselbe Feld auf beiden Seiten geaendert), die
// ueber die Vorrang-Regel aufgeloest wurden. Fuer Benutzer-Hinweise.
public System.Collections.Generic.List<FieldConflict> Conflicts { get; set; } = new System.Collections.Generic.List<FieldConflict>();
@@ -82,7 +117,8 @@ namespace StarfaceOutlookSync.Models
{
public string StarfaceId { get; set; } = "";
public string ContactName { get; set; } = "";
public string Field { get; set; } = "";
public string Field { get; set; } = ""; // Anzeige-Label, z.B. "E-Mail"
public string FieldKey { get; set; } = ""; // stabiler Schluessel, z.B. "Email"
public string OutlookValue { get; set; } = "";
public string StarfaceValue { get; set; } = "";
public string Winner { get; set; } = ""; // "Outlook" oder "Starface"
@@ -2,6 +2,22 @@ namespace StarfaceOutlookSync.Models
{
public class UnifiedContact
{
/// <summary>
/// Welche vCard-Eigenschaften dieses Modell abbildet.
///
/// Fonaria fuehrt den Kontakt im vollen vCard-Umfang — Kategorien,
/// Jahrestag, Spitzname, Bild, zweite Anschrift. Hier steht davon nur
/// ein Ausschnitt, weil die Starface nicht mehr kann. Beim Schreiben
/// nach Fonaria wird diese Liste mitgeschickt: Sie sagt der Anlage,
/// wofuer wir zustaendig sind. Alles andere bleibt dort unangetastet,
/// statt geloescht zu werden, nur weil wir es nicht kennen.
/// </summary>
public static readonly string[] VcardFelder =
{
"FN", "N", "ORG", "TITLE", "TEL", "EMAIL", "ADR", "URL", "NOTE", "BDAY"
};
public string OutlookEntryId { get; set; } = "";
public string StarfaceId { get; set; } = "";
public string FirstName { get; set; } = "";
@@ -11,6 +11,15 @@ namespace StarfaceOutlookSync.Models
public bool SyncOnStart { get; set; } = false;
public bool AutoAcceptOutlookPrompt { get; set; } = false;
// Tray-Benachrichtigungen. Allgemein = Info-Meldungen (Sync laeuft/fertig).
// WarnungenFehler = nur Konflikte und Fehler. Beide unabhaengig schaltbar.
public bool NotificationsEnabled { get; set; } = true;
public bool NotifyWarningsErrors { get; set; } = true;
// Protokoll-Eintraege aelter als X Tage automatisch entfernen. 0 = aus
// (alle Eintraege bleiben erhalten).
public int LogRetentionDays { get; set; } = 0;
// Gemeinsames Verzeichnis (Netzlaufwerk/UNC) fuer die clientuebergreifende
// Sync-Sperre. Leer = keine Sperre (nur lokaler Schutz). Verhindert, dass
// mehrere Arbeitsplaetze gleichzeitig dasselbe Adressbuch synchronisieren.
@@ -0,0 +1,76 @@
using System;
using System.Diagnostics;
using System.Security.Principal;
using Microsoft.Win32;
namespace StarfaceOutlookSync.Services
{
/// <summary>
/// Verwaltet den Windows-Autostart ueber die Run-Schluessel:
/// - pro Benutzer -> HKCU\...\Run
/// - alle Benutzer -> HKLM\...\Run (nur mit Admin-Rechten aenderbar)
/// Das Setup setzt den Autostart fuer alle Benutzer (HKLM); hierueber laesst
/// er sich nachtraeglich umstellen oder entfernen.
/// </summary>
public static class AutostartManager
{
private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string ValueName = "StarfaceOutlookSync";
private static string ExePath()
{
try
{
var p = Process.GetCurrentProcess().MainModule?.FileName;
if (!string.IsNullOrEmpty(p)) return p;
}
catch { }
return System.Reflection.Assembly.GetEntryAssembly()?.Location ?? "";
}
public static bool IsAdmin()
{
try
{
using (var id = WindowsIdentity.GetCurrent())
return new WindowsPrincipal(id).IsInRole(WindowsBuiltInRole.Administrator);
}
catch { return false; }
}
public static bool GetUserAutostart() => HasValue(Registry.CurrentUser);
public static bool GetMachineAutostart() => HasValue(Registry.LocalMachine);
public static void SetUserAutostart(bool enabled) => SetValue(Registry.CurrentUser, enabled);
/// <summary>Setzt/entfernt den Autostart fuer alle Benutzer. Braucht Admin-Rechte. Gibt Erfolg zurueck.</summary>
public static bool SetMachineAutostart(bool enabled) => SetValue(Registry.LocalMachine, enabled);
private static bool HasValue(RegistryKey root)
{
try
{
using (var k = root.OpenSubKey(RunKey, false))
return k?.GetValue(ValueName) != null;
}
catch { return false; }
}
private static bool SetValue(RegistryKey root, bool enabled)
{
try
{
using (var k = root.CreateSubKey(RunKey))
{
if (k == null) return false;
if (enabled)
k.SetValue(ValueName, "\"" + ExePath() + "\"", RegistryValueKind.String);
else if (k.GetValue(ValueName) != null)
k.DeleteValue(ValueName, false);
}
return true;
}
catch { return false; }
}
}
}
@@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using StarfaceOutlookSync.Models;
namespace StarfaceOutlookSync.Services
{
/// <summary>
/// Verteilt Konflikt-Hinweise ueber das gemeinsame Verzeichnis an alle
/// Arbeitsplaetze. Wer einen echten Feld-Konflikt aufloest, legt eine Notiz
/// ab; andere Clients zeigen beim naechsten Sync die Notizen zu Kontakten,
/// die sie selbst gemappt haben (per StarfaceId). Bereits gezeigte Notizen
/// merkt sich jeder Client lokal, damit sie nicht doppelt erscheinen.
/// </summary>
public class ConflictNotifier
{
private static readonly TimeSpan Ttl = TimeSpan.FromDays(7);
private readonly string _seenFile;
public ConflictNotifier()
{
var dir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"StarfaceOutlookSync");
try { Directory.CreateDirectory(dir); } catch { }
_seenFile = Path.Combine(dir, "seen-conflicts.json");
}
private static string ConflictsDir(string sharedDir) => Path.Combine(sharedDir, "conflicts");
/// <summary>Legt fuer jeden Konflikt eine Notiz im gemeinsamen Verzeichnis ab.</summary>
public void Write(string sharedDir, IEnumerable<FieldConflict> conflicts)
{
if (string.IsNullOrWhiteSpace(sharedDir)) return;
var list = conflicts?.ToList();
if (list == null || list.Count == 0) return;
try
{
var dir = ConflictsDir(sharedDir);
Directory.CreateDirectory(dir);
var host = Environment.MachineName;
var user = Environment.UserName;
var ts = DateTime.UtcNow.ToString("o");
foreach (var c in list)
{
var notice = new ConflictNotice
{
Id = Guid.NewGuid().ToString("N"),
ByHost = host,
ByUser = user,
TimestampUtc = ts,
StarfaceId = c.StarfaceId,
ContactName = c.ContactName,
Field = c.Field,
FieldKey = c.FieldKey,
OutlookValue = c.OutlookValue,
StarfaceValue = c.StarfaceValue,
Winner = c.Winner
};
try
{
File.WriteAllText(Path.Combine(dir, notice.Id + ".json"),
JsonConvert.SerializeObject(notice, Formatting.Indented));
}
catch { }
}
}
catch { }
}
/// <summary>
/// Liefert ungesehene Konflikt-Notizen, die Kontakte dieses Clients
/// betreffen und nicht von ihm selbst stammen. Es werden nur die Notizen
/// zurueckgegeben, bei denen der EIGENE aktuelle Feldwert vom uebernommenen
/// (Gewinner-)Wert abweicht - wer den Wert ohnehin schon hat, wird nicht
/// benachrichtigt. myContacts bildet StarfaceId -> eigener Kontaktstand ab.
/// Markiert verarbeitete Notizen als gesehen und raeumt veraltete auf.
/// </summary>
public List<ConflictNotice> GetPending(string sharedDir, IDictionary<string, UnifiedContact> myContacts)
{
var result = new List<ConflictNotice>();
if (string.IsNullOrWhiteSpace(sharedDir)) return result;
var dir = ConflictsDir(sharedDir);
string[] files;
try
{
if (!Directory.Exists(dir)) return result;
files = Directory.GetFiles(dir, "*.json");
}
catch { return result; }
var seen = LoadSeen();
var host = Environment.MachineName;
var existingIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var f in files)
{
ConflictNotice n = null;
try { n = JsonConvert.DeserializeObject<ConflictNotice>(File.ReadAllText(f)); }
catch { }
if (n == null || string.IsNullOrEmpty(n.Id)) continue;
// Veraltete Notizen entfernen.
if (DateTime.TryParse(n.TimestampUtc, out var ts)
&& DateTime.UtcNow - ts.ToUniversalTime() > Ttl)
{
try { File.Delete(f); } catch { }
continue;
}
existingIds.Add(n.Id);
if (seen.Contains(n.Id)) continue; // schon gezeigt
if (string.Equals(n.ByHost, host, StringComparison.OrdinalIgnoreCase))
{
seen.Add(n.Id); // selbst erzeugt -> nicht erneut anzeigen
continue;
}
// Habe ich diesen Kontakt ueberhaupt?
UnifiedContact mine = null;
bool haveContact = !string.IsNullOrEmpty(n.StarfaceId)
&& myContacts != null
&& myContacts.TryGetValue(n.StarfaceId, out mine);
if (!haveContact)
continue; // betrifft mich nicht (kein seen -> evtl. spaeter relevant)
// Bin ich wirklich betroffen? Nur wenn mein aktueller Feldwert vom
// uebernommenen Wert abweicht. Wer den Gewinner-Wert schon hat, wird
// nicht benachrichtigt.
if (mine != null && !string.IsNullOrEmpty(n.FieldKey))
{
var winnerValue = string.Equals(n.Winner, "Outlook", StringComparison.OrdinalIgnoreCase)
? n.OutlookValue : n.StarfaceValue;
var myValue = ContactMerger.GetValue(mine, n.FieldKey);
if (ContactMerger.ValuesEqual(n.FieldKey, myValue, winnerValue))
{
seen.Add(n.Id); // nicht betroffen -> als erledigt merken
continue;
}
}
result.Add(n);
seen.Add(n.Id);
}
// Gesehen-Liste auf noch vorhandene Notizen eindampfen.
seen.IntersectWith(existingIds);
SaveSeen(seen);
return result;
}
private HashSet<string> LoadSeen()
{
try
{
if (File.Exists(_seenFile))
return new HashSet<string>(
JsonConvert.DeserializeObject<List<string>>(File.ReadAllText(_seenFile)) ?? new List<string>(),
StringComparer.OrdinalIgnoreCase);
}
catch { }
return new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
private void SaveSeen(HashSet<string> seen)
{
try { File.WriteAllText(_seenFile, JsonConvert.SerializeObject(seen.ToList())); }
catch { }
}
}
}
@@ -15,6 +15,7 @@ namespace StarfaceOutlookSync.Services
{
private class FieldDef
{
public string Key;
public string Label;
public Func<UnifiedContact, string> Get;
public Action<UnifiedContact, string> Set;
@@ -23,28 +24,43 @@ namespace StarfaceOutlookSync.Services
private static readonly FieldDef[] Fields = new[]
{
new FieldDef { Label = "Vorname", Get = c => c.FirstName, Set = (c, v) => c.FirstName = v },
new FieldDef { Label = "Nachname", Get = c => c.LastName, Set = (c, v) => c.LastName = v },
new FieldDef { Label = "Firma", Get = c => c.Company, Set = (c, v) => c.Company = v },
new FieldDef { Label = "Position", Get = c => c.JobTitle, Set = (c, v) => c.JobTitle = v },
new FieldDef { Label = "E-Mail", Get = c => c.Email, Set = (c, v) => c.Email = v },
new FieldDef { Label = "E-Mail 2", Get = c => c.EmailSecondary, Set = (c, v) => c.EmailSecondary = v },
new FieldDef { Label = "Telefon", Get = c => c.PhoneWork, Set = (c, v) => c.PhoneWork = v, IsPhone = true },
new FieldDef { Label = "Mobil", Get = c => c.PhoneMobile, Set = (c, v) => c.PhoneMobile = v, IsPhone = true },
new FieldDef { Label = "Telefon privat", Get = c => c.PhoneHome, Set = (c, v) => c.PhoneHome = v, IsPhone = true },
new FieldDef { Label = "Fax", Get = c => c.Fax, Set = (c, v) => c.Fax = v, IsPhone = true },
new FieldDef { Label = "Strasse", Get = c => c.Street, Set = (c, v) => c.Street = v },
new FieldDef { Label = "Ort", Get = c => c.City, Set = (c, v) => c.City = v },
new FieldDef { Label = "PLZ", Get = c => c.PostalCode, Set = (c, v) => c.PostalCode = v },
new FieldDef { Label = "Bundesland", Get = c => c.State, Set = (c, v) => c.State = v },
new FieldDef { Label = "Land", Get = c => c.Country, Set = (c, v) => c.Country = v },
new FieldDef { Label = "Webseite", Get = c => c.Website, Set = (c, v) => c.Website = v },
new FieldDef { Label = "Notizen", Get = c => c.Notes, Set = (c, v) => c.Notes = v },
new FieldDef { Label = "Anrede", Get = c => c.Salutation, Set = (c, v) => c.Salutation = v },
new FieldDef { Label = "Titel", Get = c => c.Title, Set = (c, v) => c.Title = v },
new FieldDef { Label = "Geburtstag", Get = c => c.Birthday, Set = (c, v) => c.Birthday = v },
new FieldDef { Key = "FirstName", Label = "Vorname", Get = c => c.FirstName, Set = (c, v) => c.FirstName = v },
new FieldDef { Key = "LastName", Label = "Nachname", Get = c => c.LastName, Set = (c, v) => c.LastName = v },
new FieldDef { Key = "Company", Label = "Firma", Get = c => c.Company, Set = (c, v) => c.Company = v },
new FieldDef { Key = "JobTitle", Label = "Position", Get = c => c.JobTitle, Set = (c, v) => c.JobTitle = v },
new FieldDef { Key = "Email", Label = "E-Mail", Get = c => c.Email, Set = (c, v) => c.Email = v },
new FieldDef { Key = "EmailSecondary", Label = "E-Mail 2", Get = c => c.EmailSecondary, Set = (c, v) => c.EmailSecondary = v },
new FieldDef { Key = "PhoneWork", Label = "Telefon", Get = c => c.PhoneWork, Set = (c, v) => c.PhoneWork = v, IsPhone = true },
new FieldDef { Key = "PhoneMobile", Label = "Mobil", Get = c => c.PhoneMobile, Set = (c, v) => c.PhoneMobile = v, IsPhone = true },
new FieldDef { Key = "PhoneHome", Label = "Telefon privat", Get = c => c.PhoneHome, Set = (c, v) => c.PhoneHome = v, IsPhone = true },
new FieldDef { Key = "Fax", Label = "Fax", Get = c => c.Fax, Set = (c, v) => c.Fax = v, IsPhone = true },
new FieldDef { Key = "Street", Label = "Strasse", Get = c => c.Street, Set = (c, v) => c.Street = v },
new FieldDef { Key = "City", Label = "Ort", Get = c => c.City, Set = (c, v) => c.City = v },
new FieldDef { Key = "PostalCode", Label = "PLZ", Get = c => c.PostalCode, Set = (c, v) => c.PostalCode = v },
new FieldDef { Key = "State", Label = "Bundesland", Get = c => c.State, Set = (c, v) => c.State = v },
new FieldDef { Key = "Country", Label = "Land", Get = c => c.Country, Set = (c, v) => c.Country = v },
new FieldDef { Key = "Website", Label = "Webseite", Get = c => c.Website, Set = (c, v) => c.Website = v },
new FieldDef { Key = "Notes", Label = "Notizen", Get = c => c.Notes, Set = (c, v) => c.Notes = v },
new FieldDef { Key = "Salutation", Label = "Anrede", Get = c => c.Salutation, Set = (c, v) => c.Salutation = v },
new FieldDef { Key = "Title", Label = "Titel", Get = c => c.Title, Set = (c, v) => c.Title = v },
new FieldDef { Key = "Birthday", Label = "Geburtstag", Get = c => c.Birthday, Set = (c, v) => c.Birthday = v },
};
/// <summary>Liest den Wert eines Feldes per stabilem Schluessel.</summary>
public static string GetValue(UnifiedContact c, string key)
{
if (c == null || string.IsNullOrEmpty(key)) return "";
var f = Fields.FirstOrDefault(x => x.Key == key);
return f == null ? "" : (f.Get(c) ?? "");
}
/// <summary>Vergleicht zwei Feldwerte (telefon-normalisiert je nach Feld).</summary>
public static bool ValuesEqual(string key, string a, string b)
{
var f = Fields.FirstOrDefault(x => x.Key == key);
return Equal(a ?? "", b ?? "", f?.IsPhone ?? false);
}
/// <summary>
/// Fuehrt den Outlook- und Starface-Stand gegen ihre jeweilige Baseline
/// zusammen. outlookWins entscheidet bei echten Feld-Konflikten.
@@ -95,6 +111,7 @@ namespace StarfaceOutlookSync.Services
StarfaceId = starface.StarfaceId,
ContactName = outlook.DisplayName,
Field = f.Label,
FieldKey = f.Key,
OutlookValue = olv,
StarfaceValue = sfv,
Winner = outlookWins ? "Outlook" : "Starface"
@@ -0,0 +1,432 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StarfaceOutlookSync.Models;
namespace StarfaceOutlookSync.Services
{
/// <summary>
/// Die Gegenseite Fonaria.
///
/// Anders als die Starface haelt Fonaria jeden Kontakt als vollstaendige
/// vCard vor — mit Bild, Kategorien, Jahrestag, mehreren Anschriften. Das
/// Sync-Modell dieser Anwendung bildet davon nur einen Ausschnitt ab.
/// Deshalb schickt jeder Schreibvorgang <c>verwaltet</c> mit: die Liste der
/// Eigenschaften, fuer die wir uns zustaendig erklaeren. Die Anlage
/// schreibt genau diese in die vorhandene Karte und laesst den Rest stehen.
///
/// Ohne das waere der erste Abgleich verheerend: Ein aus Outlook
/// gespiegelter Kontakt haette hinterher kein Bild und keine Kategorien
/// mehr — nicht weil jemand sie geloescht haette, sondern weil wir sie
/// nicht kannten.
/// </summary>
public class FonariaApiClient : IContactBackend
{
private readonly HttpClient _http;
private readonly SystemConnection _connection;
private readonly string _baseUrl;
private string _token;
public event Action<string> OnDebug;
public string SystemName => "Fonaria";
public IReadOnlyList<string> VerwalteteFelder => UnifiedContact.VcardFelder;
public FonariaApiClient(SystemConnection connection)
{
_connection = connection;
var handler = new HttpClientHandler();
// Wie bei der Starface: Anlagen im eigenen Netz tragen oft ein
// selbst ausgestelltes Zertifikat.
handler.ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) => true;
_http = new HttpClient(handler);
_http.Timeout = TimeSpan.FromSeconds(30);
var protocol = connection.UseSsl ? "https" : "http";
var portPart = (connection.UseSsl && connection.Port == 443) ||
(!connection.UseSsl && connection.Port == 80)
? "" : $":{connection.Port}";
_baseUrl = $"{protocol}://{connection.Host}{portPart}/api/v1";
}
// -------------------------------------------------------------------
// Anmeldung
// -------------------------------------------------------------------
public async Task<bool> LoginAsync()
{
try
{
var body = new { username = _connection.LoginId, password = _connection.Password };
var content = new StringContent(
JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
var resp = await _http.PostAsync($"{_baseUrl}/auth/login", content);
var respBody = await resp.Content.ReadAsStringAsync();
if (!resp.IsSuccessStatusCode)
{
OnDebug?.Invoke($"Fonaria-Anmeldung fehlgeschlagen: {(int)resp.StatusCode}\n{respBody}");
return false;
}
_token = JObject.Parse(respBody)["access_token"]?.ToString();
if (string.IsNullOrEmpty(_token)) return false;
_http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", _token);
return true;
}
catch (Exception ex)
{
OnDebug?.Invoke($"Fonaria-Anmeldung fehlgeschlagen: {ex.Message}");
return false;
}
}
public Task LogoutAsync()
{
// Fonaria-Token laufen von selbst ab; es gibt nichts abzumelden.
_token = null;
_http.DefaultRequestHeaders.Authorization = null;
return Task.CompletedTask;
}
// -------------------------------------------------------------------
// Lesen
// -------------------------------------------------------------------
public async Task<List<RemoteAddressBook>> GetAddressBooksAsync()
{
var buecher = new List<RemoteAddressBook>();
var resp = await _http.GetAsync($"{_baseUrl}/addressbooks");
if (!resp.IsSuccessStatusCode)
{
OnDebug?.Invoke($"Adressbuecher nicht abrufbar: {(int)resp.StatusCode}");
return buecher;
}
foreach (var eintrag in JArray.Parse(await resp.Content.ReadAsStringAsync()))
{
var art = eintrag["kind"]?.ToString() ?? "shared";
// Das Benutzerverzeichnis pflegt die Anlage selbst und weist
// jeden Schreibversuch ab. Als Sync-Ziel waere es eine Falle.
if (art == "system") continue;
buecher.Add(new RemoteAddressBook
{
Type = art,
TagId = eintrag["id"]?.ToString() ?? "",
Name = eintrag["name"]?.ToString() ?? "",
UserId = eintrag["owner_id"]?.ToString() ?? ""
});
}
return buecher;
}
public async Task<List<UnifiedContact>> GetContactsAsync(RemoteAddressBook book)
{
// Bewusst mit full=1: Die Kurzform der Liste traegt nur Name, Firma
// und Nummern. Wer damit abgleicht, haelt jeden Kontakt fuer
// veraendert und schreibt bei jedem Durchlauf alles neu.
var url = $"{_baseUrl}/addressbooks/{book.TagId}/contacts?full=1&limit=5000";
HttpResponseMessage resp = null;
for (var versuch = 0; versuch < 3; versuch++)
{
try
{
resp = await _http.GetAsync(url);
if (resp.IsSuccessStatusCode) break;
}
catch (Exception ex)
{
OnDebug?.Invoke($"Kontaktabruf gescheitert (Versuch {versuch + 1}): {ex.Message}");
}
await Task.Delay(250 * (versuch + 1));
}
// Mit einer halben Liste weiterzuarbeiten ist gefaehrlicher als
// abzubrechen: Fehlende Kontakte gaelten als geloescht.
if (resp == null || !resp.IsSuccessStatusCode)
{
throw new Exception(
"Die Kontakte aus Fonaria konnten nicht geladen werden. " +
"Synchronisation abgebrochen, um Dubletten und Loeschungen zu vermeiden.");
}
var kontakte = new List<UnifiedContact>();
foreach (var eintrag in JArray.Parse(await resp.Content.ReadAsStringAsync()))
kontakte.Add(AusFonaria(eintrag));
OnDebug?.Invoke($"{kontakte.Count} Kontakte aus Fonaria-Adressbuch {book.Name} geladen");
return kontakte;
}
public async Task<UnifiedContact> GetContactAsync(string contactId, RemoteAddressBook book)
{
try
{
var resp = await _http.GetAsync(
$"{_baseUrl}/addressbooks/{book.TagId}/contacts/{contactId}");
if (resp.StatusCode == HttpStatusCode.NotFound) return null;
if (!resp.IsSuccessStatusCode) return null;
return AusFonaria(JObject.Parse(await resp.Content.ReadAsStringAsync()));
}
catch { return null; }
}
// -------------------------------------------------------------------
// Schreiben
// -------------------------------------------------------------------
public async Task<UnifiedContact> CreateContactAsync(UnifiedContact contact, RemoteAddressBook book)
{
var body = NachFonaria(contact, null).ToString();
OnDebug?.Invoke($"POST /addressbooks/{book.TagId}/contacts");
var content = new StringContent(body, Encoding.UTF8, "application/json");
var resp = await _http.PostAsync($"{_baseUrl}/addressbooks/{book.TagId}/contacts", content);
var respBody = await resp.Content.ReadAsStringAsync();
if (!resp.IsSuccessStatusCode)
{
OnDebug?.Invoke($"Anlegen fehlgeschlagen: {(int)resp.StatusCode}\n{respBody}");
return null;
}
return AusFonaria(JObject.Parse(respBody));
}
public async Task<UnifiedContact> UpdateContactAsync(
string contactId, UnifiedContact contact, RemoteAddressBook book)
{
// Den bekannten Stand mitgeben, damit nichts verlorengeht, was
// innerhalb einer verwalteten Eigenschaft liegt, aber im
// Sync-Modell nicht vorkommt.
JToken roh;
if (!_rohdaten.TryGetValue(contactId, out roh))
{
var vorher = await GetContactAsync(contactId, book);
_rohdaten.TryGetValue(contactId, out roh);
}
var body = NachFonaria(contact, roh).ToString();
var content = new StringContent(body, Encoding.UTF8, "application/json");
var resp = await _http.PutAsync(
$"{_baseUrl}/addressbooks/{book.TagId}/contacts/{contactId}", content);
var respBody = await resp.Content.ReadAsStringAsync();
if (!resp.IsSuccessStatusCode)
{
OnDebug?.Invoke($"Aendern von {contactId} fehlgeschlagen: {(int)resp.StatusCode}\n{respBody}");
return null;
}
// Der Stand *nach* dem Schreiben ist massgeblich fuer die Baseline —
// sonst gilt der Kontakt beim naechsten Lauf erneut als geaendert.
return AusFonaria(JObject.Parse(respBody));
}
public async Task<bool> DeleteContactAsync(string contactId)
{
// Ohne Adressbuch im Pfad geht es bei Fonaria nicht. Die Engine
// ruft nur mit Kontakten des Profil-Buches, deshalb reicht das
// zuletzt benutzte.
if (_letztesBuch == null) return false;
var resp = await _http.DeleteAsync(
$"{_baseUrl}/addressbooks/{_letztesBuch}/contacts/{contactId}");
return resp.IsSuccessStatusCode;
}
private string _letztesBuch;
/// <summary>
/// Die Rohdaten der zuletzt gelesenen Kontakte, nach Kennung.
///
/// Sie werden beim Schreiben gebraucht: Zwei Dinge liegen innerhalb
/// einer Eigenschaft, die wir verwalten, gehoeren aber trotzdem nicht
/// uns — die Abteilung steckt im zweiten Teil von ORG, und neben der
/// geschaeftlichen Anschrift kann eine private stehen. Beides kennt das
/// Sync-Modell nicht. Wer es nicht zurueckschreibt, loescht es.
/// </summary>
private readonly Dictionary<string, JToken> _rohdaten = new Dictionary<string, JToken>();
// -------------------------------------------------------------------
// Umwandlung
// -------------------------------------------------------------------
private UnifiedContact AusFonaria(JToken item)
{
_letztesBuch = item["address_book_id"]?.ToString() ?? _letztesBuch;
var kennung = item["id"]?.ToString();
if (!string.IsNullOrEmpty(kennung)) _rohdaten[kennung] = item;
var kontakt = new UnifiedContact
{
StarfaceId = item["id"]?.ToString() ?? "",
FirstName = item["first_name"]?.ToString() ?? "",
LastName = item["last_name"]?.ToString() ?? "",
Company = item["organization"]?.ToString() ?? "",
JobTitle = item["title"]?.ToString() ?? "",
Salutation = item["prefix"]?.ToString() ?? "",
Notes = item["notes"]?.ToString() ?? "",
Birthday = item["birthday"]?.ToString() ?? ""
};
foreach (var mail in Eintraege(item["emails"]))
{
if (string.IsNullOrEmpty(kontakt.Email)) kontakt.Email = mail.Item1;
else if (string.IsNullOrEmpty(kontakt.EmailSecondary)) kontakt.EmailSecondary = mail.Item1;
}
// Die schlanke Liste fuehrt nur ein einzelnes Feld.
if (string.IsNullOrEmpty(kontakt.Email))
kontakt.Email = item["email"]?.ToString() ?? "";
foreach (var nummer in Nummern(item["numbers"]))
{
switch (nummer.Item2)
{
case "mobil": if (string.IsNullOrEmpty(kontakt.PhoneMobile)) kontakt.PhoneMobile = nummer.Item1; break;
case "home": if (string.IsNullOrEmpty(kontakt.PhoneHome)) kontakt.PhoneHome = nummer.Item1; break;
case "fax": if (string.IsNullOrEmpty(kontakt.Fax)) kontakt.Fax = nummer.Item1; break;
default: if (string.IsNullOrEmpty(kontakt.PhoneWork)) kontakt.PhoneWork = nummer.Item1; break;
}
}
var webadresse = Eintraege(item["urls"]).FirstOrDefault();
if (webadresse != null) kontakt.Website = webadresse.Item1;
// Von mehreren Anschriften traegt das Modell nur eine. Die
// geschaeftliche hat Vorrang — das ist die, um die es im
// Telefonbuch einer Anlage geht.
var anschriften = item["addresses"] as JArray;
if (anschriften != null && anschriften.Count > 0)
{
var gewaehlt = anschriften.FirstOrDefault(a => a["art"]?.ToString() == "work")
?? anschriften[0];
kontakt.Street = gewaehlt["strasse"]?.ToString() ?? "";
kontakt.City = gewaehlt["ort"]?.ToString() ?? "";
kontakt.PostalCode = gewaehlt["plz"]?.ToString() ?? "";
kontakt.State = gewaehlt["region"]?.ToString() ?? "";
kontakt.Country = gewaehlt["land"]?.ToString() ?? "";
}
return kontakt;
}
private static List<Tuple<string, string>> Eintraege(JToken liste)
{
var raus = new List<Tuple<string, string>>();
if (!(liste is JArray felder)) return raus;
foreach (var f in felder)
{
var wert = f["value"]?.ToString() ?? "";
if (!string.IsNullOrEmpty(wert))
raus.Add(Tuple.Create(wert, f["kind"]?.ToString() ?? ""));
}
return raus;
}
private static List<Tuple<string, string>> Nummern(JToken liste)
{
var raus = new List<Tuple<string, string>>();
if (!(liste is JArray felder)) return raus;
foreach (var f in felder)
{
// Die Kurzform der Liste nennt das Feld "number", die
// Vollansicht "value".
var wert = f["number"]?.ToString() ?? f["value"]?.ToString() ?? "";
if (!string.IsNullOrEmpty(wert))
raus.Add(Tuple.Create(wert, f["kind"]?.ToString() ?? "work"));
}
return raus;
}
private JObject NachFonaria(UnifiedContact contact, JToken bekannt)
{
var nummern = new JArray();
void Nummer(string wert, string art)
{
if (!string.IsNullOrWhiteSpace(wert))
nummern.Add(new JObject { ["value"] = wert, ["kind"] = art });
}
Nummer(contact.PhoneWork, "work");
Nummer(contact.PhoneMobile, "mobil");
Nummer(contact.PhoneHome, "home");
Nummer(contact.Fax, "fax");
var mails = new JArray();
if (!string.IsNullOrWhiteSpace(contact.Email))
mails.Add(new JObject { ["value"] = contact.Email, ["kind"] = "work" });
if (!string.IsNullOrWhiteSpace(contact.EmailSecondary))
mails.Add(new JObject { ["value"] = contact.EmailSecondary, ["kind"] = "home" });
var webadressen = new JArray();
if (!string.IsNullOrWhiteSpace(contact.Website))
webadressen.Add(new JObject { ["value"] = contact.Website, ["kind"] = "work" });
// Das Sync-Modell traegt genau eine Anschrift, die geschaeftliche.
// Alle uebrigen der Anlage werden unveraendert wieder mitgeschickt.
var anschriften = new JArray();
if (!string.IsNullOrWhiteSpace(contact.Street) ||
!string.IsNullOrWhiteSpace(contact.City) ||
!string.IsNullOrWhiteSpace(contact.PostalCode))
{
anschriften.Add(new JObject
{
["art"] = "work",
["strasse"] = contact.Street ?? "",
["ort"] = contact.City ?? "",
["plz"] = contact.PostalCode ?? "",
["region"] = contact.State ?? "",
["land"] = contact.Country ?? ""
});
}
if (bekannt?["addresses"] is JArray vorhandene)
{
foreach (var a in vorhandene)
if (a["art"]?.ToString() != "work")
anschriften.Add(a.DeepClone());
}
// Dasselbe fuer die Abteilung: Sie steckt im zweiten Teil von ORG,
// das Sync-Modell kennt nur die Firma.
var abteilung = bekannt?["department"]?.ToString() ?? "";
return new JObject
{
// Der Kern: Nur diese Eigenschaften fasst Fonaria an.
["verwaltet"] = new JArray(VerwalteteFelder),
["display_name"] = contact.DisplayName,
["prefix"] = contact.Salutation ?? "",
["first_name"] = contact.FirstName ?? "",
["last_name"] = contact.LastName ?? "",
["organization"] = contact.Company ?? "",
["department"] = abteilung,
["title"] = contact.JobTitle ?? "",
["numbers"] = nummern,
["emails"] = mails,
["urls"] = webadressen,
["addresses"] = anschriften,
["birthday"] = contact.Birthday ?? "",
["notes"] = string.IsNullOrEmpty(contact.Notes) ? null : contact.Notes
};
}
public void Dispose()
{
_http?.Dispose();
}
}
}
@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using StarfaceOutlookSync.Models;
namespace StarfaceOutlookSync.Services
{
/// <summary>
/// Die Gegenseite eines Abgleichs — eine Telefonanlage mit Adressbuechern.
///
/// Die SyncEngine kennt nur dieses Interface. Was dahinter steckt, eine
/// Starface oder eine Fonaria, entscheidet allein das Profil. Ohne diese
/// Trennung muesste die Engine fuer jede weitere Anlage angefasst werden —
/// und in ihr steckt die ganze Erfahrung mit getrennten Baselines,
/// Wiederzuordnung und Konfliktaufloesung, die man nicht zweimal haben will.
/// </summary>
public interface IContactBackend : IDisposable
{
/// <summary>Ausfuehrliche Meldungen fuer das Protokoll.</summary>
event Action<string> OnDebug;
/// <summary>Welche Anlage ist das? Nur fuer Meldungen an den Anwender.</summary>
string SystemName { get; }
/// <summary>
/// Welche vCard-Eigenschaften diese Anlage ueberhaupt fuehrt.
///
/// Entscheidend beim Schreiben: Fonaria haelt den Kontakt im vollen
/// vCard-Umfang. Ein Abgleich mit einer Starface darf deshalb nicht
/// die ganze Karte ersetzen — die Starface kennt weder Kategorien noch
/// Jahrestag noch Bild und wuerde sie beim ersten Durchlauf
/// mitloeschen, nur weil sie sie nicht mitschickt. Diese Liste sagt der
/// Gegenseite, wofuer wir uns zustaendig fuehlen.
/// </summary>
IReadOnlyList<string> VerwalteteFelder { get; }
Task<bool> LoginAsync();
Task LogoutAsync();
Task<List<RemoteAddressBook>> GetAddressBooksAsync();
Task<List<UnifiedContact>> GetContactsAsync(RemoteAddressBook book);
Task<UnifiedContact> GetContactAsync(string contactId, RemoteAddressBook book);
Task<UnifiedContact> CreateContactAsync(UnifiedContact contact, RemoteAddressBook book);
Task<UnifiedContact> UpdateContactAsync(string contactId, UnifiedContact contact, RemoteAddressBook book);
Task<bool> DeleteContactAsync(string contactId);
}
/// <summary>Waehlt die Umsetzung, die zum Profil passt.</summary>
public static class ContactBackendFactory
{
public static IContactBackend Create(SystemConnection connection)
{
switch (connection.System)
{
case PhoneSystem.Fonaria:
return new FonariaApiClient(connection);
default:
return new StarfaceApiClient(connection);
}
}
}
}
+124
View File
@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace StarfaceOutlookSync.Services
{
/// <summary>
/// Einfaches, threadsicheres Datei-Protokoll. Haelt fest, was bei Syncs
/// passiert (Ergebnisse, Konflikte, Fehler) - dauerhaft nachlesbar, auch
/// nachdem eine Tray-Meldung verschwunden ist.
/// </summary>
public static class Logger
{
private static readonly object _lock = new object();
private const long MaxBytes = 2 * 1024 * 1024; // 2 MB, dann Rotation
public static string LogFilePath { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"StarfaceOutlookSync", "sync.log");
public static void Log(string message)
{
try
{
lock (_lock)
{
Directory.CreateDirectory(Path.GetDirectoryName(LogFilePath));
Rotate();
var line = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}{Environment.NewLine}";
File.AppendAllText(LogFilePath, line, Encoding.UTF8);
}
}
catch { }
}
private static void Rotate()
{
try
{
var fi = new FileInfo(LogFilePath);
if (fi.Exists && fi.Length > MaxBytes)
{
var bak = LogFilePath + ".1";
if (File.Exists(bak)) File.Delete(bak);
File.Move(LogFilePath, bak);
}
}
catch { }
}
public static string ReadAll()
{
try
{
lock (_lock)
{
if (!File.Exists(LogFilePath)) return "";
using (var fs = new FileStream(LogFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs, Encoding.UTF8))
return sr.ReadToEnd();
}
}
catch { return ""; }
}
/// <summary>
/// Entfernt Protokoll-Eintraege, die aelter als <paramref name="days"/>
/// Tage sind. days &lt;= 0 -> nichts tun (alle Eintraege bleiben).
/// </summary>
public static void PruneOlderThan(int days)
{
if (days <= 0) return;
try
{
lock (_lock)
{
if (!File.Exists(LogFilePath)) return;
var cutoff = DateTime.Now.AddDays(-days);
var lines = File.ReadAllLines(LogFilePath, Encoding.UTF8);
var kept = new List<string>(lines.Length);
foreach (var line in lines)
{
// Eintraege ohne erkennbaren Zeitstempel (z.B. Fortsetzungs-
// zeilen) bleiben erhalten; nur datierte Alt-Eintraege fliegen raus.
if (TryParseLineDate(line, out var dt) && dt < cutoff)
continue;
kept.Add(line);
}
if (kept.Count != lines.Length)
File.WriteAllLines(LogFilePath, kept, Encoding.UTF8);
}
}
catch { }
}
private static bool TryParseLineDate(string line, out DateTime dt)
{
dt = default;
// Format: "[yyyy-MM-dd HH:mm:ss] ..."
if (line != null && line.Length >= 21 && line[0] == '[' && line[20] == ']')
{
return DateTime.TryParseExact(line.Substring(1, 19), "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
}
return false;
}
public static void Clear()
{
try
{
lock (_lock)
{
if (File.Exists(LogFilePath)) File.Delete(LogFilePath);
var bak = LogFilePath + ".1";
if (File.Exists(bak)) File.Delete(bak);
}
}
catch { }
}
}
}
@@ -12,14 +12,25 @@ using StarfaceOutlookSync.Models;
namespace StarfaceOutlookSync.Services
{
public class StarfaceApiClient : IDisposable
public class StarfaceApiClient : IContactBackend
{
public string SystemName => "Starface";
/// <summary>
/// Was eine Starface an Feldern kennt — mehr gibt ihr Datenmodell nicht
/// her. Beim Schreiben nach Fonaria zaehlt genau diese Liste: Alles
/// andere in der dortigen vCard bleibt unangetastet, statt hier
/// mangels Kenntnis geloescht zu werden.
/// </summary>
public IReadOnlyList<string> VerwalteteFelder => UnifiedContact.VcardFelder;
private readonly HttpClient _http;
private readonly StarfaceConnection _connection;
private readonly SystemConnection _connection;
private readonly string _baseUrl;
private string _token;
public StarfaceApiClient(StarfaceConnection connection)
public StarfaceApiClient(SystemConnection connection)
{
_connection = connection;
@@ -112,9 +123,9 @@ namespace StarfaceOutlookSync.Services
catch { return null; }
}
public async Task<List<StarfaceAddressBook>> GetAddressBooksAsync()
public async Task<List<RemoteAddressBook>> GetAddressBooksAsync()
{
var books = new List<StarfaceAddressBook>();
var books = new List<RemoteAddressBook>();
// Alle Tags laden - die Starface nutzt Tags als Adressbuch-Zuordnung
var allTags = new JArray();
@@ -134,7 +145,7 @@ namespace StarfaceOutlookSync.Services
// Zentrales Adressbuch (folder/all)
var allTag = allTags.FirstOrDefault(t => t["name"]?.ToString() == "folder/all"
|| t["alias"]?.ToString()?.Contains("folder.all") == true);
books.Add(new StarfaceAddressBook
books.Add(new RemoteAddressBook
{
Type = "central",
TagId = allTag?["id"]?.ToString() ?? "",
@@ -149,7 +160,7 @@ namespace StarfaceOutlookSync.Services
(t["name"]?.ToString() == "folder/private" || t["alias"]?.ToString()?.Contains("folder.private") == true)
&& t["owner"]?.ToString() == userId);
books.Add(new StarfaceAddressBook
books.Add(new RemoteAddressBook
{
Type = "user",
UserId = userId,
@@ -165,7 +176,7 @@ namespace StarfaceOutlookSync.Services
// folder/all und folder/private bereits oben erfasst
if (tagName == "folder/all" || tagName == "folder/private") continue;
books.Add(new StarfaceAddressBook
books.Add(new RemoteAddressBook
{
Type = "tag",
TagId = tag["id"]?.ToString() ?? "",
@@ -178,7 +189,7 @@ namespace StarfaceOutlookSync.Services
public event Action<string> OnDebug;
public async Task<List<UnifiedContact>> GetContactsAsync(StarfaceAddressBook book)
public async Task<List<UnifiedContact>> GetContactsAsync(RemoteAddressBook book)
{
var contacts = new List<UnifiedContact>();
int page = 0;
@@ -314,7 +325,7 @@ namespace StarfaceOutlookSync.Services
$"Synchronisation abgebrochen, um Dubletten zu vermeiden.");
}
public async Task<UnifiedContact> CreateContactAsync(UnifiedContact contact, StarfaceAddressBook book)
public async Task<UnifiedContact> CreateContactAsync(UnifiedContact contact, RemoteAddressBook book)
{
var sfContact = MapToStarface(contact);
@@ -354,7 +365,7 @@ namespace StarfaceOutlookSync.Services
/// Hash-Baseline benoetigt, damit der Kontakt beim naechsten Sync nicht
/// erneut faelschlich als geaendert gilt.
/// </summary>
public async Task<UnifiedContact> UpdateContactAsync(string contactId, UnifiedContact contact, StarfaceAddressBook book)
public async Task<UnifiedContact> UpdateContactAsync(string contactId, UnifiedContact contact, RemoteAddressBook book)
{
var sfContact = MapToStarface(contact);
sfContact["id"] = contactId;
@@ -394,11 +405,16 @@ namespace StarfaceOutlookSync.Services
}
catch { }
return await GetContactAsync(contactId) ?? contact;
return await GetContactAsync(contactId, book) ?? contact;
}
/// <summary>Laedt einen einzelnen Kontakt mit allen Feldern.</summary>
public async Task<UnifiedContact> GetContactAsync(string contactId)
/// <summary>Laedt einen einzelnen Kontakt mit allen Feldern.
///
/// Das Adressbuch spielt hier keine Rolle: Die Starface findet einen
/// Kontakt ueber alle Buecher hinweg. Genau darauf beruht die Regel,
/// dass ein nicht in der Liste gefundener Kontakt nur verschoben und
/// nicht geloescht ist.</summary>
public async Task<UnifiedContact> GetContactAsync(string contactId, RemoteAddressBook book = null)
{
try
{
@@ -0,0 +1,163 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using StarfaceOutlookSync.Models;
namespace StarfaceOutlookSync.Services
{
/// <summary>
/// Gemeinsame Orchestrierung fuer JEDEN Sync-Lauf - egal ob automatisch
/// (Tray/Timer) oder manuell (Fortschrittsfenster). Sorgt einheitlich fuer:
/// - lokalen Re-Entrancy-Schutz (prozessweit, statisch),
/// - clientuebergreifende Lock-Datei,
/// - Anzeige/Logging von Konflikt-Notizen anderer Arbeitsplaetze,
/// - Protokollierung (Start, Ergebnis, Aenderungen, Konflikte, Fehler),
/// - Verteilen eigener Konflikt-Notizen.
/// Die eigentliche UI (Tray-Meldung vs. Fenster) bleibt beim Aufrufer.
/// </summary>
public class SyncCoordinator
{
// Prozessweit: nie zwei Syncs gleichzeitig - auch nicht manuell + automatisch.
private static int _running = 0;
private readonly ProfileManager _profileManager = new ProfileManager();
private readonly ConflictNotifier _notifier = new ConflictNotifier();
public class SyncOutcome
{
public bool Skipped;
public string SkipReason = "";
public SyncResult Result;
public Exception Error;
public List<ConflictNotice> RemoteNotices = new List<ConflictNotice>();
}
/// <summary>
/// Fuehrt einen Sync koordiniert aus. runEngine kapselt den eigentlichen
/// Engine-Aufruf (inkl. ggf. Task.Run/Progress-Anbindung des Aufrufers),
/// damit das Threading-Verhalten pro Pfad erhalten bleibt. status erhaelt
/// Fortschrittstexte (Warten auf Sperre, Synchronisiere ...).
/// </summary>
public async Task<SyncOutcome> RunAsync(SyncProfile profile,
Func<Task<SyncResult>> runEngine, Action<string> status)
{
var outcome = new SyncOutcome();
if (Interlocked.CompareExchange(ref _running, 1, 0) != 0)
{
outcome.Skipped = true;
outcome.SkipReason = "Sync laeuft bereits, bitte warten...";
return outcome;
}
SyncLock crossLock = null;
var settings = UserSettings.Load();
Logger.PruneOlderThan(settings.LogRetentionDays);
var sharedDir = settings.SharedDirectory;
try
{
crossLock = await AcquireCrossClientLock(sharedDir, status);
if (crossLock == null)
{
outcome.Skipped = true;
outcome.SkipReason = "Anderer Arbeitsplatz synchronisiert gerade - uebersprungen.";
Logger.Log($"Sync '{profile.Name}' uebersprungen: anderer Arbeitsplatz synct gerade.");
return outcome;
}
// Konflikt-Hinweise anderer Arbeitsplaetze ermitteln, BEVOR der Sync
// den eigenen Stand auf den Gewinner-Wert angleicht.
try
{
outcome.RemoteNotices = _notifier.GetPending(sharedDir, MyContactsByStarfaceId());
foreach (var n in outcome.RemoteNotices)
Logger.Log($" KONFLIKT (anderer Arbeitsplatz): {n}");
}
catch { }
Logger.Log($"Sync gestartet: '{profile.Name}' (Richtung: {profile.SyncDirection})");
status?.Invoke($"Synchronisiere '{profile.Name}'...");
SyncResult result;
try
{
result = await runEngine();
}
catch (Exception ex)
{
outcome.Error = ex;
Logger.Log($"Sync FEHLER '{profile.Name}': {ex.Message}");
return outcome;
}
outcome.Result = result;
var msg = $"{profile.Name}: {result.Created} erstellt, {result.Updated} aktualisiert"
+ (result.Errors > 0 ? $", {result.Errors} Fehler" : "")
+ (result.Conflicts.Count > 0 ? $", {result.Conflicts.Count} Konflikt(e)" : "");
Logger.Log($"Sync fertig: {msg}");
foreach (var ch in result.Changes) Logger.Log($" {ch}");
foreach (var em in result.ErrorMessages) Logger.Log($" Fehler: {em}");
foreach (var c in result.Conflicts) Logger.Log($" KONFLIKT: {c}");
// Andere Arbeitsplaetze ueber eigene Konflikte informieren.
if (result.Conflicts.Count > 0)
_notifier.Write(sharedDir, result.Conflicts);
return outcome;
}
finally
{
crossLock?.Dispose();
Interlocked.Exchange(ref _running, 0);
}
}
private async Task<SyncLock> AcquireCrossClientLock(string dir, Action<string> status)
{
if (string.IsNullOrWhiteSpace(dir))
return SyncLock.NoOp();
try
{
// Legt das Verzeichnis bei Bedarf an (idempotent). Funktioniert mit
// UNC-Pfaden (\\server\freigabe\...) - kein Netzlaufwerk noetig.
Directory.CreateDirectory(dir);
}
catch
{
status?.Invoke("Gemeinsames Verzeichnis nicht erreichbar - synce ohne Sperre.");
return SyncLock.NoOp();
}
var deadline = DateTime.UtcNow.AddMinutes(2);
int attempt = 0;
while (true)
{
var l = SyncLock.TryAcquire(dir, out var heldBy);
if (l != null) return l;
if (DateTime.UtcNow >= deadline) return null;
attempt++;
status?.Invoke($"Warte auf anderen Arbeitsplatz ({heldBy ?? "unbekannt"})... ({attempt})");
await Task.Delay(3000);
}
}
private Dictionary<string, UnifiedContact> MyContactsByStarfaceId()
{
var map = new Dictionary<string, UnifiedContact>(StringComparer.OrdinalIgnoreCase);
try
{
foreach (var p in _profileManager.GetProfiles())
foreach (var m in _profileManager.GetMappings(p.Id))
if (!string.IsNullOrEmpty(m.StarfaceId) && !map.ContainsKey(m.StarfaceId))
map[m.StarfaceId] = m.LastOutlook;
}
catch { }
return map;
}
}
}
+32 -25
View File
@@ -15,6 +15,13 @@ namespace StarfaceOutlookSync.Services
private void Log(string message) => OnProgress?.Invoke(message);
/// <summary>Protokolliert eine tatsaechliche Aenderung (fuer Live-Log UND SyncResult.Changes).</summary>
private void Action(SyncResult result, string message)
{
Log(" " + message);
result?.Changes.Add(message);
}
/// <summary>
/// Setzt die Baseline eines Mappings auf den uebergebenen Stand beider
/// Seiten (Snapshot + Hash). Der Snapshot wird fuer das Feld-Merge bei
@@ -103,7 +110,7 @@ namespace StarfaceOutlookSync.Services
try
{
Log("Verbinde mit Starface...");
using (var starface = new StarfaceApiClient(profile.StarfaceConnection))
using (var starface = ContactBackendFactory.Create(profile.Connection))
{
starface.OnDebug += (msg) => Log(msg);
var loginOk = await starface.LoginAsync();
@@ -120,7 +127,7 @@ namespace StarfaceOutlookSync.Services
Log($"{outlookContacts.Count} Outlook-Kontakte geladen");
Log("Lade Starface-Kontakte...");
var starfaceContacts = await starface.GetContactsAsync(profile.StarfaceAddressBook);
var starfaceContacts = await starface.GetContactsAsync(profile.AddressBook);
Log($"{starfaceContacts.Count} Starface-Kontakte geladen");
// Bestehende Mappings laden
@@ -184,7 +191,7 @@ namespace StarfaceOutlookSync.Services
if (await starface.DeleteContactAsync(mapping.StarfaceId))
{
result.Updated++;
Log($" Geloescht (OL->SF): {sc.DisplayName}");
Action(result, $"Geloescht (OL->SF): {sc.DisplayName}");
}
continue;
}
@@ -202,7 +209,7 @@ namespace StarfaceOutlookSync.Services
if (await starface.DeleteContactAsync(mapping.StarfaceId))
{
result.Updated++;
Log($" Geloescht (OL->SF): {sc.DisplayName}");
Action(result, $"Geloescht (OL->SF): {sc.DisplayName}");
}
continue;
}
@@ -229,7 +236,7 @@ namespace StarfaceOutlookSync.Services
// (sonst Dublette).
// (b) per ID 404 -> in Starface WIRKLICH geloescht.
bool stillExists = !string.IsNullOrEmpty(mapping.StarfaceId)
&& await starface.GetContactAsync(mapping.StarfaceId) != null;
&& await starface.GetContactAsync(mapping.StarfaceId, profile.AddressBook) != null;
if (stillExists)
{
@@ -245,7 +252,7 @@ namespace StarfaceOutlookSync.Services
if (_outlookService.DeleteContact(oc.OutlookEntryId))
{
result.Updated++;
Log($" Geloescht (SF->OL): {oc.DisplayName}");
Action(result, $"Geloescht (SF->OL): {oc.DisplayName}");
}
continue;
}
@@ -263,7 +270,7 @@ namespace StarfaceOutlookSync.Services
if (_outlookService.DeleteContact(oc.OutlookEntryId))
{
result.Updated++;
Log($" Geloescht (SF->OL): {oc.DisplayName}");
Action(result, $"Geloescht (SF->OL): {oc.DisplayName}");
}
continue;
}
@@ -317,12 +324,12 @@ namespace StarfaceOutlookSync.Services
if (olChanged && !sfChanged && (profile.SyncDirection == SyncDirection.Both || profile.SyncDirection == SyncDirection.OutlookToStarface))
{
// Outlook hat sich geaendert -> Starface updaten
var updated = await starface.UpdateContactAsync(mapping.StarfaceId, oc, profile.StarfaceAddressBook);
var updated = await starface.UpdateContactAsync(mapping.StarfaceId, oc, profile.AddressBook);
if (updated != null)
{
SetBaseline(mapping, oc, updated);
result.Updated++;
Log($" Aktualisiert (OL->SF): {oc.DisplayName}");
Action(result, $"Aktualisiert (OL->SF): {oc.DisplayName}");
}
}
else if (sfChanged && !olChanged && (profile.SyncDirection == SyncDirection.Both || profile.SyncDirection == SyncDirection.StarfaceToOutlook))
@@ -333,7 +340,7 @@ namespace StarfaceOutlookSync.Services
{
SetBaseline(mapping, updated, sc);
result.Updated++;
Log($" Aktualisiert (SF->OL): {sc.DisplayName}");
Action(result, $"Aktualisiert (SF->OL): {sc.DisplayName}");
}
}
else if (olChanged && sfChanged)
@@ -348,7 +355,7 @@ namespace StarfaceOutlookSync.Services
var (merged, conflicts) = ContactMerger.Merge(
mapping.LastOutlook, mapping.LastStarface, oc, sc, outlookWins: true);
var updatedSf = await starface.UpdateContactAsync(mapping.StarfaceId, merged, profile.StarfaceAddressBook);
var updatedSf = await starface.UpdateContactAsync(mapping.StarfaceId, merged, profile.AddressBook);
var updatedOl = _outlookService.UpdateContact(mapping.OutlookEntryId, merged);
if (updatedSf != null || updatedOl != null)
@@ -366,21 +373,21 @@ namespace StarfaceOutlookSync.Services
mapping.LastSyncHash = "";
result.Updated++;
foreach (var cf in conflicts) result.Conflicts.Add(cf);
Log(conflicts.Count > 0
? $" Beidseitig geaendert, zusammengefuehrt ({conflicts.Count} Feld-Konflikt(e), Outlook gewinnt): {oc.DisplayName}"
: $" Beidseitig geaendert, zusammengefuehrt: {oc.DisplayName}");
Action(result, conflicts.Count > 0
? $"Beidseitig geaendert, zusammengefuehrt ({conflicts.Count} Feld-Konflikt(e), Outlook gewinnt): {oc.DisplayName}"
: $"Beidseitig geaendert, zusammengefuehrt: {oc.DisplayName}");
}
}
else if (profile.SyncDirection != SyncDirection.StarfaceToOutlook)
{
// Fallback ohne Snapshot bzw. OutlookToStarface:
// Outlook gewinnt komplett.
var updated = await starface.UpdateContactAsync(mapping.StarfaceId, oc, profile.StarfaceAddressBook);
var updated = await starface.UpdateContactAsync(mapping.StarfaceId, oc, profile.AddressBook);
if (updated != null)
{
SetBaseline(mapping, oc, updated);
result.Updated++;
Log($" Konflikt (OL gewinnt): {oc.DisplayName}");
Action(result, $"Konflikt (OL gewinnt): {oc.DisplayName}");
}
}
else
@@ -390,7 +397,7 @@ namespace StarfaceOutlookSync.Services
{
SetBaseline(mapping, updated, sc);
result.Updated++;
Log($" Konflikt (SF gewinnt): {sc.DisplayName}");
Action(result, $"Konflikt (SF gewinnt): {sc.DisplayName}");
}
}
}
@@ -425,7 +432,7 @@ namespace StarfaceOutlookSync.Services
if (match != null)
{
// Existiert schon -> verknuepfen und updaten
var updated = await starface.UpdateContactAsync(match.StarfaceId, oc, profile.StarfaceAddressBook);
var updated = await starface.UpdateContactAsync(match.StarfaceId, oc, profile.AddressBook);
if (updated != null)
{
newMappings.Add(new SyncMapping
@@ -441,14 +448,14 @@ namespace StarfaceOutlookSync.Services
processedStarfaceIds.Add(match.StarfaceId);
unmappedStarface.Remove(match);
result.Updated++;
Log($" Verknuepft (OL->SF): {oc.DisplayName}");
Action(result, $"Verknuepft (OL->SF): {oc.DisplayName}");
}
}
else
{
// Neu -> in Starface erstellen
Log($" Erstelle in Starface: {oc.DisplayName}");
var created = await starface.CreateContactAsync(oc, profile.StarfaceAddressBook);
var created = await starface.CreateContactAsync(oc, profile.AddressBook);
if (created != null && !string.IsNullOrEmpty(created.StarfaceId))
{
newMappings.Add(new SyncMapping
@@ -462,7 +469,7 @@ namespace StarfaceOutlookSync.Services
LastStarfaceHash = created.GetHash()
});
result.Created++;
Log($" Erstellt (OL->SF): {oc.DisplayName}");
Action(result, $"Erstellt (OL->SF): {oc.DisplayName}");
}
else
{
@@ -521,7 +528,7 @@ namespace StarfaceOutlookSync.Services
processedOutlookIds.Add(match.OutlookEntryId);
unmappedOutlook.Remove(match);
result.Updated++;
Log($" Verknuepft (SF->OL): {sc.DisplayName}");
Action(result, $"Verknuepft (SF->OL): {sc.DisplayName}");
}
}
else
@@ -541,7 +548,7 @@ namespace StarfaceOutlookSync.Services
LastOutlookHash = created.GetHash()
});
result.Created++;
Log($" Erstellt (SF->OL): {sc.DisplayName}");
Action(result, $"Erstellt (SF->OL): {sc.DisplayName}");
}
}
}
@@ -581,7 +588,7 @@ namespace StarfaceOutlookSync.Services
if (await starface.DeleteContactAsync(sc.StarfaceId))
{
result.Updated++;
Log($" Geloescht (nur in Starface): {sc.DisplayName}");
Action(result, $"Geloescht (nur in Starface): {sc.DisplayName}");
}
}
catch (Exception ex)
@@ -612,7 +619,7 @@ namespace StarfaceOutlookSync.Services
if (_outlookService.DeleteContact(oc.OutlookEntryId))
{
result.Updated++;
Log($" Geloescht (nur in Outlook): {oc.DisplayName}");
Action(result, $"Geloescht (nur in Outlook): {oc.DisplayName}");
}
}
catch (Exception ex)
@@ -7,9 +7,9 @@
<AssemblyTitle>Starface Outlook Sync</AssemblyTitle>
<Company>HackerSoft - Hacker-Net Telekommunikation</Company>
<Product>Starface Outlook Sync</Product>
<Version>0.0.0.27</Version>
<AssemblyVersion>0.0.0.27</AssemblyVersion>
<FileVersion>0.0.0.27</FileVersion>
<Version>0.0.0.30</Version>
<AssemblyVersion>0.0.0.30</AssemblyVersion>
<FileVersion>0.0.0.30</FileVersion>
<Description>Synchronisiert Outlook-Kontakte mit Starface Telefonanlage</Description>
<Copyright>Stefan Hacker - HackerSoft</Copyright>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
+1 -1
View File
@@ -27,7 +27,7 @@ namespace StarfaceOutlookSync.UI
var lblVersion = new Label
{
Text = "Version 0.0.0.27",
Text = "Version 0.0.0.30",
Left = 0, Top = 56, Width = 340, Height = 20,
TextAlign = ContentAlignment.MiddleCenter,
ForeColor = Color.Gray
@@ -0,0 +1,92 @@
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using StarfaceOutlookSync.Models;
using StarfaceOutlookSync.Services;
namespace StarfaceOutlookSync.UI
{
/// <summary>Zeigt das Sync-Protokoll an (read-only) mit Aktualisieren/Leeren.</summary>
public class LogViewerForm : Form
{
private TextBox _txt;
private Button _btnClose;
private Panel _panel;
public LogViewerForm()
{
Text = "Protokoll";
Size = new Size(720, 500);
StartPosition = FormStartPosition.CenterParent;
Font = new Font("Segoe UI", 9);
_txt = new TextBox
{
Multiline = true,
ReadOnly = true,
ScrollBars = ScrollBars.Both,
WordWrap = false,
Dock = DockStyle.Fill,
BackColor = Color.White,
Font = new Font("Consolas", 9)
};
_panel = new Panel { Dock = DockStyle.Bottom, Height = 44 };
var btnRefresh = new Button { Text = "Aktualisieren", Left = 10, Top = 8, Width = 100, Height = 28 };
btnRefresh.Click += (s, e) => LoadLog();
var btnClear = new Button { Text = "Leeren", Left = 118, Top = 8, Width = 80, Height = 28 };
btnClear.Click += (s, e) =>
{
if (MessageBox.Show("Protokoll wirklich leeren?", "Protokoll",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Logger.Clear();
LoadLog();
}
};
var btnFolder = new Button { Text = "Ordner oeffnen", Left = 206, Top = 8, Width = 120, Height = 28 };
btnFolder.Click += (s, e) => OpenFolder();
_btnClose = new Button
{
Text = "Schliessen", Top = 8, Width = 100, Height = 28,
Anchor = AnchorStyles.Top | AnchorStyles.Right
};
_btnClose.Click += (s, e) => Close();
_panel.Controls.AddRange(new Control[] { btnRefresh, btnClear, btnFolder, _btnClose });
Controls.Add(_txt);
Controls.Add(_panel);
Load += (s, e) =>
{
_btnClose.Left = _panel.ClientSize.Width - _btnClose.Width - 10;
LoadLog();
};
}
private void LoadLog()
{
Logger.PruneOlderThan(UserSettings.Load().LogRetentionDays);
_txt.Text = Logger.ReadAll();
_txt.SelectionStart = _txt.TextLength;
_txt.ScrollToCaret();
}
private void OpenFolder()
{
try
{
var dir = Path.GetDirectoryName(Logger.LogFilePath);
Process.Start(new ProcessStartInfo { FileName = dir, UseShellExecute = true });
}
catch { }
}
}
}
+68 -73
View File
@@ -2,7 +2,6 @@ using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
@@ -16,16 +15,18 @@ namespace StarfaceOutlookSync.UI
{
private readonly ProfileManager _profileManager = new ProfileManager();
private readonly SyncEngine _syncEngine = new SyncEngine();
private readonly SyncCoordinator _coordinator = new SyncCoordinator();
private NotifyIcon _trayIcon;
private ContextMenuStrip _trayMenu;
private ListView _profileList;
private Button _btnNew, _btnEdit, _btnDelete, _btnSync, _btnReset, _btnSettings, _btnInfo;
private Button _btnNew, _btnEdit, _btnDelete, _btnSync, _btnReset, _btnSettings, _btnLog, _btnInfo;
private StatusStrip _statusBar;
private ToolStripStatusLabel _statusLabel;
private Timer _autoSyncTimer;
// 0 = frei, 1 = Sync laeuft. Per Interlocked atomar geschaltet, damit
// ein manueller Sync und der Auto-Sync-Timer nicht gleichzeitig starten.
private int _syncRunning = 0;
// Aktive Benachrichtigungs-Einstellung (pro Sync-Lauf gesetzt).
private bool _notifyGeneral = true;
private bool _notifyWarn = true;
public MainForm()
{
@@ -38,6 +39,9 @@ namespace StarfaceOutlookSync.UI
var settings = UserSettings.Load();
settings.ApplyOutlookSecuritySetting();
// Protokoll bei Bedarf auf das eingestellte Alter eindampfen.
Logger.PruneOlderThan(settings.LogRetentionDays);
if (settings.StartMinimized)
{
WindowState = FormWindowState.Minimized;
@@ -128,10 +132,13 @@ namespace StarfaceOutlookSync.UI
_btnSettings = new Button { Text = "Einstellungen", Width = 95, Height = 30 };
_btnSettings.Click += (s, e) => ShowSettings();
_btnLog = new Button { Text = "Protokoll", Width = 80, Height = 30 };
_btnLog.Click += (s, e) => ShowLog();
_btnInfo = new Button { Text = "Info", Width = 50, Height = 30 };
_btnInfo.Click += (s, e) => ShowAbout();
buttonPanel.Controls.AddRange(new Control[] { _btnNew, _btnEdit, _btnDelete, _btnSync, _btnReset, _btnSettings, _btnInfo });
buttonPanel.Controls.AddRange(new Control[] { _btnNew, _btnEdit, _btnDelete, _btnSync, _btnReset, _btnSettings, _btnLog, _btnInfo });
// Statusbar
_statusBar = new StatusStrip();
@@ -234,7 +241,7 @@ namespace StarfaceOutlookSync.UI
var item = new ListViewItem(new[]
{
p.Name,
$"{p.StarfaceConnection.Host} / {p.StarfaceAddressBook.Name}",
$"{p.Connection.Host} / {p.AddressBook.Name}",
p.OutlookFolderName,
dirText,
lastSync
@@ -340,103 +347,83 @@ namespace StarfaceOutlookSync.UI
private async Task RunSync(SyncProfile profile)
{
// Atomar pruefen-und-setzen: verhindert, dass manueller Sync und
// Auto-Sync-Timer gleichzeitig denselben/einen Sync starten.
if (Interlocked.CompareExchange(ref _syncRunning, 1, 0) != 0)
{
SetStatus("Sync laeuft bereits, bitte warten...");
return;
}
var settings = UserSettings.Load();
_notifyGeneral = settings.NotificationsEnabled;
_notifyWarn = settings.NotifyWarningsErrors;
SyncLock crossLock = null;
try
{
// Clientuebergreifende Sperre (falls gemeinsames Verzeichnis konfiguriert).
crossLock = await AcquireCrossClientLock();
if (crossLock == null)
// Lokaler Guard, Lock-Datei, Konflikt-Notizen und Protokoll laufen
// zentral im Coordinator (gemeinsam mit dem manuellen Sync-Pfad).
var outcome = await _coordinator.RunAsync(
profile,
runEngine: () => _syncEngine.SyncProfileAsync(profile),
status: SetStatus);
if (outcome.Skipped)
{
SetStatus("Anderer Arbeitsplatz synchronisiert gerade - uebersprungen.");
SetStatus(outcome.SkipReason);
return;
}
SetStatus($"Synchronisiere '{profile.Name}'...");
_trayIcon.ShowBalloonTip(2000, "Starface Sync",
$"Synchronisiere '{profile.Name}'...", ToolTipIcon.Info);
// Konflikt-Hinweise anderer Arbeitsplaetze als Tray-Meldung (falls aktiv).
ShowRemoteNoticesTray(outcome.RemoteNotices);
var result = await _syncEngine.SyncProfileAsync(profile);
if (outcome.Error != null)
{
Balloon(3000, "Starface Sync Fehler", outcome.Error.Message, ToolTipIcon.Error, warn: true);
SetStatus($"Fehler: {outcome.Error.Message}");
return;
}
var result = outcome.Result;
var msg = $"{profile.Name}: {result.Created} erstellt, {result.Updated} aktualisiert";
if (result.Errors > 0) msg += $", {result.Errors} Fehler";
if (result.Conflicts.Count > 0) msg += $", {result.Conflicts.Count} Konflikt(e)";
_trayIcon.ShowBalloonTip(3000, "Starface Sync", msg,
result.Errors > 0 ? ToolTipIcon.Warning : ToolTipIcon.Info);
// Zusammenfassung als Warnung werten, wenn Fehler/Konflikte auftraten.
bool noteworthy = result.Errors > 0 || result.Conflicts.Count > 0;
Balloon(3000, "Starface Sync", msg,
result.Errors > 0 ? ToolTipIcon.Warning : ToolTipIcon.Info, warn: noteworthy);
// Echte Feld-Konflikte gesondert melden, damit der Benutzer weiss,
// dass ein Wert ueberschrieben wurde.
// Echte Feld-Konflikte gesondert melden (eigener Wert wurde ueberschrieben).
if (result.Conflicts.Count > 0)
{
var detail = string.Join("\n", result.Conflicts.Take(5).Select(c => c.ToString()));
if (result.Conflicts.Count > 5)
detail += $"\n... und {result.Conflicts.Count - 5} weitere";
_trayIcon.ShowBalloonTip(10000,
$"Konflikt bei {result.Conflicts.Count} Kontakt(en)", detail, ToolTipIcon.Warning);
Balloon(10000, $"Konflikt bei {result.Conflicts.Count} Kontakt(en)", detail, ToolTipIcon.Warning, warn: true);
}
SetStatus(msg);
}
catch (Exception ex)
{
_trayIcon.ShowBalloonTip(3000, "Starface Sync Fehler",
ex.Message, ToolTipIcon.Error);
Balloon(3000, "Starface Sync Fehler", ex.Message, ToolTipIcon.Error, warn: true);
SetStatus($"Fehler: {ex.Message}");
}
finally
{
crossLock?.Dispose();
Interlocked.Exchange(ref _syncRunning, 0);
Logger.Log($"Sync FEHLER '{profile.Name}': {ex.Message}");
}
}
/// <summary>
/// Holt die clientuebergreifende Lock-Datei aus dem konfigurierten
/// gemeinsamen Verzeichnis. Wartet bis zu 2 Minuten, falls ein anderer
/// Arbeitsplatz gerade synct. Gibt null zurueck, wenn die Sperre nicht
/// erlangt werden konnte (-> diesen Lauf ueberspringen).
/// Ist kein Verzeichnis konfiguriert oder es ist nicht erreichbar, wird
/// ohne clientuebergreifende Sperre fortgefahren (lokaler Schutz bleibt).
/// </summary>
private async Task<SyncLock> AcquireCrossClientLock()
/// <summary>Zeigt Konflikt-Hinweise anderer Arbeitsplaetze als Tray-Meldung.</summary>
private void ShowRemoteNoticesTray(System.Collections.Generic.List<ConflictNotice> notices)
{
var dir = UserSettings.Load().SharedDirectory;
if (string.IsNullOrWhiteSpace(dir))
return SyncLock.NoOp();
if (notices == null || notices.Count == 0) return;
var detail = string.Join("\n", notices.Take(5).Select(p => p.ToString()));
if (notices.Count > 5)
detail += $"\n... und {notices.Count - 5} weitere";
Balloon(10000, $"Konflikt an anderem Arbeitsplatz ({notices.Count})", detail, ToolTipIcon.Warning, warn: true);
}
try
{
// Legt das Verzeichnis bei Bedarf an (idempotent). Funktioniert mit
// UNC-Pfaden (\\server\freigabe\...) - kein Netzlaufwerk noetig.
System.IO.Directory.CreateDirectory(dir);
}
catch
{
SetStatus("Gemeinsames Verzeichnis nicht erreichbar - synce ohne Sperre.");
return SyncLock.NoOp();
}
var deadline = DateTime.UtcNow.AddMinutes(2);
int attempt = 0;
while (true)
{
var l = SyncLock.TryAcquire(dir, out var heldBy);
if (l != null) return l;
if (DateTime.UtcNow >= deadline) return null;
attempt++;
SetStatus($"Warte auf anderen Arbeitsplatz ({heldBy ?? "unbekannt"})... ({attempt})");
await Task.Delay(3000);
}
/// <summary>
/// Zeigt eine Tray-Meldung - aber nur, wenn die passende Benachrichtigungs-
/// Einstellung aktiv ist. warn=true -> Warnungen/Fehler (Konflikte, Fehler),
/// warn=false -> allgemeine Info-Meldungen.
/// </summary>
private void Balloon(int ms, string title, string text, ToolTipIcon icon, bool warn)
{
bool allow = warn ? _notifyWarn : _notifyGeneral;
if (allow) _trayIcon.ShowBalloonTip(ms, title, text, icon);
}
private void SetStatus(string text)
@@ -463,6 +450,14 @@ namespace StarfaceOutlookSync.UI
}
}
private void ShowLog()
{
using (var log = new LogViewerForm())
{
log.ShowDialog(this);
}
}
private void ExitApplication()
{
_autoSyncTimer?.Stop();
+69 -26
View File
@@ -24,10 +24,30 @@ namespace StarfaceOutlookSync.UI
private Label _lblTestResult;
private Label _lblDirectionHint;
private List<StarfaceAddressBook> _addressBooks = new List<StarfaceAddressBook>();
private List<RemoteAddressBook> _addressBooks = new List<RemoteAddressBook>();
private List<string> _outlookFolderPaths = new List<string>();
private string _selectedOutlookPath = "";
private string _selectedOutlookName = "";
private ComboBox _cmbSystem;
private Label _lblAnlage;
private Label _lblLoginId;
private Label _lblAddressBook;
private string AnlagenName => GewaehlteAnlage == PhoneSystem.Fonaria ? "Fonaria" : "Starface";
private PhoneSystem GewaehlteAnlage =>
_cmbSystem != null && _cmbSystem.SelectedIndex == 1 ? PhoneSystem.Fonaria : PhoneSystem.Starface;
/// <summary>Beschriftungen, die je nach Anlage anders heissen.</summary>
private void UpdateSystemLabels()
{
var fonaria = GewaehlteAnlage == PhoneSystem.Fonaria;
if (_lblLoginId != null)
_lblLoginId.Text = fonaria ? "Benutzername:" : "Login-ID:";
if (_lblAddressBook != null)
_lblAddressBook.Text = fonaria ? "Fonaria-Adressbuch:" : "Starface-Adressbuch:";
UpdateDirectionHint();
}
public ProfileEditorForm(SyncProfile profile)
{
@@ -54,8 +74,26 @@ namespace StarfaceOutlookSync.UI
panel.Controls.Add(MakeLabel("Profilname:", 12, y)); y += 22;
_txtName = new TextBox { Left = 12, Top = y, Width = 420 }; panel.Controls.Add(_txtName); y += 32;
// === Starface ===
panel.Controls.Add(MakeSectionLabel("Starface-Verbindung", 12, y)); y += 26;
// === Anlage ===
_lblAnlage = MakeSectionLabel("Verbindung zur Telefonanlage", 12, y); y += 26;
panel.Controls.Add(_lblAnlage);
panel.Controls.Add(MakeLabel("Anlage:", 12, y)); y += 22;
_cmbSystem = new ComboBox { Left = 12, Top = y, Width = 200, DropDownStyle = ComboBoxStyle.DropDownList };
_cmbSystem.Items.AddRange(new object[] { "Starface", "Fonaria" });
_cmbSystem.SelectedIndex = 0;
// Beide sprechen ihre eigene Schnittstelle; der Vorgabeport ist
// derselbe, aber die Adressbuecher heissen anders. Beim Wechsel
// muss die Auswahl darum neu geladen werden.
_cmbSystem.SelectedIndexChanged += (s, e) =>
{
_addressBooks.Clear();
_cmbAddressBook.Items.Clear();
_lblTestResult.Text = "Anlage gewechselt - bitte Adressbuecher neu laden.";
_lblTestResult.ForeColor = Color.FromArgb(150, 80, 0);
UpdateSystemLabels();
};
panel.Controls.Add(_cmbSystem); y += 32;
panel.Controls.Add(MakeLabel("Host / IP-Adresse:", 12, y)); y += 22;
_txtHost = new TextBox { Left = 12, Top = y, Width = 320 };
@@ -67,7 +105,8 @@ namespace StarfaceOutlookSync.UI
_chkSsl = new CheckBox { Text = "HTTPS verwenden", Left = 12, Top = y, Checked = true, AutoSize = true };
panel.Controls.Add(_chkSsl); y += 28;
panel.Controls.Add(MakeLabel("Login-ID:", 12, y)); y += 22;
_lblLoginId = MakeLabel("Login-ID:", 12, y);
panel.Controls.Add(_lblLoginId); y += 22;
_txtLoginId = new TextBox { Left = 12, Top = y, Width = 200 }; panel.Controls.Add(_txtLoginId); y += 32;
panel.Controls.Add(MakeLabel("Kennwort:", 12, y)); y += 22;
@@ -84,7 +123,8 @@ namespace StarfaceOutlookSync.UI
_lblTestResult = new Label { Left = 12, Top = y, Width = 420, Height = 20, ForeColor = Color.Gray };
panel.Controls.Add(_lblTestResult); y += 26;
panel.Controls.Add(MakeLabel("Starface-Adressbuch:", 12, y)); y += 22;
_lblAddressBook = MakeLabel("Adressbuch der Anlage:", 12, y);
panel.Controls.Add(_lblAddressBook); y += 22;
_cmbAddressBook = new ComboBox { Left = 12, Top = y, Width = 420, DropDownStyle = ComboBoxStyle.DropDownList };
panel.Controls.Add(_cmbAddressBook); y += 32;
@@ -100,7 +140,7 @@ namespace StarfaceOutlookSync.UI
panel.Controls.Add(MakeLabel("Sync-Richtung:", 12, y)); y += 22;
_cmbDirection = new ComboBox { Left = 12, Top = y, Width = 250, DropDownStyle = ComboBoxStyle.DropDownList };
_cmbDirection.Items.AddRange(new object[] { "Bidirektional", "Outlook -> Starface", "Starface -> Outlook" });
_cmbDirection.Items.AddRange(new object[] { "Bidirektional", "Outlook -> Anlage", "Anlage -> Outlook" });
_cmbDirection.SelectedIndex = 0;
panel.Controls.Add(_cmbDirection); y += 28;
@@ -138,11 +178,11 @@ namespace StarfaceOutlookSync.UI
{
switch (_cmbDirection.SelectedIndex)
{
case 1: // Outlook -> Starface
_lblDirectionHint.Text = "Achtung: Das Starface-Adressbuch wird zur exakten Kopie von Outlook.\nKontakte, die nur in Starface existieren, werden geloescht.";
case 1: // Outlook -> Anlage
_lblDirectionHint.Text = $"Achtung: Das Adressbuch der {AnlagenName} wird zur exakten Kopie von Outlook.\nKontakte, die nur dort existieren, werden geloescht.";
break;
case 2: // Starface -> Outlook
_lblDirectionHint.Text = "Achtung: Der Outlook-Ordner wird zur exakten Kopie von Starface.\nKontakte, die nur in Outlook existieren, werden geloescht.";
case 2: // Anlage -> Outlook
_lblDirectionHint.Text = $"Achtung: Der Outlook-Ordner wird zur exakten Kopie der {AnlagenName}.\nKontakte, die nur in Outlook existieren, werden geloescht.";
break;
default: // Bidirektional
_lblDirectionHint.Text = "Aenderungen werden in beide Richtungen abgeglichen.";
@@ -182,15 +222,17 @@ namespace StarfaceOutlookSync.UI
if (_existingProfile != null)
{
_txtName.Text = _existingProfile.Name;
_txtHost.Text = _existingProfile.StarfaceConnection.Host;
_txtPort.Text = _existingProfile.StarfaceConnection.Port.ToString();
_chkSsl.Checked = _existingProfile.StarfaceConnection.UseSsl;
_txtLoginId.Text = _existingProfile.StarfaceConnection.LoginId;
_txtPassword.Text = _existingProfile.StarfaceConnection.Password;
_cmbSystem.SelectedIndex = _existingProfile.Connection.System == PhoneSystem.Fonaria ? 1 : 0;
_txtHost.Text = _existingProfile.Connection.Host;
_txtPort.Text = _existingProfile.Connection.Port.ToString();
_chkSsl.Checked = _existingProfile.Connection.UseSsl;
_txtLoginId.Text = _existingProfile.Connection.LoginId;
_txtPassword.Text = _existingProfile.Connection.Password;
_chkEnabled.Checked = _existingProfile.Enabled;
_numAutoSync.Value = _existingProfile.AutoSyncIntervalMinutes;
_cmbDirection.SelectedIndex = (int)_existingProfile.SyncDirection;
UpdateSystemLabels();
// Outlook-Ordner
_selectedOutlookPath = _existingProfile.OutlookFolderPath;
@@ -198,10 +240,10 @@ namespace StarfaceOutlookSync.UI
_txtOutlookFolder.Text = _selectedOutlookPath;
// Adressbuch
if (_existingProfile.StarfaceAddressBook != null)
if (_existingProfile.AddressBook != null)
{
_addressBooks.Add(_existingProfile.StarfaceAddressBook);
_cmbAddressBook.Items.Add(_existingProfile.StarfaceAddressBook.Name);
_addressBooks.Add(_existingProfile.AddressBook);
_cmbAddressBook.Items.Add(_existingProfile.AddressBook.Name);
_cmbAddressBook.SelectedIndex = 0;
}
}
@@ -227,10 +269,11 @@ namespace StarfaceOutlookSync.UI
}
}
private StarfaceConnection GetConnection()
private SystemConnection GetConnection()
{
return new StarfaceConnection
return new SystemConnection
{
System = GewaehlteAnlage,
Host = _txtHost.Text.Trim(),
Port = int.TryParse(_txtPort.Text, out var p) ? p : 443,
UseSsl = _chkSsl.Checked,
@@ -247,7 +290,7 @@ namespace StarfaceOutlookSync.UI
try
{
using (var client = new StarfaceApiClient(GetConnection()))
using (var client = ContactBackendFactory.Create(GetConnection()))
{
var ok = await client.LoginAsync();
if (ok)
@@ -280,7 +323,7 @@ namespace StarfaceOutlookSync.UI
try
{
using (var client = new StarfaceApiClient(GetConnection()))
using (var client = ContactBackendFactory.Create(GetConnection()))
{
var ok = await client.LoginAsync();
if (!ok)
@@ -350,8 +393,8 @@ namespace StarfaceOutlookSync.UI
{
Id = _existingProfile?.Id ?? _pm.GenerateId(),
Name = _txtName.Text.Trim(),
StarfaceConnection = GetConnection(),
StarfaceAddressBook = _addressBooks[_cmbAddressBook.SelectedIndex],
Connection = GetConnection(),
AddressBook = _addressBooks[_cmbAddressBook.SelectedIndex],
OutlookFolderPath = _selectedOutlookPath,
OutlookFolderName = _selectedOutlookName,
SyncDirection = (SyncDirection)_cmbDirection.SelectedIndex,
@@ -367,8 +410,8 @@ namespace StarfaceOutlookSync.UI
else
{
// Wenn Adressbuch gewechselt wurde, Mappings zuruecksetzen
if (_existingProfile.StarfaceAddressBook?.TagId != profile.StarfaceAddressBook?.TagId
|| _existingProfile.StarfaceAddressBook?.Type != profile.StarfaceAddressBook?.Type)
if (_existingProfile.AddressBook?.TagId != profile.AddressBook?.TagId
|| _existingProfile.AddressBook?.Type != profile.AddressBook?.Type)
{
_pm.SaveMappings(profile.Id, new List<SyncMapping>());
profile.LastSync = "";
+81 -8
View File
@@ -1,12 +1,16 @@
using System.Drawing;
using System.Windows.Forms;
using StarfaceOutlookSync.Models;
using StarfaceOutlookSync.Services;
namespace StarfaceOutlookSync.UI
{
public class SettingsForm : Form
{
private CheckBox _chkStartMinimized, _chkSyncOnStart, _chkAutoAcceptOutlook;
private CheckBox _chkNotifGeneral, _chkNotifWarn;
private CheckBox _chkAutostartUser, _chkAutostartAll;
private NumericUpDown _numLogRetention;
private TextBox _txtSharedDir;
private Button _btnBrowseShared;
private Button _btnSave, _btnCancel;
@@ -61,21 +65,47 @@ namespace StarfaceOutlookSync.UI
Font = new Font("Segoe UI", 8)
};
_chkNotifGeneral = new CheckBox
{
Text = "Tray-Benachrichtigungen (allgemein)",
Left = 20, Top = 144, AutoSize = true,
Checked = _settings.NotificationsEnabled
};
_chkNotifWarn = new CheckBox
{
Text = "Benachrichtigungen bei Warnungen/Fehlern (Konflikte, Fehler)",
Left = 20, Top = 170, AutoSize = true,
Checked = _settings.NotifyWarningsErrors
};
var lblLogRetention = new Label
{
Text = "Protokoll auto-leeren - Eintraege aelter als (Tage, 0 = aus):",
Left = 20, Top = 204, AutoSize = true
};
_numLogRetention = new NumericUpDown
{
Left = 305, Top = 200, Width = 55, Minimum = 0, Maximum = 3650,
Value = System.Math.Max(0, System.Math.Min(3650, _settings.LogRetentionDays))
};
var lblShared = new Label
{
Text = "Gemeinsames Verzeichnis fuer Sync-Sperre (Mehrplatz, optional):",
Left = 20, Top = 150, AutoSize = true
Left = 20, Top = 240, AutoSize = true
};
_txtSharedDir = new TextBox
{
Left = 20, Top = 172, Width = 250,
Left = 20, Top = 262, Width = 250,
Text = _settings.SharedDirectory
};
_btnBrowseShared = new Button
{
Text = "...", Left = 274, Top = 171, Width = 36, Height = 24
Text = "...", Left = 274, Top = 261, Width = 36, Height = 24
};
_btnBrowseShared.Click += (s, e) => BrowseSharedDir();
@@ -83,26 +113,52 @@ namespace StarfaceOutlookSync.UI
{
Text = "Netzlaufwerk/UNC, das alle Arbeitsplaetze erreichen. Leer = keine\n" +
"clientuebergreifende Sperre (nur Schutz auf diesem PC).",
Left = 20, Top = 198, Width = 330, Height = 32,
Left = 20, Top = 288, Width = 330, Height = 32,
ForeColor = Color.Gray, Font = new Font("Segoe UI", 8)
};
// === Autostart ===
bool isAdmin = AutostartManager.IsAdmin();
var lblAutostart = new Label
{
Text = "Autostart (bei Windows-Anmeldung starten)",
Left = 12, Top = 332, AutoSize = true, Font = new Font("Segoe UI", 10, FontStyle.Bold)
};
_chkAutostartUser = new CheckBox
{
Text = "Nur fuer diesen Benutzer",
Left = 20, Top = 360, AutoSize = true,
Checked = AutostartManager.GetUserAutostart()
};
_chkAutostartAll = new CheckBox
{
Text = "Fuer alle Benutzer" + (isAdmin ? "" : " (nur mit Admin-Rechten aenderbar)"),
Left = 20, Top = 386, AutoSize = true,
Checked = AutostartManager.GetMachineAutostart(),
Enabled = isAdmin
};
_btnSave = new Button
{
Text = "Speichern", Left = 95, Top = 240, Width = 85, Height = 28,
Text = "Speichern", Left = 95, Top = 422, Width = 85, Height = 28,
DialogResult = DialogResult.None
};
_btnSave.Click += (s, e) => Save();
_btnCancel = new Button
{
Text = "Abbrechen", Left = 189, Top = 240, Width = 85, Height = 28,
Text = "Abbrechen", Left = 189, Top = 422, Width = 85, Height = 28,
DialogResult = DialogResult.Cancel
};
Size = new Size(380, 330);
Size = new Size(380, 512);
Controls.AddRange(new Control[] { _chkStartMinimized, _chkSyncOnStart, _chkAutoAcceptOutlook, lblHint,
lblShared, _txtSharedDir, _btnBrowseShared, lblSharedHint, _btnSave, _btnCancel });
_chkNotifGeneral, _chkNotifWarn, lblLogRetention, _numLogRetention,
lblShared, _txtSharedDir, _btnBrowseShared, lblSharedHint,
lblAutostart, _chkAutostartUser, _chkAutostartAll, _btnSave, _btnCancel });
AcceptButton = _btnSave;
CancelButton = _btnCancel;
}
@@ -126,8 +182,25 @@ namespace StarfaceOutlookSync.UI
_settings.StartMinimized = _chkStartMinimized.Checked;
_settings.SyncOnStart = _chkSyncOnStart.Checked;
_settings.AutoAcceptOutlookPrompt = _chkAutoAcceptOutlook.Checked;
_settings.NotificationsEnabled = _chkNotifGeneral.Checked;
_settings.NotifyWarningsErrors = _chkNotifWarn.Checked;
_settings.LogRetentionDays = (int)_numLogRetention.Value;
_settings.SharedDirectory = _txtSharedDir.Text.Trim();
_settings.Save();
// Sofort anwenden, damit der Effekt direkt sichtbar ist.
Logger.PruneOlderThan(_settings.LogRetentionDays);
// Autostart (Registry). Pro Benutzer immer; alle Benutzer nur mit Admin.
AutostartManager.SetUserAutostart(_chkAutostartUser.Checked);
if (AutostartManager.IsAdmin())
{
if (!AutostartManager.SetMachineAutostart(_chkAutostartAll.Checked))
MessageBox.Show(this,
"Autostart fuer alle Benutzer konnte nicht geaendert werden (Rechte?).",
"Autostart", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
DialogResult = DialogResult.OK;
Close();
}
+37 -16
View File
@@ -11,6 +11,7 @@ namespace StarfaceOutlookSync.UI
{
private readonly SyncProfile _profile;
private readonly SyncEngine _engine = new SyncEngine();
private readonly SyncCoordinator _coordinator = new SyncCoordinator();
private TextBox _txtLog;
private ProgressBar _progressBar;
private Button _btnClose, _btnStart;
@@ -34,7 +35,7 @@ namespace StarfaceOutlookSync.UI
var infoLabel = new Label
{
Text = $"{_profile.StarfaceConnection.Host} ({_profile.StarfaceAddressBook.Name}) <-> {_profile.OutlookFolderName}",
Text = $"{_profile.Connection.Host} ({_profile.AddressBook.Name}) <-> {_profile.OutlookFolderName}",
Left = 12, Top = 12, Width = 460, AutoSize = false, Height = 20
};
@@ -92,19 +93,46 @@ namespace StarfaceOutlookSync.UI
_progressBar.Style = ProgressBarStyle.Marquee;
_lblResult.Text = "";
_engine.OnProgress += AppendLog;
try
// Engine-Aufruf inkl. Live-Log: laeuft im Hintergrund, damit das
// Fenster reagiert. Guard/Lock/Notizen/Protokoll uebernimmt der
// Coordinator (gemeinsam mit dem Auto-/Tray-Sync).
Func<Task<SyncResult>> runEngine = async () =>
{
var result = await Task.Run(() => _engine.SyncProfileAsync(_profile));
_engine.OnProgress += AppendLog;
try { return await Task.Run(() => _engine.SyncProfileAsync(_profile)); }
finally { _engine.OnProgress -= AppendLog; }
};
_progressBar.Style = ProgressBarStyle.Blocks;
_progressBar.Value = 100;
var outcome = await _coordinator.RunAsync(_profile, runEngine, status: AppendLog);
var resultText = $"Erstellt: {result.Created} | Aktualisiert: {result.Updated} | Fehler: {result.Errors}";
_lblResult.Text = resultText;
_progressBar.Style = ProgressBarStyle.Blocks;
_progressBar.Value = 100;
if (outcome.Skipped)
{
_lblResult.Text = outcome.SkipReason;
_lblResult.ForeColor = Color.OrangeRed;
AppendLog(outcome.SkipReason);
}
else if (outcome.Error != null)
{
_lblResult.Text = $"Fehler: {outcome.Error.Message}";
_lblResult.ForeColor = Color.Red;
AppendLog($"FEHLER: {outcome.Error.Message}");
}
else
{
var result = outcome.Result;
_lblResult.Text = $"Erstellt: {result.Created} | Aktualisiert: {result.Updated} | Fehler: {result.Errors}";
_lblResult.ForeColor = result.Errors > 0 ? Color.OrangeRed : Color.Green;
// Konflikt-Hinweise anderer Arbeitsplaetze im Fenster zeigen.
foreach (var n in outcome.RemoteNotices)
AppendLog($"Konflikt an anderem Arbeitsplatz: {n}");
foreach (var c in result.Conflicts)
AppendLog($"KONFLIKT: {c}");
if (result.ErrorMessages.Count > 0)
{
AppendLog("--- Fehler ---");
@@ -112,14 +140,7 @@ namespace StarfaceOutlookSync.UI
AppendLog(err);
}
}
catch (Exception ex)
{
_lblResult.Text = $"Fehler: {ex.Message}";
_lblResult.ForeColor = Color.Red;
AppendLog($"FEHLER: {ex.Message}");
}
_engine.OnProgress -= AppendLog;
_btnStart.Enabled = true;
_btnStart.Text = "Erneut synchronisieren";
_btnClose.Enabled = true;