Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 96c34e542f | |||
| 23223fe0be | |||
| b8a7fda7bf | |||
| 257b6fb33d | |||
| cf2970a41a | |||
| 5a0203e49e | |||
| 31aef01ccd | |||
| 6c9721acc6 | |||
| 212ced4c81 | |||
| d3fa452504 | |||
| bee17a7fc6 | |||
| 1987e25c37 | |||
| b5ad59ff9d | |||
| 1e9ff63833 | |||
| 561ffff03e | |||
| 53eed8eda3 | |||
| ad323c9d0f | |||
| 849a996b9a | |||
| b07a3b3a87 | |||
| f620e96d23 | |||
| e8731a87d4 | |||
| 53ca4611d1 | |||
| df13ddf6b1 | |||
| c08a625348 |
+119
@@ -0,0 +1,119 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
Alle nennenswerten Aenderungen an Starface Outlook Sync werden hier dokumentiert.
|
||||||
|
|
||||||
|
Format orientiert sich an [Keep a Changelog](https://keepachangelog.com/de/),
|
||||||
|
Versionsschema ist `x.x.x.x` (siehe `release.sh`).
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Behoben
|
||||||
|
|
||||||
|
- **Dubletten auf beiden Seiten beim Synchronisieren.** Mehrere zusammenhaengende
|
||||||
|
Ursachen wurden beseitigt:
|
||||||
|
- Eine unvollstaendig geladene Starface-Kontaktliste (z.B. durch einen
|
||||||
|
Lade-Fehler oder Timeout) liess die Engine Kontakte faelschlich als
|
||||||
|
"geloescht" ansehen, ihr Mapping verwerfen und sie beim naechsten Lauf neu
|
||||||
|
anlegen. Der Kontakt-Abruf bricht jetzt mit Fehlermeldung ab (inkl.
|
||||||
|
Wiederholversuch), statt still mit einer Teil-Liste weiterzuarbeiten.
|
||||||
|
- Ist ein Starface-Kontakt nicht in der geladenen Liste, wird er jetzt per
|
||||||
|
ID direkt abgefragt: existiert er noch (liegt also in einem **anderen
|
||||||
|
Adressbuch**), bleibt das Mapping erhalten und es wird nichts neu angelegt
|
||||||
|
(keine Dublette). Ist er **wirklich geloescht** (404), wird er je nach
|
||||||
|
Sync-Richtung in Starface neu angelegt bzw. die Loeschung nach Outlook
|
||||||
|
gespiegelt. (Vorher wurde das Mapping faelschlich behalten und der Kontakt
|
||||||
|
in Outlook->Starface gar nicht neu angelegt.)
|
||||||
|
- Das Wiederzuordnen bestehender Kontakte war zu streng: eine von Starface
|
||||||
|
umformatierte Telefonnummer konnte einen eindeutigen E-Mail- oder
|
||||||
|
Namens-Treffer ueberstimmen und so eine Neuanlage statt Verknuepfung
|
||||||
|
ausloesen. Ein gleicher E-Mail- oder voller Namens-Treffer reicht jetzt.
|
||||||
|
|
||||||
|
- **Synchronisation extrem langsam / schrieb bei jedem Lauf alle Kontakte neu.**
|
||||||
|
Die Aenderungserkennung verglich einen einzigen Hash gegen beide Seiten.
|
||||||
|
Outlook und Starface stellen denselben Kontakt aber unterschiedlich dar
|
||||||
|
(nicht uebertragene Felder, abweichendes Telefonformat), wodurch der Hash nie
|
||||||
|
uebereinstimmte und praktisch jeder Kontakt bei jedem Sync neu geschrieben
|
||||||
|
wurde. Jede Seite hat jetzt eine eigene Baseline (`LastOutlookHash` /
|
||||||
|
`LastStarfaceHash`); nur tatsaechlich geaenderte Kontakte werden geschrieben.
|
||||||
|
|
||||||
|
### Hinzugefuegt
|
||||||
|
|
||||||
|
- **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
|
||||||
|
Clients warten, bis sie frei ist (bis 2 Min, sonst wird der Lauf uebersprungen).
|
||||||
|
Stuerzt ein Client ab, uebernimmt ein anderer die verwaiste Sperre. Ist kein
|
||||||
|
Verzeichnis konfiguriert oder nicht erreichbar, wird ohne diese Sperre
|
||||||
|
weitergearbeitet (der lokale Schutz auf dem PC bleibt).
|
||||||
|
- **Feldweises 3-Wege-Merge bei Konflikten (bidirektional).** Wenn derselbe
|
||||||
|
Kontakt zwischen zwei Syncs auf beiden Seiten geaendert wurde, bleiben jetzt
|
||||||
|
Aenderungen an *unterschiedlichen* Feldern beide erhalten (z.B. einer aendert
|
||||||
|
die Telefonnummer in Outlook, ein anderer die E-Mail in Starface). Nur wenn
|
||||||
|
DASSELBE Feld auf beiden Seiten unterschiedlich geaendert wurde, greift die
|
||||||
|
Vorrang-Regel (Outlook gewinnt). Dafuer wird im Mapping zusaetzlich ein
|
||||||
|
Snapshot des letzten Sync-Stands je Seite gespeichert. Solche echten
|
||||||
|
Feld-Konflikte werden dem Benutzer per Tray-Meldung angezeigt.
|
||||||
|
|
||||||
|
### Geaendert
|
||||||
|
|
||||||
|
- **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
|
||||||
|
durchrutschen konnten.
|
||||||
|
- **Ein-Richtungs-Modi sind jetzt echtes "Ersetzen".** Outlook->Starface macht
|
||||||
|
das Starface-Adressbuch zu einer exakten Kopie von Outlook: Kontakte, die nur
|
||||||
|
in Starface existieren (kein Pendant in Outlook), werden geloescht.
|
||||||
|
Starface->Outlook entsprechend umgekehrt. Schutz: Ist die Quelle komplett
|
||||||
|
leer (z.B. falscher Ordner gewaehlt), wird die Loeschphase uebersprungen
|
||||||
|
statt die Zielseite zu leeren. Mass-Loeschungen finden nur bei vollstaendig
|
||||||
|
geladener Liste statt (unvollstaendige Ladevorgaenge brechen vorher ab).
|
||||||
|
- **Bidirektionale Loeschungen** werden jetzt erkannt. Wird ein Kontakt auf
|
||||||
|
einer Seite geloescht und ist die andere Seite seit dem letzten Sync
|
||||||
|
unveraendert (Abgleich ueber die gespeicherte Baseline), wird die Loeschung
|
||||||
|
auf die andere Seite gespiegelt – statt den Kontakt wieder anzulegen. Wurde
|
||||||
|
die andere Seite zwischenzeitlich bearbeitet, gewinnt die Bearbeitung und der
|
||||||
|
Kontakt wird neu angelegt (kein Datenverlust). In den Ein-Richtungs-Modi
|
||||||
|
bleibt die jeweilige Quelle fuehrend (Loeschung im Ziel wird wiederhergestellt).
|
||||||
|
- Starface-Kontaktdetails werden beim Laden parallel abgerufen (8 gleichzeitig)
|
||||||
|
statt einzeln nacheinander – deutlich schneller bei grossen Adressbuechern.
|
||||||
|
- `UpdateContact` (Outlook) und `UpdateContactAsync` (Starface) geben jetzt den
|
||||||
|
frisch eingelesenen Stand zurueck, damit die Baseline nach dem Schreiben
|
||||||
|
korrekt gesetzt wird und der Sync sauber konvergiert.
|
||||||
|
|
||||||
|
### Migration
|
||||||
|
|
||||||
|
- Bestehende Mapping-Dateien werden beim ersten Sync automatisch uebernommen
|
||||||
|
(ein ruhiger Durchlauf ohne Massen-Update).
|
||||||
|
- **Bereits vorhandene Dubletten werden nicht automatisch entfernt** – die Fixes
|
||||||
|
verhindern nur neue. Vorhandene Doppel-Kontakte einmalig manuell bereinigen.
|
||||||
|
|
||||||
|
## [0.0.0.23]
|
||||||
|
|
||||||
|
### Behoben
|
||||||
|
|
||||||
|
- Kritischer Loesch-Fehler: Kontakte wurden bei einer geaenderten Outlook-EntryID
|
||||||
|
nicht mehr massenhaft geloescht.
|
||||||
|
|
||||||
|
### Geaendert
|
||||||
|
|
||||||
|
- Outlook-Sicherheitsschluessel werden fuer Domaenenumgebungen zusaetzlich nach
|
||||||
|
HKLM geschrieben (unterdrueckt die Outlook-Sicherheitsabfrage).
|
||||||
|
|
||||||
|
## Aeltere Versionen
|
||||||
|
|
||||||
|
Aeltere Releases (v0.0.0.1 – v0.0.0.22) sind ueber die Git-Historie und die
|
||||||
|
Git-Tags nachvollziehbar.
|
||||||
@@ -8,7 +8,10 @@ Windows-Anwendung zur bidirektionalen Synchronisation von Kontakten zwischen Mic
|
|||||||
- **Profil-System** zum Verwalten mehrerer Sync-Konfigurationen (verschiedene Adressbuecher oder Anlagen)
|
- **Profil-System** zum Verwalten mehrerer Sync-Konfigurationen (verschiedene Adressbuecher oder Anlagen)
|
||||||
- **Starface-Adressbuecher**: Zentrales Adressbuch, persoenliches Adressbuch und Tag-basierte Adressbuecher
|
- **Starface-Adressbuecher**: Zentrales Adressbuch, persoenliches Adressbuch und Tag-basierte Adressbuecher
|
||||||
- **Outlook-Kontaktordner**: Frei waehlbarer Kontaktordner als Sync-Ziel
|
- **Outlook-Kontaktordner**: Frei waehlbarer Kontaktordner als Sync-Ziel
|
||||||
- **Sync-Richtung** konfigurierbar: Outlook -> Starface, Starface -> Outlook oder bidirektional
|
- **Sync-Richtung** konfigurierbar:
|
||||||
|
- *Bidirektional*: Aenderungen werden in beide Richtungen abgeglichen (inkl. Loeschungen)
|
||||||
|
- *Outlook -> Starface*: Das Starface-Adressbuch wird zur exakten Kopie von Outlook (nur in Starface vorhandene Kontakte werden geloescht)
|
||||||
|
- *Starface -> Outlook*: Der Outlook-Ordner wird zur exakten Kopie von Starface (nur in Outlook vorhandene Kontakte werden geloescht)
|
||||||
- **Intelligentes Matching**: Kontakte werden anhand von E-Mail-Adresse oder Name abgeglichen
|
- **Intelligentes Matching**: Kontakte werden anhand von E-Mail-Adresse oder Name abgeglichen
|
||||||
- **Aenderungserkennung**: Nur geaenderte Kontakte werden uebertragen (Hash-basiert)
|
- **Aenderungserkennung**: Nur geaenderte Kontakte werden uebertragen (Hash-basiert)
|
||||||
- **Auto-Sync**: Optionaler automatischer Sync in konfigurierbarem Intervall
|
- **Auto-Sync**: Optionaler automatischer Sync in konfigurierbarem Intervall
|
||||||
@@ -42,6 +45,32 @@ Windows-Anwendung zur bidirektionalen Synchronisation von Kontakten zwischen Mic
|
|||||||
5. Starface-Adressbuch und Outlook-Kontaktordner waehlen
|
5. Starface-Adressbuch und Outlook-Kontaktordner waehlen
|
||||||
6. Speichern und "Jetzt synchronisieren"
|
6. Speichern und "Jetzt synchronisieren"
|
||||||
|
|
||||||
|
### Outlook-Sicherheitsabfrage unterdruecken
|
||||||
|
|
||||||
|
Beim Zugriff auf Outlook-Kontakte zeigt Outlook standardmaessig einen
|
||||||
|
Sicherheitsdialog ("Ein Programm versucht auf Ihre E-Mail-Adressinformationen
|
||||||
|
zuzugreifen"). Dieser kann in den Einstellungen der App deaktiviert werden:
|
||||||
|
|
||||||
|
1. In der App auf "Einstellungen" klicken
|
||||||
|
2. "Outlook-Sicherheitsabfrage automatisch erlauben" aktivieren
|
||||||
|
3. Speichern
|
||||||
|
|
||||||
|
**Auf Domaenen-PCs / Terminal Servern:**
|
||||||
|
|
||||||
|
Die Outlook-Sicherheitseinstellungen werden dort per Gruppenrichtlinie (GPO)
|
||||||
|
gesteuert und sind im Trust Center ausgegraut. In diesem Fall muss die App
|
||||||
|
**einmalig als Administrator** gestartet werden, damit die Registry-Keys
|
||||||
|
unter HKLM geschrieben werden koennen:
|
||||||
|
|
||||||
|
1. Rechtsklick auf die App -> "Als Administrator ausfuehren"
|
||||||
|
2. Einstellungen -> "Outlook-Sicherheitsabfrage automatisch erlauben" aktivieren
|
||||||
|
3. Speichern und App schliessen
|
||||||
|
4. Outlook neu starten
|
||||||
|
5. App kann danach wieder normal (ohne Admin) gestartet werden
|
||||||
|
|
||||||
|
Die Einstellung bleibt dauerhaft bestehen und gilt fuer alle Benutzer
|
||||||
|
auf dem Rechner.
|
||||||
|
|
||||||
### Deinstallation
|
### Deinstallation
|
||||||
|
|
||||||
Ueber Windows Einstellungen -> Apps oder die Systemsteuerung.
|
Ueber Windows Einstellungen -> Apps oder die Systemsteuerung.
|
||||||
@@ -231,11 +260,60 @@ StarfaceOutlookSync.exe
|
|||||||
Alle Daten werden lokal pro Benutzer gespeichert:
|
Alle Daten werden lokal pro Benutzer gespeichert:
|
||||||
- `%AppData%\StarfaceOutlookSync\profiles.json` - Sync-Profile mit Zugangsdaten
|
- `%AppData%\StarfaceOutlookSync\profiles.json` - Sync-Profile mit Zugangsdaten
|
||||||
- `%AppData%\StarfaceOutlookSync\mappings\` - Kontakt-Zuordnungen pro Profil
|
- `%AppData%\StarfaceOutlookSync\mappings\` - Kontakt-Zuordnungen pro Profil
|
||||||
|
- `%AppData%\StarfaceOutlookSync\sync.log` - Protokoll (Syncs, Konflikte, Fehler);
|
||||||
|
im Hauptfenster ueber den Button **Protokoll** einsehbar
|
||||||
|
|
||||||
### SSL-Zertifikate
|
### SSL-Zertifikate
|
||||||
|
|
||||||
Self-signed Zertifikate der Starface werden automatisch akzeptiert. Es ist kein manueller Zertifikat-Import erforderlich.
|
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
|
## Lizenz
|
||||||
|
|
||||||
Proprietaer - Alle Rechte vorbehalten.
|
Proprietaer - Alle Rechte vorbehalten.
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
; Erfordert Inno Setup 6.x (https://jrsoftware.org/isinfo.php)
|
; Erfordert Inno Setup 6.x (https://jrsoftware.org/isinfo.php)
|
||||||
|
|
||||||
#define MyAppName "Starface Outlook Sync"
|
#define MyAppName "Starface Outlook Sync"
|
||||||
#define MyAppVersion "0.0.0.21"
|
#define MyAppVersion "0.0.0.29"
|
||||||
#define MyAppPublisher "HackerSoft - Hacker-Net Telekommunikation"
|
#define MyAppPublisher "HackerSoft - Hacker-Net Telekommunikation"
|
||||||
#define MyAppURL "https://www.hacker-net.de"
|
#define MyAppURL "https://www.hacker-net.de"
|
||||||
#define MyAppExeName "StarfaceOutlookSync.exe"
|
#define MyAppExeName "StarfaceOutlookSync.exe"
|
||||||
|
|||||||
@@ -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";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -45,6 +45,22 @@ namespace StarfaceOutlookSync.Models
|
|||||||
public string ProfileId { get; set; } = "";
|
public string ProfileId { get; set; } = "";
|
||||||
public string OutlookEntryId { get; set; } = "";
|
public string OutlookEntryId { get; set; } = "";
|
||||||
public string StarfaceId { get; set; } = "";
|
public string StarfaceId { get; set; } = "";
|
||||||
|
|
||||||
|
// Getrennte Baselines pro Seite. Outlook und Starface stellen denselben
|
||||||
|
// Kontakt unterschiedlich dar (Felder, Telefonformat), daher MUSS jede
|
||||||
|
// Seite gegen ihre eigene zuletzt-gesehene Repraesentation verglichen
|
||||||
|
// werden - sonst gilt jeder Kontakt bei jedem Sync als geaendert.
|
||||||
|
public string LastOutlookHash { get; set; } = "";
|
||||||
|
public string LastStarfaceHash { get; set; } = "";
|
||||||
|
|
||||||
|
// Snapshot des zuletzt synchronisierten Stands je Seite. Ermoeglicht ein
|
||||||
|
// feldweises 3-Wege-Merge bei Konflikten (welche Seite hat welches Feld
|
||||||
|
// geaendert), statt den ganzen Datensatz zu ueberschreiben. Null bei
|
||||||
|
// Alt-Mappings -> dann Fallback auf ganz-ueberschreiben.
|
||||||
|
public UnifiedContact LastOutlook { get; set; }
|
||||||
|
public UnifiedContact LastStarface { get; set; }
|
||||||
|
|
||||||
|
// Alt-Feld (vor v0.0.0.24). Nur noch fuer Migration bestehender Mappings.
|
||||||
public string LastSyncHash { get; set; } = "";
|
public string LastSyncHash { get; set; } = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,5 +72,24 @@ namespace StarfaceOutlookSync.Models
|
|||||||
public int Updated { get; set; }
|
public int Updated { get; set; }
|
||||||
public int Errors { get; set; }
|
public int Errors { get; set; }
|
||||||
public System.Collections.Generic.List<string> ErrorMessages { get; set; } = new System.Collections.Generic.List<string>();
|
public System.Collections.Generic.List<string> ErrorMessages { 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>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class FieldConflict
|
||||||
|
{
|
||||||
|
public string StarfaceId { get; set; } = "";
|
||||||
|
public string ContactName { 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"
|
||||||
|
|
||||||
|
public override string ToString() =>
|
||||||
|
$"{ContactName}: Feld '{Field}' auf beiden Seiten geaendert " +
|
||||||
|
$"(Outlook: '{OutlookValue}' / Starface: '{StarfaceValue}') -> {Winner} uebernommen";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,11 @@ namespace StarfaceOutlookSync.Models
|
|||||||
public bool SyncOnStart { get; set; } = false;
|
public bool SyncOnStart { get; set; } = false;
|
||||||
public bool AutoAcceptOutlookPrompt { get; set; } = false;
|
public bool AutoAcceptOutlookPrompt { get; set; } = false;
|
||||||
|
|
||||||
|
// Gemeinsames Verzeichnis (Netzlaufwerk/UNC) fuer die clientuebergreifende
|
||||||
|
// Sync-Sperre. Leer = keine Sperre (nur lokaler Schutz). Verhindert, dass
|
||||||
|
// mehrere Arbeitsplaetze gleichzeitig dasselbe Adressbuch synchronisieren.
|
||||||
|
public string SharedDirectory { get; set; } = "";
|
||||||
|
|
||||||
private static readonly string SettingsFile = Path.Combine(
|
private static readonly string SettingsFile = Path.Combine(
|
||||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||||
"StarfaceOutlookSync", "settings.json");
|
"StarfaceOutlookSync", "settings.json");
|
||||||
@@ -41,42 +46,80 @@ namespace StarfaceOutlookSync.Models
|
|||||||
|
|
||||||
public void ApplyOutlookSecuritySetting()
|
public void ApplyOutlookSecuritySetting()
|
||||||
{
|
{
|
||||||
// Alle Office-Versionen abdecken (16.0 = 2016/2019/2021/2024/365, 15.0 = 2013)
|
|
||||||
var versions = new[] { "16.0", "15.0" };
|
var versions = new[] { "16.0", "15.0" };
|
||||||
|
|
||||||
|
var securityValues = new (string name, int value)[]
|
||||||
|
{
|
||||||
|
("ObjectModelGuard", 2),
|
||||||
|
("PromptOOMAddressBookAccess", 2),
|
||||||
|
("PromptOOMAddressInformationAccess", 2),
|
||||||
|
("PromptOOMSend", 2),
|
||||||
|
("PromptOOMSaveAs", 2),
|
||||||
|
("PromptOOMFormulaAccess", 2),
|
||||||
|
("PromptOOMCustomAction", 2),
|
||||||
|
("PromptSimpleMAPISend", 2),
|
||||||
|
("PromptSimpleMAPINameResolve", 2),
|
||||||
|
("PromptSimpleMAPIOpenMessage", 2),
|
||||||
|
("AdminSecurityMode", 3),
|
||||||
|
};
|
||||||
|
|
||||||
|
// In alle moeglichen Pfade schreiben (HKCU + HKLM, Policies + direkt)
|
||||||
|
var roots = new[] { Registry.CurrentUser, Registry.LocalMachine };
|
||||||
|
var prefixes = new[]
|
||||||
|
{
|
||||||
|
@"Software\Policies\Microsoft\Office",
|
||||||
|
@"Software\Microsoft\Office"
|
||||||
|
};
|
||||||
|
|
||||||
foreach (var ver in versions)
|
foreach (var ver in versions)
|
||||||
{
|
{
|
||||||
|
foreach (var root in roots)
|
||||||
|
{
|
||||||
|
foreach (var prefix in prefixes)
|
||||||
|
{
|
||||||
|
var regPath = $@"{prefix}\{ver}\Outlook\Security";
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var regPath = $@"Software\Policies\Microsoft\Office\{ver}\Outlook\Security";
|
|
||||||
|
|
||||||
if (AutoAcceptOutlookPrompt)
|
if (AutoAcceptOutlookPrompt)
|
||||||
{
|
{
|
||||||
var key = Registry.CurrentUser.CreateSubKey(regPath);
|
var key = root.CreateSubKey(regPath);
|
||||||
key.SetValue("ObjectModelGuard", 2, RegistryValueKind.DWord);
|
if (key != null)
|
||||||
key.SetValue("PromptOOMAddressBookAccess", 2, RegistryValueKind.DWord);
|
{
|
||||||
key.SetValue("PromptOOMAddressInformationAccess", 2, RegistryValueKind.DWord);
|
foreach (var (name, value) in securityValues)
|
||||||
key.SetValue("PromptOOMSend", 2, RegistryValueKind.DWord);
|
key.SetValue(name, value, RegistryValueKind.DWord);
|
||||||
key.SetValue("PromptOOMSaveAs", 2, RegistryValueKind.DWord);
|
|
||||||
key.SetValue("PromptOOMFormulaAccess", 2, RegistryValueKind.DWord);
|
|
||||||
key.SetValue("PromptOOMCustomAction", 2, RegistryValueKind.DWord);
|
|
||||||
key.SetValue("PromptSimpleMAPISend", 2, RegistryValueKind.DWord);
|
|
||||||
key.SetValue("PromptSimpleMAPINameResolve", 2, RegistryValueKind.DWord);
|
|
||||||
key.SetValue("PromptSimpleMAPIOpenMessage", 2, RegistryValueKind.DWord);
|
|
||||||
key.SetValue("AdminSecurityMode", 3, RegistryValueKind.DWord);
|
|
||||||
key.Close();
|
key.Close();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
else
|
else
|
||||||
|
{
|
||||||
|
try { root.DeleteSubKey(regPath, false); } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { } // Kein Fehler wenn Rechte fehlen - naechsten Pfad versuchen
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Prueft ob die Outlook-Sicherheitseinstellung per GPO blockiert wird.
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsOutlookSecurityLockedByPolicy()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Registry.CurrentUser.DeleteSubKey(regPath, false);
|
// Wenn HKLM Policies gesetzt sind und wir dort nicht schreiben koennen
|
||||||
}
|
var key = Registry.LocalMachine.OpenSubKey(
|
||||||
catch { }
|
@"Software\Policies\Microsoft\Office\16.0\Outlook\Security", false);
|
||||||
|
if (key != null)
|
||||||
|
{
|
||||||
|
var val = key.GetValue("AdminSecurityMode");
|
||||||
|
key.Close();
|
||||||
|
if (val != null) return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch { }
|
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 { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using StarfaceOutlookSync.Models;
|
||||||
|
|
||||||
|
namespace StarfaceOutlookSync.Services
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Feldweises 3-Wege-Merge zweier Kontaktstaende gegen ihre Baseline.
|
||||||
|
/// Erlaubt es, dass zwei Stellen unterschiedliche Felder desselben Kontakts
|
||||||
|
/// aendern, ohne dass eine Aenderung verloren geht. Nur wenn DASSELBE Feld
|
||||||
|
/// auf beiden Seiten geaendert wurde, greift die Vorrang-Regel.
|
||||||
|
/// </summary>
|
||||||
|
public static class ContactMerger
|
||||||
|
{
|
||||||
|
private class FieldDef
|
||||||
|
{
|
||||||
|
public string Key;
|
||||||
|
public string Label;
|
||||||
|
public Func<UnifiedContact, string> Get;
|
||||||
|
public Action<UnifiedContact, string> Set;
|
||||||
|
public bool IsPhone;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly FieldDef[] Fields = new[]
|
||||||
|
{
|
||||||
|
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.
|
||||||
|
/// </summary>
|
||||||
|
public static (UnifiedContact merged, List<FieldConflict> conflicts) Merge(
|
||||||
|
UnifiedContact baseOutlook, UnifiedContact baseStarface,
|
||||||
|
UnifiedContact outlook, UnifiedContact starface,
|
||||||
|
bool outlookWins)
|
||||||
|
{
|
||||||
|
var merged = new UnifiedContact
|
||||||
|
{
|
||||||
|
OutlookEntryId = outlook.OutlookEntryId,
|
||||||
|
StarfaceId = starface.StarfaceId
|
||||||
|
};
|
||||||
|
var conflicts = new List<FieldConflict>();
|
||||||
|
|
||||||
|
foreach (var f in Fields)
|
||||||
|
{
|
||||||
|
string olv = f.Get(outlook) ?? "";
|
||||||
|
string sfv = f.Get(starface) ?? "";
|
||||||
|
string bol = f.Get(baseOutlook) ?? "";
|
||||||
|
string bsf = f.Get(baseStarface) ?? "";
|
||||||
|
|
||||||
|
bool olChanged = !Equal(olv, bol, f.IsPhone);
|
||||||
|
bool sfChanged = !Equal(sfv, bsf, f.IsPhone);
|
||||||
|
|
||||||
|
string chosen;
|
||||||
|
if (olChanged && !sfChanged)
|
||||||
|
{
|
||||||
|
chosen = olv;
|
||||||
|
}
|
||||||
|
else if (sfChanged && !olChanged)
|
||||||
|
{
|
||||||
|
chosen = sfv;
|
||||||
|
}
|
||||||
|
else if (olChanged && sfChanged)
|
||||||
|
{
|
||||||
|
if (Equal(olv, sfv, f.IsPhone))
|
||||||
|
{
|
||||||
|
// Beide auf denselben Wert geaendert -> kein echter Konflikt.
|
||||||
|
chosen = olv;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
chosen = outlookWins ? olv : sfv;
|
||||||
|
conflicts.Add(new FieldConflict
|
||||||
|
{
|
||||||
|
StarfaceId = starface.StarfaceId,
|
||||||
|
ContactName = outlook.DisplayName,
|
||||||
|
Field = f.Label,
|
||||||
|
FieldKey = f.Key,
|
||||||
|
OutlookValue = olv,
|
||||||
|
StarfaceValue = sfv,
|
||||||
|
Winner = outlookWins ? "Outlook" : "Starface"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Keine Seite hat dieses Feld geaendert -> Outlook-Wert behalten.
|
||||||
|
chosen = olv;
|
||||||
|
}
|
||||||
|
|
||||||
|
f.Set(merged, chosen);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (merged, conflicts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool Equal(string a, string b, bool isPhone)
|
||||||
|
{
|
||||||
|
if (isPhone)
|
||||||
|
return NormalizePhone(a) == NormalizePhone(b);
|
||||||
|
return string.Equals(a ?? "", b ?? "", StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string NormalizePhone(string phone)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(phone)) return "";
|
||||||
|
return new string(phone.Where(c => char.IsDigit(c) || c == '+').ToArray());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
using System;
|
||||||
|
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 ""; }
|
||||||
|
}
|
||||||
|
|
||||||
|
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 { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -350,7 +350,13 @@ namespace StarfaceOutlookSync.Services
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool UpdateContact(string entryId, UnifiedContact contact)
|
/// <summary>
|
||||||
|
/// Aktualisiert den Outlook-Kontakt und gibt den frisch eingelesenen
|
||||||
|
/// Stand zurueck (null bei Fehler). Der zurueckgegebene Kontakt liefert
|
||||||
|
/// den massgeblichen Hash NACH dem Schreiben - noetig damit die naechste
|
||||||
|
/// Synchronisation den Kontakt nicht erneut als geaendert erkennt.
|
||||||
|
/// </summary>
|
||||||
|
public UnifiedContact UpdateContact(string entryId, UnifiedContact contact)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -361,15 +367,17 @@ namespace StarfaceOutlookSync.Services
|
|||||||
MapToOutlook(contact, ci);
|
MapToOutlook(contact, ci);
|
||||||
ci.Save();
|
ci.Save();
|
||||||
|
|
||||||
|
var updated = MapFromOutlook(ci);
|
||||||
|
|
||||||
Marshal.ReleaseComObject(ci);
|
Marshal.ReleaseComObject(ci);
|
||||||
Marshal.ReleaseComObject(ns);
|
Marshal.ReleaseComObject(ns);
|
||||||
|
|
||||||
return true;
|
return updated;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
System.Diagnostics.Debug.WriteLine($"Error updating contact: {ex.Message}");
|
System.Diagnostics.Debug.WriteLine($"Error updating contact: {ex.Message}");
|
||||||
return false;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -194,7 +194,16 @@ namespace StarfaceOutlookSync.Services
|
|||||||
query += $"&tags={book.TagId}";
|
query += $"&tags={book.TagId}";
|
||||||
|
|
||||||
var resp = await _http.GetAsync($"{_baseUrl}/contacts?{query}");
|
var resp = await _http.GetAsync($"{_baseUrl}/contacts?{query}");
|
||||||
if (!resp.IsSuccessStatusCode) break;
|
if (!resp.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
// WICHTIG: nicht still abbrechen. Eine unvollstaendige Liste
|
||||||
|
// laesst die Sync-Engine Kontakte faelschlich als geloescht
|
||||||
|
// ansehen -> Mappings werden verworfen -> Dubletten.
|
||||||
|
throw new Exception(
|
||||||
|
$"Starface-Kontaktliste konnte nicht vollstaendig geladen werden " +
|
||||||
|
$"(Seite {page}: HTTP {(int)resp.StatusCode}). Synchronisation abgebrochen, " +
|
||||||
|
$"um Dubletten zu vermeiden.");
|
||||||
|
}
|
||||||
|
|
||||||
var body = await resp.Content.ReadAsStringAsync();
|
var body = await resp.Content.ReadAsStringAsync();
|
||||||
JArray array;
|
JArray array;
|
||||||
@@ -232,31 +241,40 @@ namespace StarfaceOutlookSync.Services
|
|||||||
|
|
||||||
OnDebug?.Invoke($"Seite {page}: {array.Count} Kontakte in Liste");
|
OnDebug?.Invoke($"Seite {page}: {array.Count} Kontakte in Liste");
|
||||||
|
|
||||||
// Die Listen-API gibt nur Summary zurueck.
|
|
||||||
// Jeden Kontakt einzeln abrufen fuer alle Felder.
|
|
||||||
foreach (var item in array)
|
|
||||||
{
|
|
||||||
var id = item["id"]?.ToString();
|
|
||||||
if (string.IsNullOrEmpty(id)) continue;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var detailResp = await _http.GetAsync($"{_baseUrl}/contacts/{id}");
|
|
||||||
if (detailResp.IsSuccessStatusCode)
|
|
||||||
{
|
|
||||||
var detailBody = await detailResp.Content.ReadAsStringAsync();
|
|
||||||
var detailObj = JObject.Parse(detailBody);
|
|
||||||
|
|
||||||
if (firstPage)
|
if (firstPage)
|
||||||
{
|
{
|
||||||
OnDebug?.Invoke($"Starface Kontakt-Detail (1. Kontakt):\n{detailObj.ToString(Formatting.Indented)}");
|
var firstId = array[0]?["id"]?.ToString();
|
||||||
|
if (!string.IsNullOrEmpty(firstId))
|
||||||
|
{
|
||||||
|
var sample = await FetchDetailAsync(firstId);
|
||||||
|
if (sample != null)
|
||||||
|
OnDebug?.Invoke($"Starface Kontakt-Detail (1. Kontakt):\n{sample.ToString(Formatting.Indented)}");
|
||||||
|
}
|
||||||
firstPage = false;
|
firstPage = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
contacts.Add(MapFromStarface(detailObj));
|
// Die Listen-API liefert nur eine Zusammenfassung; jeder Kontakt
|
||||||
}
|
// muss einzeln geladen werden. Das parallelisieren (begrenzt),
|
||||||
}
|
// sonst dauert es bei vielen Kontakten extrem lange.
|
||||||
catch { }
|
var ids = array
|
||||||
|
.Select(it => it["id"]?.ToString())
|
||||||
|
.Where(id => !string.IsNullOrEmpty(id))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
const int maxParallel = 8;
|
||||||
|
for (int i = 0; i < ids.Count; i += maxParallel)
|
||||||
|
{
|
||||||
|
var batch = ids.Skip(i).Take(maxParallel)
|
||||||
|
.Select(async id =>
|
||||||
|
{
|
||||||
|
var detail = await FetchDetailAsync(id);
|
||||||
|
// null = 404 (zwischenzeitlich geloescht) -> ueberspringen.
|
||||||
|
return detail == null ? null : MapFromStarface(detail);
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var mapped = await Task.WhenAll(batch);
|
||||||
|
contacts.AddRange(mapped.Where(c => c != null));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (array.Count < pageSize) break;
|
if (array.Count < pageSize) break;
|
||||||
@@ -266,6 +284,36 @@ namespace StarfaceOutlookSync.Services
|
|||||||
return contacts;
|
return contacts;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Laedt das Detail-JSON eines Kontakts mit kleiner Wiederholung.
|
||||||
|
/// Gibt null zurueck, wenn der Kontakt zwischen Listen- und Detail-Abruf
|
||||||
|
/// wirklich geloescht wurde (404 - harmlos, wird uebersprungen).
|
||||||
|
/// Wirft bei transienten Fehlern, damit der Aufrufer NICHT mit einer
|
||||||
|
/// unvollstaendigen Liste weiterarbeitet (sonst entstehen Dubletten).
|
||||||
|
/// </summary>
|
||||||
|
private async Task<JObject> FetchDetailAsync(string id)
|
||||||
|
{
|
||||||
|
for (int attempt = 0; attempt < 3; attempt++)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var resp = await _http.GetAsync($"{_baseUrl}/contacts/{id}");
|
||||||
|
if (resp.IsSuccessStatusCode)
|
||||||
|
return JObject.Parse(await resp.Content.ReadAsStringAsync());
|
||||||
|
|
||||||
|
// 404 = zwischenzeitlich geloescht; nicht erneut versuchen.
|
||||||
|
if (resp.StatusCode == HttpStatusCode.NotFound) return null;
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
|
||||||
|
await Task.Delay(250 * (attempt + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Exception(
|
||||||
|
$"Starface-Kontakt {id} konnte nach mehreren Versuchen nicht geladen werden. " +
|
||||||
|
$"Synchronisation abgebrochen, um Dubletten zu vermeiden.");
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<UnifiedContact> CreateContactAsync(UnifiedContact contact, StarfaceAddressBook book)
|
public async Task<UnifiedContact> CreateContactAsync(UnifiedContact contact, StarfaceAddressBook book)
|
||||||
{
|
{
|
||||||
var sfContact = MapToStarface(contact);
|
var sfContact = MapToStarface(contact);
|
||||||
@@ -300,7 +348,13 @@ namespace StarfaceOutlookSync.Services
|
|||||||
return MapFromStarface(created);
|
return MapFromStarface(created);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> UpdateContactAsync(string contactId, UnifiedContact contact, StarfaceAddressBook book)
|
/// <summary>
|
||||||
|
/// Aktualisiert den Starface-Kontakt und gibt den massgeblichen Stand
|
||||||
|
/// NACH dem Schreiben zurueck (null bei Fehler). Wird fuer die getrennte
|
||||||
|
/// 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)
|
||||||
{
|
{
|
||||||
var sfContact = MapToStarface(contact);
|
var sfContact = MapToStarface(contact);
|
||||||
sfContact["id"] = contactId;
|
sfContact["id"] = contactId;
|
||||||
@@ -323,9 +377,37 @@ namespace StarfaceOutlookSync.Services
|
|||||||
{
|
{
|
||||||
var respBody = await resp.Content.ReadAsStringAsync();
|
var respBody = await resp.Content.ReadAsStringAsync();
|
||||||
OnDebug?.Invoke($"PUT /contacts/{contactId} fehlgeschlagen: {(int)resp.StatusCode}\n{respBody}");
|
OnDebug?.Invoke($"PUT /contacts/{contactId} fehlgeschlagen: {(int)resp.StatusCode}\n{respBody}");
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return resp.IsSuccessStatusCode;
|
// Frischen Stand zurueckgeben. Manche Versionen liefern den Kontakt
|
||||||
|
// direkt in der PUT-Antwort, sonst per GET nachladen.
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var respBody = await resp.Content.ReadAsStringAsync();
|
||||||
|
if (!string.IsNullOrWhiteSpace(respBody))
|
||||||
|
{
|
||||||
|
var obj = JObject.Parse(respBody);
|
||||||
|
if (obj["blocks"] != null)
|
||||||
|
return MapFromStarface(obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
|
||||||
|
return await GetContactAsync(contactId) ?? contact;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Laedt einen einzelnen Kontakt mit allen Feldern.</summary>
|
||||||
|
public async Task<UnifiedContact> GetContactAsync(string contactId)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var resp = await _http.GetAsync($"{_baseUrl}/contacts/{contactId}");
|
||||||
|
if (!resp.IsSuccessStatusCode) return null;
|
||||||
|
var obj = JObject.Parse(await resp.Content.ReadAsStringAsync());
|
||||||
|
return MapFromStarface(obj);
|
||||||
|
}
|
||||||
|
catch { return null; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> DeleteContactAsync(string contactId)
|
public async Task<bool> DeleteContactAsync(string contactId)
|
||||||
|
|||||||
@@ -15,6 +15,20 @@ namespace StarfaceOutlookSync.Services
|
|||||||
|
|
||||||
private void Log(string message) => OnProgress?.Invoke(message);
|
private void Log(string message) => OnProgress?.Invoke(message);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Setzt die Baseline eines Mappings auf den uebergebenen Stand beider
|
||||||
|
/// Seiten (Snapshot + Hash). Der Snapshot wird fuer das Feld-Merge bei
|
||||||
|
/// kuenftigen Konflikten gebraucht.
|
||||||
|
/// </summary>
|
||||||
|
private static void SetBaseline(SyncMapping m, UnifiedContact outlook, UnifiedContact starface)
|
||||||
|
{
|
||||||
|
m.LastOutlook = outlook;
|
||||||
|
m.LastStarface = starface;
|
||||||
|
m.LastOutlookHash = outlook?.GetHash() ?? "";
|
||||||
|
m.LastStarfaceHash = starface?.GetHash() ?? "";
|
||||||
|
m.LastSyncHash = "";
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Findet einen passenden Kontakt in der Kandidatenliste.
|
/// Findet einen passenden Kontakt in der Kandidatenliste.
|
||||||
/// Strenges Matching: Felder die auf einer Seite gefuellt sind muessen
|
/// Strenges Matching: Felder die auf einer Seite gefuellt sind muessen
|
||||||
@@ -37,72 +51,38 @@ namespace StarfaceOutlookSync.Services
|
|||||||
|
|
||||||
private static bool IsMatch(UnifiedContact a, UnifiedContact b)
|
private static bool IsMatch(UnifiedContact a, UnifiedContact b)
|
||||||
{
|
{
|
||||||
// Mindestens ein identifizierendes Feld muss vorhanden sein
|
bool hasName = (!string.IsNullOrEmpty(a.FirstName) || !string.IsNullOrEmpty(a.LastName))
|
||||||
bool hasName = !string.IsNullOrEmpty(a.FirstName) || !string.IsNullOrEmpty(a.LastName);
|
&& (!string.IsNullOrEmpty(b.FirstName) || !string.IsNullOrEmpty(b.LastName));
|
||||||
bool hasEmail = !string.IsNullOrEmpty(a.Email);
|
|
||||||
bool hasPhone = !string.IsNullOrEmpty(a.PhoneWork) || !string.IsNullOrEmpty(a.PhoneMobile);
|
|
||||||
|
|
||||||
if (!hasName && !hasEmail && !hasPhone) return false;
|
// Starke Identifikatoren
|
||||||
|
|
||||||
// E-Mail: wenn auf beiden Seiten vorhanden, muss sie gleich sein
|
|
||||||
// Wenn nur auf einer Seite vorhanden -> kein Match
|
|
||||||
if (!FieldsCompatible(a.Email, b.Email)) return false;
|
|
||||||
|
|
||||||
// Name: wenn auf einer Seite vorhanden, muss er gleich sein
|
|
||||||
if (!FieldsCompatible(a.FirstName, b.FirstName)) return false;
|
|
||||||
if (!FieldsCompatible(a.LastName, b.LastName)) return false;
|
|
||||||
|
|
||||||
// Firma: wenn auf einer Seite vorhanden, muss sie gleich sein
|
|
||||||
// Leere Firma vs. gefuellte Firma = verschiedene Kontakte
|
|
||||||
if (!FieldsCompatible(a.Company, b.Company)) return false;
|
|
||||||
|
|
||||||
// Telefon/Fax: wenn auf einer Seite vorhanden, muss es gleich sein
|
|
||||||
if (!PhoneFieldsCompatible(a.PhoneWork, b.PhoneWork)) return false;
|
|
||||||
if (!PhoneFieldsCompatible(a.PhoneMobile, b.PhoneMobile)) return false;
|
|
||||||
if (!PhoneFieldsCompatible(a.PhoneHome, b.PhoneHome)) return false;
|
|
||||||
if (!PhoneFieldsCompatible(a.Fax, b.Fax)) return false;
|
|
||||||
|
|
||||||
// Mindestens ein starkes Match muss vorhanden sein
|
|
||||||
bool emailMatch = !string.IsNullOrEmpty(a.Email) && !string.IsNullOrEmpty(b.Email)
|
bool emailMatch = !string.IsNullOrEmpty(a.Email) && !string.IsNullOrEmpty(b.Email)
|
||||||
&& a.Email.Equals(b.Email, StringComparison.OrdinalIgnoreCase);
|
&& a.Email.Equals(b.Email, StringComparison.OrdinalIgnoreCase);
|
||||||
bool nameMatch = hasName
|
bool nameMatch = hasName
|
||||||
&& a.FirstName.Equals(b.FirstName, StringComparison.OrdinalIgnoreCase)
|
&& (a.FirstName ?? "").Equals(b.FirstName ?? "", StringComparison.OrdinalIgnoreCase)
|
||||||
&& a.LastName.Equals(b.LastName, StringComparison.OrdinalIgnoreCase)
|
&& (a.LastName ?? "").Equals(b.LastName ?? "", StringComparison.OrdinalIgnoreCase);
|
||||||
&& (!string.IsNullOrEmpty(a.FirstName) || !string.IsNullOrEmpty(a.LastName));
|
|
||||||
bool phoneMatch = (!string.IsNullOrEmpty(a.PhoneWork) && !string.IsNullOrEmpty(b.PhoneWork)
|
bool phoneMatch = (!string.IsNullOrEmpty(a.PhoneWork) && !string.IsNullOrEmpty(b.PhoneWork)
|
||||||
&& NormalizePhone(a.PhoneWork) == NormalizePhone(b.PhoneWork))
|
&& NormalizePhone(a.PhoneWork) == NormalizePhone(b.PhoneWork))
|
||||||
|
|| (!string.IsNullOrEmpty(a.PhoneMobile) && !string.IsNullOrEmpty(b.PhoneMobile)
|
||||||
|
&& NormalizePhone(a.PhoneMobile) == NormalizePhone(b.PhoneMobile))
|
||||||
|| (!string.IsNullOrEmpty(a.Fax) && !string.IsNullOrEmpty(b.Fax)
|
|| (!string.IsNullOrEmpty(a.Fax) && !string.IsNullOrEmpty(b.Fax)
|
||||||
&& NormalizePhone(a.Fax) == NormalizePhone(b.Fax));
|
&& NormalizePhone(a.Fax) == NormalizePhone(b.Fax));
|
||||||
bool companyMatch = !string.IsNullOrEmpty(a.Company) && !string.IsNullOrEmpty(b.Company)
|
bool companyMatch = !string.IsNullOrEmpty(a.Company) && !string.IsNullOrEmpty(b.Company)
|
||||||
&& a.Company.Equals(b.Company, StringComparison.OrdinalIgnoreCase);
|
&& a.Company.Equals(b.Company, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
// Email oder Name reicht. Telefon/Fax nur mit Firma zusammen.
|
// Widerspruch: beide haben eine E-Mail, aber unterschiedlich -> verschiedene Personen.
|
||||||
return emailMatch || nameMatch || (phoneMatch && companyMatch) || (companyMatch && phoneMatch);
|
bool emailContradiction = !string.IsNullOrEmpty(a.Email) && !string.IsNullOrEmpty(b.Email) && !emailMatch;
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
// Gleiche E-Mail ist der staerkste Identifikator und reicht allein.
|
||||||
/// Prueft ob zwei Felder kompatibel sind.
|
if (emailMatch) return true;
|
||||||
/// Beide leer = kompatibel. Beide gleich = kompatibel.
|
|
||||||
/// Eins leer, eins gefuellt = NICHT kompatibel (verschiedene Kontakte).
|
|
||||||
/// </summary>
|
|
||||||
private static bool FieldsCompatible(string a, string b)
|
|
||||||
{
|
|
||||||
bool aEmpty = string.IsNullOrEmpty(a);
|
|
||||||
bool bEmpty = string.IsNullOrEmpty(b);
|
|
||||||
|
|
||||||
if (aEmpty && bEmpty) return true;
|
// Gleicher voller Name reicht, solange keine widerspruechliche E-Mail vorliegt.
|
||||||
if (aEmpty != bEmpty) return false; // Einer leer, anderer nicht
|
// (Telefon-Umformatierung durch Starface darf einen Namens-Treffer NICHT verhindern.)
|
||||||
return a.Equals(b, StringComparison.OrdinalIgnoreCase);
|
if (nameMatch && !emailContradiction) return true;
|
||||||
}
|
|
||||||
|
|
||||||
private static bool PhoneFieldsCompatible(string a, string b)
|
// Schwacher Pfad: Telefon/Fax nur zusammen mit gleicher Firma und ohne E-Mail-Widerspruch.
|
||||||
{
|
if (phoneMatch && companyMatch && !emailContradiction) return true;
|
||||||
bool aEmpty = string.IsNullOrEmpty(a);
|
|
||||||
bool bEmpty = string.IsNullOrEmpty(b);
|
|
||||||
|
|
||||||
if (aEmpty && bEmpty) return true;
|
return false;
|
||||||
if (aEmpty != bEmpty) return false;
|
|
||||||
return NormalizePhone(a) == NormalizePhone(b);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string NormalizePhone(string phone)
|
private static string NormalizePhone(string phone)
|
||||||
@@ -183,56 +163,164 @@ namespace StarfaceOutlookSync.Services
|
|||||||
|
|
||||||
if (oc == null && sc != null)
|
if (oc == null && sc != null)
|
||||||
{
|
{
|
||||||
// In Outlook geloescht -> in Starface auch loeschen
|
// Outlook-Kontakt nicht gefunden.
|
||||||
if (profile.SyncDirection == SyncDirection.Both || profile.SyncDirection == SyncDirection.OutlookToStarface)
|
// Erst pruefen ob er vielleicht nur eine neue EntryID hat
|
||||||
|
var reMatch = FindMatch(sc, outlookContacts.Where(c =>
|
||||||
|
!processedOutlookIds.Contains(c.OutlookEntryId)).ToList());
|
||||||
|
if (reMatch != null)
|
||||||
{
|
{
|
||||||
|
// Kontakt existiert noch in Outlook, nur EntryID geaendert
|
||||||
|
Log($" EntryID geaendert, verknuepfe neu: {sc.DisplayName}");
|
||||||
|
mapping.OutlookEntryId = reMatch.OutlookEntryId;
|
||||||
|
processedOutlookIds.Add(reMatch.OutlookEntryId);
|
||||||
|
newMappings.Add(mapping);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wirklich in Outlook geloescht.
|
||||||
|
if (profile.SyncDirection == SyncDirection.OutlookToStarface)
|
||||||
|
{
|
||||||
|
// Outlook ist fuehrend -> Loeschung nach Starface spiegeln.
|
||||||
if (await starface.DeleteContactAsync(mapping.StarfaceId))
|
if (await starface.DeleteContactAsync(mapping.StarfaceId))
|
||||||
{
|
{
|
||||||
result.Updated++;
|
result.Updated++;
|
||||||
Log($" Geloescht (OL->SF): {sc.DisplayName}");
|
Log($" Geloescht (OL->SF): {sc.DisplayName}");
|
||||||
}
|
}
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
else
|
|
||||||
|
if (profile.SyncDirection == SyncDirection.Both)
|
||||||
{
|
{
|
||||||
// Richtung erlaubt kein Loeschen -> Mapping behalten
|
// Bidirektional: anhand der Baseline pruefen, ob die
|
||||||
newMappings.Add(mapping);
|
// Starface-Seite seit dem letzten Sync unveraendert ist.
|
||||||
|
bool sfUnchanged = !string.IsNullOrEmpty(mapping.LastStarfaceHash)
|
||||||
|
&& sc.GetHash() == mapping.LastStarfaceHash;
|
||||||
|
if (sfUnchanged)
|
||||||
|
{
|
||||||
|
// Unveraendert + in Outlook geloescht -> Loeschung gilt
|
||||||
|
// -> auch aus Starface entfernen.
|
||||||
|
if (await starface.DeleteContactAsync(mapping.StarfaceId))
|
||||||
|
{
|
||||||
|
result.Updated++;
|
||||||
|
Log($" Geloescht (OL->SF): {sc.DisplayName}");
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
// In Outlook geloescht, aber in Starface geaendert ->
|
||||||
|
// Bearbeitung gewinnt, in Outlook neu anlegen (Phase 3).
|
||||||
|
Log($" In Outlook geloescht, in Starface geaendert -> neu anlegen: {sc.DisplayName}");
|
||||||
|
processedStarfaceIds.Remove(sc.StarfaceId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// StarfaceToOutlook: Starface ist alleinige Quelle -> in Outlook
|
||||||
|
// neu anlegen (Loeschung im Ziel zaehlt nicht).
|
||||||
|
Log($" Outlook-Kontakt geloescht, wird neu angelegt: {sc.DisplayName}");
|
||||||
|
processedStarfaceIds.Remove(sc.StarfaceId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (oc != null && sc == null)
|
if (oc != null && sc == null)
|
||||||
{
|
{
|
||||||
// In Starface geloescht -> in Outlook auch loeschen
|
// Starface-Kontakt nicht in der geladenen Liste. Zwei Faelle
|
||||||
if (profile.SyncDirection == SyncDirection.Both || profile.SyncDirection == SyncDirection.StarfaceToOutlook)
|
// unterscheiden, indem wir ihn per ID direkt abfragen:
|
||||||
|
// (a) per ID noch vorhanden -> liegt in einem ANDEREN
|
||||||
|
// Adressbuch -> Mapping behalten, NICHT neu anlegen
|
||||||
|
// (sonst Dublette).
|
||||||
|
// (b) per ID 404 -> in Starface WIRKLICH geloescht.
|
||||||
|
bool stillExists = !string.IsNullOrEmpty(mapping.StarfaceId)
|
||||||
|
&& await starface.GetContactAsync(mapping.StarfaceId) != null;
|
||||||
|
|
||||||
|
if (stillExists)
|
||||||
{
|
{
|
||||||
if (_outlookService.DeleteContact(mapping.OutlookEntryId))
|
Log($" Starface-Kontakt in anderem Adressbuch, behalte Mapping: {oc.DisplayName}");
|
||||||
|
newMappings.Add(mapping);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wirklich in Starface geloescht.
|
||||||
|
if (profile.SyncDirection == SyncDirection.StarfaceToOutlook)
|
||||||
|
{
|
||||||
|
// Starface ist fuehrend -> Loeschung nach Outlook spiegeln.
|
||||||
|
if (_outlookService.DeleteContact(oc.OutlookEntryId))
|
||||||
{
|
{
|
||||||
result.Updated++;
|
result.Updated++;
|
||||||
Log($" Geloescht (SF->OL): {oc.DisplayName}");
|
Log($" Geloescht (SF->OL): {oc.DisplayName}");
|
||||||
}
|
}
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
else
|
|
||||||
|
if (profile.SyncDirection == SyncDirection.Both)
|
||||||
{
|
{
|
||||||
// Richtung erlaubt kein Loeschen -> Mapping behalten
|
// Bidirektional: anhand der Baseline entscheiden, ob der
|
||||||
newMappings.Add(mapping);
|
// Outlook-Kontakt seit dem letzten Sync unveraendert ist.
|
||||||
|
bool olUnchanged = !string.IsNullOrEmpty(mapping.LastOutlookHash)
|
||||||
|
&& oc.GetHash() == mapping.LastOutlookHash;
|
||||||
|
if (olUnchanged)
|
||||||
|
{
|
||||||
|
// Unveraendert + in Starface geloescht -> Loeschung gilt
|
||||||
|
// -> aus Outlook entfernen.
|
||||||
|
if (_outlookService.DeleteContact(oc.OutlookEntryId))
|
||||||
|
{
|
||||||
|
result.Updated++;
|
||||||
|
Log($" Geloescht (SF->OL): {oc.DisplayName}");
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
// In Starface geloescht, aber in Outlook geaendert ->
|
||||||
|
// Bearbeitung gewinnt, in Starface neu anlegen.
|
||||||
|
Log($" In Starface geloescht, in Outlook geaendert -> neu anlegen: {oc.DisplayName}");
|
||||||
|
processedOutlookIds.Remove(oc.OutlookEntryId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// OutlookToStarface: Outlook ist alleinige Quelle -> Kontakt
|
||||||
|
// in Starface neu anlegen (Loeschung im Ziel zaehlt nicht).
|
||||||
|
Log($" Starface-Kontakt geloescht, wird neu angelegt: {oc.DisplayName}");
|
||||||
|
processedOutlookIds.Remove(oc.OutlookEntryId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (oc != null && sc != null)
|
if (oc != null && sc != null)
|
||||||
{
|
{
|
||||||
// Beide vorhanden -> auf Aenderungen pruefen
|
// Beide vorhanden -> auf Aenderungen pruefen.
|
||||||
|
// WICHTIG: jede Seite gegen ihre EIGENE Baseline pruefen.
|
||||||
|
// Outlook und Starface stellen denselben Kontakt
|
||||||
|
// unterschiedlich dar, ein gemeinsamer Hash schlaegt nie an.
|
||||||
var olHash = oc.GetHash();
|
var olHash = oc.GetHash();
|
||||||
var sfHash = sc.GetHash();
|
var sfHash = sc.GetHash();
|
||||||
bool olChanged = olHash != mapping.LastSyncHash;
|
|
||||||
bool sfChanged = sfHash != mapping.LastSyncHash;
|
// Migration alter Mappings (nur LastSyncHash vorhanden):
|
||||||
|
// aktuellen Stand als Baseline uebernehmen und als synchron
|
||||||
|
// annehmen, damit kein Massen-Update ausgeloest wird.
|
||||||
|
if (string.IsNullOrEmpty(mapping.LastOutlookHash) &&
|
||||||
|
string.IsNullOrEmpty(mapping.LastStarfaceHash))
|
||||||
|
{
|
||||||
|
SetBaseline(mapping, oc, sc);
|
||||||
|
newMappings.Add(mapping);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool olChanged = olHash != mapping.LastOutlookHash;
|
||||||
|
bool sfChanged = sfHash != mapping.LastStarfaceHash;
|
||||||
|
|
||||||
|
if (!olChanged && !sfChanged)
|
||||||
|
{
|
||||||
|
// Unveraendert. Snapshots aelterer Mappings (nur Hash)
|
||||||
|
// nachtragen, damit kuenftige Konflikte gemergt werden koennen.
|
||||||
|
if (mapping.LastOutlook == null || mapping.LastStarface == null)
|
||||||
|
SetBaseline(mapping, oc, sc);
|
||||||
|
newMappings.Add(mapping);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (olChanged && !sfChanged && (profile.SyncDirection == SyncDirection.Both || profile.SyncDirection == SyncDirection.OutlookToStarface))
|
if (olChanged && !sfChanged && (profile.SyncDirection == SyncDirection.Both || profile.SyncDirection == SyncDirection.OutlookToStarface))
|
||||||
{
|
{
|
||||||
// Outlook hat sich geaendert -> Starface updaten
|
// Outlook hat sich geaendert -> Starface updaten
|
||||||
if (await starface.UpdateContactAsync(mapping.StarfaceId, oc, profile.StarfaceAddressBook))
|
var updated = await starface.UpdateContactAsync(mapping.StarfaceId, oc, profile.StarfaceAddressBook);
|
||||||
|
if (updated != null)
|
||||||
{
|
{
|
||||||
mapping.LastSyncHash = olHash;
|
SetBaseline(mapping, oc, updated);
|
||||||
result.Updated++;
|
result.Updated++;
|
||||||
Log($" Aktualisiert (OL->SF): {oc.DisplayName}");
|
Log($" Aktualisiert (OL->SF): {oc.DisplayName}");
|
||||||
}
|
}
|
||||||
@@ -240,36 +328,72 @@ namespace StarfaceOutlookSync.Services
|
|||||||
else if (sfChanged && !olChanged && (profile.SyncDirection == SyncDirection.Both || profile.SyncDirection == SyncDirection.StarfaceToOutlook))
|
else if (sfChanged && !olChanged && (profile.SyncDirection == SyncDirection.Both || profile.SyncDirection == SyncDirection.StarfaceToOutlook))
|
||||||
{
|
{
|
||||||
// Starface hat sich geaendert -> Outlook updaten
|
// Starface hat sich geaendert -> Outlook updaten
|
||||||
if (_outlookService.UpdateContact(mapping.OutlookEntryId, sc))
|
var updated = _outlookService.UpdateContact(mapping.OutlookEntryId, sc);
|
||||||
|
if (updated != null)
|
||||||
{
|
{
|
||||||
mapping.LastSyncHash = sfHash;
|
SetBaseline(mapping, updated, sc);
|
||||||
result.Updated++;
|
result.Updated++;
|
||||||
Log($" Aktualisiert (SF->OL): {sc.DisplayName}");
|
Log($" Aktualisiert (SF->OL): {sc.DisplayName}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (olChanged && sfChanged)
|
else if (olChanged && sfChanged)
|
||||||
{
|
{
|
||||||
// Beide geaendert -> Konflikt, neuere gewinnt (Outlook bevorzugt)
|
// Beide Seiten geaendert.
|
||||||
if (profile.SyncDirection != SyncDirection.StarfaceToOutlook)
|
if (profile.SyncDirection == SyncDirection.Both
|
||||||
|
&& mapping.LastOutlook != null && mapping.LastStarface != null)
|
||||||
{
|
{
|
||||||
if (await starface.UpdateContactAsync(mapping.StarfaceId, oc, profile.StarfaceAddressBook))
|
// Feldweises 3-Wege-Merge: unterschiedliche Felder
|
||||||
|
// bleiben beide erhalten; nur bei gleichem Feld auf
|
||||||
|
// beiden Seiten gewinnt Outlook.
|
||||||
|
var (merged, conflicts) = ContactMerger.Merge(
|
||||||
|
mapping.LastOutlook, mapping.LastStarface, oc, sc, outlookWins: true);
|
||||||
|
|
||||||
|
var updatedSf = await starface.UpdateContactAsync(mapping.StarfaceId, merged, profile.StarfaceAddressBook);
|
||||||
|
var updatedOl = _outlookService.UpdateContact(mapping.OutlookEntryId, merged);
|
||||||
|
|
||||||
|
if (updatedSf != null || updatedOl != null)
|
||||||
{
|
{
|
||||||
mapping.LastSyncHash = olHash;
|
if (updatedOl != null)
|
||||||
|
{
|
||||||
|
mapping.LastOutlook = updatedOl;
|
||||||
|
mapping.LastOutlookHash = updatedOl.GetHash();
|
||||||
|
}
|
||||||
|
if (updatedSf != null)
|
||||||
|
{
|
||||||
|
mapping.LastStarface = updatedSf;
|
||||||
|
mapping.LastStarfaceHash = updatedSf.GetHash();
|
||||||
|
}
|
||||||
|
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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (profile.SyncDirection != SyncDirection.StarfaceToOutlook)
|
||||||
|
{
|
||||||
|
// Fallback ohne Snapshot bzw. OutlookToStarface:
|
||||||
|
// Outlook gewinnt komplett.
|
||||||
|
var updated = await starface.UpdateContactAsync(mapping.StarfaceId, oc, profile.StarfaceAddressBook);
|
||||||
|
if (updated != null)
|
||||||
|
{
|
||||||
|
SetBaseline(mapping, oc, updated);
|
||||||
result.Updated++;
|
result.Updated++;
|
||||||
Log($" Konflikt (OL gewinnt): {oc.DisplayName}");
|
Log($" Konflikt (OL gewinnt): {oc.DisplayName}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if (_outlookService.UpdateContact(mapping.OutlookEntryId, sc))
|
var updated = _outlookService.UpdateContact(mapping.OutlookEntryId, sc);
|
||||||
|
if (updated != null)
|
||||||
{
|
{
|
||||||
mapping.LastSyncHash = sfHash;
|
SetBaseline(mapping, updated, sc);
|
||||||
result.Updated++;
|
result.Updated++;
|
||||||
Log($" Konflikt (SF gewinnt): {sc.DisplayName}");
|
Log($" Konflikt (SF gewinnt): {sc.DisplayName}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Beide unveraendert -> nichts tun
|
|
||||||
}
|
}
|
||||||
|
|
||||||
newMappings.Add(mapping);
|
newMappings.Add(mapping);
|
||||||
@@ -301,14 +425,18 @@ namespace StarfaceOutlookSync.Services
|
|||||||
if (match != null)
|
if (match != null)
|
||||||
{
|
{
|
||||||
// Existiert schon -> verknuepfen und updaten
|
// Existiert schon -> verknuepfen und updaten
|
||||||
if (await starface.UpdateContactAsync(match.StarfaceId, oc, profile.StarfaceAddressBook))
|
var updated = await starface.UpdateContactAsync(match.StarfaceId, oc, profile.StarfaceAddressBook);
|
||||||
|
if (updated != null)
|
||||||
{
|
{
|
||||||
newMappings.Add(new SyncMapping
|
newMappings.Add(new SyncMapping
|
||||||
{
|
{
|
||||||
ProfileId = profile.Id,
|
ProfileId = profile.Id,
|
||||||
OutlookEntryId = oc.OutlookEntryId,
|
OutlookEntryId = oc.OutlookEntryId,
|
||||||
StarfaceId = match.StarfaceId,
|
StarfaceId = match.StarfaceId,
|
||||||
LastSyncHash = oc.GetHash()
|
LastOutlook = oc,
|
||||||
|
LastStarface = updated,
|
||||||
|
LastOutlookHash = oc.GetHash(),
|
||||||
|
LastStarfaceHash = updated.GetHash()
|
||||||
});
|
});
|
||||||
processedStarfaceIds.Add(match.StarfaceId);
|
processedStarfaceIds.Add(match.StarfaceId);
|
||||||
unmappedStarface.Remove(match);
|
unmappedStarface.Remove(match);
|
||||||
@@ -328,7 +456,10 @@ namespace StarfaceOutlookSync.Services
|
|||||||
ProfileId = profile.Id,
|
ProfileId = profile.Id,
|
||||||
OutlookEntryId = oc.OutlookEntryId,
|
OutlookEntryId = oc.OutlookEntryId,
|
||||||
StarfaceId = created.StarfaceId,
|
StarfaceId = created.StarfaceId,
|
||||||
LastSyncHash = oc.GetHash()
|
LastOutlook = oc,
|
||||||
|
LastStarface = created,
|
||||||
|
LastOutlookHash = oc.GetHash(),
|
||||||
|
LastStarfaceHash = created.GetHash()
|
||||||
});
|
});
|
||||||
result.Created++;
|
result.Created++;
|
||||||
Log($" Erstellt (OL->SF): {oc.DisplayName}");
|
Log($" Erstellt (OL->SF): {oc.DisplayName}");
|
||||||
@@ -374,14 +505,18 @@ namespace StarfaceOutlookSync.Services
|
|||||||
if (match != null)
|
if (match != null)
|
||||||
{
|
{
|
||||||
// Existiert schon -> verknuepfen und updaten
|
// Existiert schon -> verknuepfen und updaten
|
||||||
if (_outlookService.UpdateContact(match.OutlookEntryId, sc))
|
var updated = _outlookService.UpdateContact(match.OutlookEntryId, sc);
|
||||||
|
if (updated != null)
|
||||||
{
|
{
|
||||||
newMappings.Add(new SyncMapping
|
newMappings.Add(new SyncMapping
|
||||||
{
|
{
|
||||||
ProfileId = profile.Id,
|
ProfileId = profile.Id,
|
||||||
OutlookEntryId = match.OutlookEntryId,
|
OutlookEntryId = match.OutlookEntryId,
|
||||||
StarfaceId = sc.StarfaceId,
|
StarfaceId = sc.StarfaceId,
|
||||||
LastSyncHash = sc.GetHash()
|
LastStarface = sc,
|
||||||
|
LastOutlook = updated,
|
||||||
|
LastStarfaceHash = sc.GetHash(),
|
||||||
|
LastOutlookHash = updated.GetHash()
|
||||||
});
|
});
|
||||||
processedOutlookIds.Add(match.OutlookEntryId);
|
processedOutlookIds.Add(match.OutlookEntryId);
|
||||||
unmappedOutlook.Remove(match);
|
unmappedOutlook.Remove(match);
|
||||||
@@ -400,7 +535,10 @@ namespace StarfaceOutlookSync.Services
|
|||||||
ProfileId = profile.Id,
|
ProfileId = profile.Id,
|
||||||
OutlookEntryId = created.OutlookEntryId,
|
OutlookEntryId = created.OutlookEntryId,
|
||||||
StarfaceId = sc.StarfaceId,
|
StarfaceId = sc.StarfaceId,
|
||||||
LastSyncHash = sc.GetHash()
|
LastStarface = sc,
|
||||||
|
LastOutlook = created,
|
||||||
|
LastStarfaceHash = sc.GetHash(),
|
||||||
|
LastOutlookHash = created.GetHash()
|
||||||
});
|
});
|
||||||
result.Created++;
|
result.Created++;
|
||||||
Log($" Erstellt (SF->OL): {sc.DisplayName}");
|
Log($" Erstellt (SF->OL): {sc.DisplayName}");
|
||||||
@@ -415,6 +553,77 @@ namespace StarfaceOutlookSync.Services
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Phase 4: Ersetzen-Modus - Zielseite an Quelle angleichen
|
||||||
|
// ============================================
|
||||||
|
// In den Ein-Richtungs-Modi soll die Zielseite eine exakte Kopie
|
||||||
|
// der Quelle werden. Kontakte, die nur auf der Zielseite existieren
|
||||||
|
// (kein Mapping, kein Treffer in der Quelle), werden geloescht.
|
||||||
|
// Sicher, weil unvollstaendige Ladevorgaenge vorher abbrechen.
|
||||||
|
if (profile.SyncDirection == SyncDirection.OutlookToStarface)
|
||||||
|
{
|
||||||
|
// Schutz gegen versehentliches Leerraeumen (z.B. falscher Ordner).
|
||||||
|
if (outlookContacts.Count == 0)
|
||||||
|
{
|
||||||
|
Log("Ersetzen-Modus uebersprungen: Outlook-Ordner ist leer (Schutz vor versehentlichem Leeren).");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var leftover = starfaceContacts
|
||||||
|
.Where(c => !string.IsNullOrEmpty(c.StarfaceId) && !processedStarfaceIds.Contains(c.StarfaceId))
|
||||||
|
.ToList();
|
||||||
|
if (leftover.Count > 0)
|
||||||
|
Log($"Ersetzen-Modus: entferne {leftover.Count} Kontakt(e) aus Starface, die nicht in Outlook existieren");
|
||||||
|
foreach (var sc in leftover)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (await starface.DeleteContactAsync(sc.StarfaceId))
|
||||||
|
{
|
||||||
|
result.Updated++;
|
||||||
|
Log($" Geloescht (nur in Starface): {sc.DisplayName}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
result.Errors++;
|
||||||
|
result.ErrorMessages.Add($"Loeschen SF {sc.DisplayName}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (profile.SyncDirection == SyncDirection.StarfaceToOutlook)
|
||||||
|
{
|
||||||
|
if (starfaceContacts.Count == 0)
|
||||||
|
{
|
||||||
|
Log("Ersetzen-Modus uebersprungen: Starface-Adressbuch ist leer (Schutz vor versehentlichem Leeren).");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var leftover = outlookContacts
|
||||||
|
.Where(c => !string.IsNullOrEmpty(c.OutlookEntryId) && !processedOutlookIds.Contains(c.OutlookEntryId))
|
||||||
|
.ToList();
|
||||||
|
if (leftover.Count > 0)
|
||||||
|
Log($"Ersetzen-Modus: entferne {leftover.Count} Kontakt(e) aus Outlook, die nicht in Starface existieren");
|
||||||
|
foreach (var oc in leftover)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_outlookService.DeleteContact(oc.OutlookEntryId))
|
||||||
|
{
|
||||||
|
result.Updated++;
|
||||||
|
Log($" Geloescht (nur in Outlook): {oc.DisplayName}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
result.Errors++;
|
||||||
|
result.ErrorMessages.Add($"Loeschen OL {oc.DisplayName}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Mappings speichern
|
// Mappings speichern
|
||||||
_profileManager.SaveMappings(profile.Id, newMappings);
|
_profileManager.SaveMappings(profile.Id, newMappings);
|
||||||
_profileManager.UpdateLastSync(profile.Id);
|
_profileManager.UpdateLastSync(profile.Id);
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
using System;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace StarfaceOutlookSync.Services
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Clientuebergreifende Sperre ueber eine Lock-Datei in einem gemeinsamen
|
||||||
|
/// Verzeichnis (Netzlaufwerk/Share). Verhindert, dass mehrere Arbeitsplaetze
|
||||||
|
/// gleichzeitig dasselbe Starface-Adressbuch synchronisieren.
|
||||||
|
///
|
||||||
|
/// Atomar ueber FileMode.CreateNew: das Anlegen schlaegt fehl, wenn die Datei
|
||||||
|
/// schon existiert. Die Datei wird waehrend des Syncs offen gehalten
|
||||||
|
/// (FileShare.None) - stuerzt ein Client ab, gibt das Betriebssystem das
|
||||||
|
/// Handle frei und ein anderer Client kann die (dann verwaiste) Datei
|
||||||
|
/// uebernehmen. Eine reine Zeitstempel-Pruefung allein waere nicht sicher.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SyncLock : IDisposable
|
||||||
|
{
|
||||||
|
public const string LockFileName = "starface-sync.lock";
|
||||||
|
|
||||||
|
// Aelter als das -> als verwaist behandeln und Uebernahme VERSUCHEN.
|
||||||
|
// Lebt der Eigentuemer noch, schlaegt das Loeschen am offenen Handle fehl,
|
||||||
|
// die Sperre bleibt also korrekt bestehen.
|
||||||
|
private static readonly TimeSpan StaleAfter = TimeSpan.FromMinutes(15);
|
||||||
|
|
||||||
|
private FileStream _stream;
|
||||||
|
private readonly string _path;
|
||||||
|
|
||||||
|
private SyncLock(string path, FileStream stream)
|
||||||
|
{
|
||||||
|
_path = path;
|
||||||
|
_stream = stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sperre, die nichts haelt (wenn kein gemeinsames Verzeichnis konfiguriert/erreichbar ist).</summary>
|
||||||
|
public static SyncLock NoOp() => new SyncLock(null, null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Versucht die Sperre zu holen. Gibt null zurueck, wenn gerade ein
|
||||||
|
/// anderer (lebender) Client synct. heldBy enthaelt - sofern lesbar -
|
||||||
|
/// Infos zum aktuellen Halter.
|
||||||
|
/// </summary>
|
||||||
|
public static SyncLock TryAcquire(string dir, out string heldBy)
|
||||||
|
{
|
||||||
|
heldBy = null;
|
||||||
|
var path = Path.Combine(dir, LockFileName);
|
||||||
|
|
||||||
|
var lockObj = TryCreate(path);
|
||||||
|
if (lockObj != null) return lockObj;
|
||||||
|
|
||||||
|
// Existiert bereits. Halter ermitteln und ggf. verwaiste Datei uebernehmen.
|
||||||
|
heldBy = ReadOwner(path);
|
||||||
|
if (IsStale(path))
|
||||||
|
{
|
||||||
|
try { File.Delete(path); } // scheitert, wenn der Halter noch lebt (Handle offen)
|
||||||
|
catch { return null; }
|
||||||
|
return TryCreate(path);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SyncLock TryCreate(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None);
|
||||||
|
var info = $"{Environment.MachineName}|{Environment.UserName}|{DateTime.UtcNow:o}|pid{GetPid()}";
|
||||||
|
var bytes = Encoding.UTF8.GetBytes(info);
|
||||||
|
fs.Write(bytes, 0, bytes.Length);
|
||||||
|
fs.Flush();
|
||||||
|
return new SyncLock(path, fs);
|
||||||
|
}
|
||||||
|
catch (IOException) { return null; } // existiert schon
|
||||||
|
catch (UnauthorizedAccessException) { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int GetPid()
|
||||||
|
{
|
||||||
|
try { return Process.GetCurrentProcess().Id; } catch { return 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ReadOwner(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Eigene Freigabe, falls der Halter die Datei nur zum Schreiben offen hat.
|
||||||
|
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||||
|
using (var sr = new StreamReader(fs))
|
||||||
|
{
|
||||||
|
var raw = sr.ReadToEnd();
|
||||||
|
var parts = raw.Split('|');
|
||||||
|
return parts.Length >= 1 ? parts[0] : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsStale(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var age = DateTime.UtcNow - File.GetLastWriteTimeUtc(path);
|
||||||
|
return age > StaleAfter;
|
||||||
|
}
|
||||||
|
catch { return false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
try { _stream?.Dispose(); } catch { }
|
||||||
|
_stream = null;
|
||||||
|
if (!string.IsNullOrEmpty(_path))
|
||||||
|
{
|
||||||
|
try { File.Delete(_path); } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,9 +7,9 @@
|
|||||||
<AssemblyTitle>Starface Outlook Sync</AssemblyTitle>
|
<AssemblyTitle>Starface Outlook Sync</AssemblyTitle>
|
||||||
<Company>HackerSoft - Hacker-Net Telekommunikation</Company>
|
<Company>HackerSoft - Hacker-Net Telekommunikation</Company>
|
||||||
<Product>Starface Outlook Sync</Product>
|
<Product>Starface Outlook Sync</Product>
|
||||||
<Version>0.0.0.21</Version>
|
<Version>0.0.0.29</Version>
|
||||||
<AssemblyVersion>0.0.0.21</AssemblyVersion>
|
<AssemblyVersion>0.0.0.29</AssemblyVersion>
|
||||||
<FileVersion>0.0.0.21</FileVersion>
|
<FileVersion>0.0.0.29</FileVersion>
|
||||||
<Description>Synchronisiert Outlook-Kontakte mit Starface Telefonanlage</Description>
|
<Description>Synchronisiert Outlook-Kontakte mit Starface Telefonanlage</Description>
|
||||||
<Copyright>Stefan Hacker - HackerSoft</Copyright>
|
<Copyright>Stefan Hacker - HackerSoft</Copyright>
|
||||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ namespace StarfaceOutlookSync.UI
|
|||||||
|
|
||||||
var lblVersion = new Label
|
var lblVersion = new Label
|
||||||
{
|
{
|
||||||
Text = "Version 0.0.0.21",
|
Text = "Version 0.0.0.29",
|
||||||
Left = 0, Top = 56, Width = 340, Height = 20,
|
Left = 0, Top = 56, Width = 340, Height = 20,
|
||||||
TextAlign = ContentAlignment.MiddleCenter,
|
TextAlign = ContentAlignment.MiddleCenter,
|
||||||
ForeColor = Color.Gray
|
ForeColor = Color.Gray
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
using System;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Drawing;
|
||||||
|
using System.IO;
|
||||||
|
using System.Windows.Forms;
|
||||||
|
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()
|
||||||
|
{
|
||||||
|
_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 { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Drawing;
|
using System.Drawing;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.Timers;
|
using System.Timers;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
@@ -15,14 +16,17 @@ namespace StarfaceOutlookSync.UI
|
|||||||
{
|
{
|
||||||
private readonly ProfileManager _profileManager = new ProfileManager();
|
private readonly ProfileManager _profileManager = new ProfileManager();
|
||||||
private readonly SyncEngine _syncEngine = new SyncEngine();
|
private readonly SyncEngine _syncEngine = new SyncEngine();
|
||||||
|
private readonly ConflictNotifier _conflictNotifier = new ConflictNotifier();
|
||||||
private NotifyIcon _trayIcon;
|
private NotifyIcon _trayIcon;
|
||||||
private ContextMenuStrip _trayMenu;
|
private ContextMenuStrip _trayMenu;
|
||||||
private ListView _profileList;
|
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 StatusStrip _statusBar;
|
||||||
private ToolStripStatusLabel _statusLabel;
|
private ToolStripStatusLabel _statusLabel;
|
||||||
private Timer _autoSyncTimer;
|
private Timer _autoSyncTimer;
|
||||||
private volatile bool _syncRunning = false;
|
// 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;
|
||||||
|
|
||||||
public MainForm()
|
public MainForm()
|
||||||
{
|
{
|
||||||
@@ -125,10 +129,13 @@ namespace StarfaceOutlookSync.UI
|
|||||||
_btnSettings = new Button { Text = "Einstellungen", Width = 95, Height = 30 };
|
_btnSettings = new Button { Text = "Einstellungen", Width = 95, Height = 30 };
|
||||||
_btnSettings.Click += (s, e) => ShowSettings();
|
_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 = new Button { Text = "Info", Width = 50, Height = 30 };
|
||||||
_btnInfo.Click += (s, e) => ShowAbout();
|
_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
|
||||||
_statusBar = new StatusStrip();
|
_statusBar = new StatusStrip();
|
||||||
@@ -337,15 +344,34 @@ namespace StarfaceOutlookSync.UI
|
|||||||
|
|
||||||
private async Task RunSync(SyncProfile profile)
|
private async Task RunSync(SyncProfile profile)
|
||||||
{
|
{
|
||||||
if (_syncRunning)
|
// 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...");
|
SetStatus("Sync laeuft bereits, bitte warten...");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_syncRunning = true;
|
SyncLock crossLock = null;
|
||||||
|
var sharedDir = UserSettings.Load().SharedDirectory;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
// Clientuebergreifende Sperre (falls gemeinsames Verzeichnis konfiguriert).
|
||||||
|
crossLock = await AcquireCrossClientLock(sharedDir);
|
||||||
|
if (crossLock == null)
|
||||||
|
{
|
||||||
|
SetStatus("Anderer Arbeitsplatz synchronisiert gerade - uebersprungen.");
|
||||||
|
Logger.Log($"Sync '{profile.Name}' uebersprungen: anderer Arbeitsplatz synct gerade.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.Log($"Sync gestartet: '{profile.Name}' (Richtung: {profile.SyncDirection})");
|
||||||
|
|
||||||
|
// Konflikt-Hinweise von ANDEREN Arbeitsplaetzen anzeigen, BEVOR der
|
||||||
|
// Sync den eigenen Stand auf den Gewinner-Wert aktualisiert (sonst
|
||||||
|
// koennte man nicht mehr erkennen, ob man betroffen war).
|
||||||
|
ShowRemoteConflictNotices(sharedDir);
|
||||||
|
|
||||||
SetStatus($"Synchronisiere '{profile.Name}'...");
|
SetStatus($"Synchronisiere '{profile.Name}'...");
|
||||||
_trayIcon.ShowBalloonTip(2000, "Starface Sync",
|
_trayIcon.ShowBalloonTip(2000, "Starface Sync",
|
||||||
$"Synchronisiere '{profile.Name}'...", ToolTipIcon.Info);
|
$"Synchronisiere '{profile.Name}'...", ToolTipIcon.Info);
|
||||||
@@ -354,10 +380,32 @@ namespace StarfaceOutlookSync.UI
|
|||||||
|
|
||||||
var msg = $"{profile.Name}: {result.Created} erstellt, {result.Updated} aktualisiert";
|
var msg = $"{profile.Name}: {result.Created} erstellt, {result.Updated} aktualisiert";
|
||||||
if (result.Errors > 0) msg += $", {result.Errors} Fehler";
|
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,
|
_trayIcon.ShowBalloonTip(3000, "Starface Sync", msg,
|
||||||
result.Errors > 0 ? ToolTipIcon.Warning : ToolTipIcon.Info);
|
result.Errors > 0 ? ToolTipIcon.Warning : ToolTipIcon.Info);
|
||||||
|
|
||||||
|
Logger.Log($"Sync fertig: {msg}");
|
||||||
|
foreach (var em in result.ErrorMessages)
|
||||||
|
Logger.Log($" Fehler: {em}");
|
||||||
|
|
||||||
|
// Echte Feld-Konflikte gesondert melden, damit der Benutzer weiss,
|
||||||
|
// dass ein Wert ueberschrieben wurde.
|
||||||
|
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);
|
||||||
|
|
||||||
|
foreach (var c in result.Conflicts)
|
||||||
|
Logger.Log($" KONFLIKT: {c}");
|
||||||
|
|
||||||
|
// Andere Arbeitsplaetze ueber das gemeinsame Verzeichnis informieren.
|
||||||
|
_conflictNotifier.Write(sharedDir, result.Conflicts);
|
||||||
|
}
|
||||||
|
|
||||||
SetStatus(msg);
|
SetStatus(msg);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -365,13 +413,99 @@ namespace StarfaceOutlookSync.UI
|
|||||||
_trayIcon.ShowBalloonTip(3000, "Starface Sync Fehler",
|
_trayIcon.ShowBalloonTip(3000, "Starface Sync Fehler",
|
||||||
ex.Message, ToolTipIcon.Error);
|
ex.Message, ToolTipIcon.Error);
|
||||||
SetStatus($"Fehler: {ex.Message}");
|
SetStatus($"Fehler: {ex.Message}");
|
||||||
|
Logger.Log($"Sync FEHLER '{profile.Name}': {ex.Message}");
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
_syncRunning = false;
|
crossLock?.Dispose();
|
||||||
|
Interlocked.Exchange(ref _syncRunning, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <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(string dir)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(dir))
|
||||||
|
return SyncLock.NoOp();
|
||||||
|
|
||||||
|
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 Konflikt-Hinweise an, die andere Arbeitsplaetze ueber das
|
||||||
|
/// gemeinsame Verzeichnis hinterlassen haben und Kontakte betreffen, die
|
||||||
|
/// auch dieser Client gemappt hat.
|
||||||
|
/// </summary>
|
||||||
|
private void ShowRemoteConflictNotices(string sharedDir)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(sharedDir)) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var pending = _conflictNotifier.GetPending(sharedDir, MyContactsByStarfaceId());
|
||||||
|
if (pending.Count == 0) return;
|
||||||
|
|
||||||
|
foreach (var p in pending)
|
||||||
|
Logger.Log($" KONFLIKT (anderer Arbeitsplatz): {p}");
|
||||||
|
|
||||||
|
var detail = string.Join("\n", pending.Take(5).Select(p => p.ToString()));
|
||||||
|
if (pending.Count > 5)
|
||||||
|
detail += $"\n... und {pending.Count - 5} weitere";
|
||||||
|
_trayIcon.ShowBalloonTip(10000,
|
||||||
|
$"Konflikt an anderem Arbeitsplatz ({pending.Count})", detail, ToolTipIcon.Warning);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Eigener Kontaktstand je StarfaceId (ueber alle Profile), aus den
|
||||||
|
/// Mapping-Snapshots. Dient dazu, bei Konflikt-Notizen zu pruefen, ob der
|
||||||
|
/// eigene Feldwert ueberhaupt vom uebernommenen Wert abweicht.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
private void SetStatus(string text)
|
private void SetStatus(string text)
|
||||||
{
|
{
|
||||||
if (InvokeRequired)
|
if (InvokeRequired)
|
||||||
@@ -396,6 +530,14 @@ namespace StarfaceOutlookSync.UI
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void ShowLog()
|
||||||
|
{
|
||||||
|
using (var log = new LogViewerForm())
|
||||||
|
{
|
||||||
|
log.ShowDialog(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void ExitApplication()
|
private void ExitApplication()
|
||||||
{
|
{
|
||||||
_autoSyncTimer?.Stop();
|
_autoSyncTimer?.Stop();
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ namespace StarfaceOutlookSync.UI
|
|||||||
private NumericUpDown _numAutoSync;
|
private NumericUpDown _numAutoSync;
|
||||||
private Button _btnTest, _btnLoadBooks, _btnSave, _btnCancel;
|
private Button _btnTest, _btnLoadBooks, _btnSave, _btnCancel;
|
||||||
private Label _lblTestResult;
|
private Label _lblTestResult;
|
||||||
|
private Label _lblDirectionHint;
|
||||||
|
|
||||||
private List<StarfaceAddressBook> _addressBooks = new List<StarfaceAddressBook>();
|
private List<StarfaceAddressBook> _addressBooks = new List<StarfaceAddressBook>();
|
||||||
private List<string> _outlookFolderPaths = new List<string>();
|
private List<string> _outlookFolderPaths = new List<string>();
|
||||||
@@ -101,7 +102,18 @@ namespace StarfaceOutlookSync.UI
|
|||||||
_cmbDirection = new ComboBox { Left = 12, Top = y, Width = 250, DropDownStyle = ComboBoxStyle.DropDownList };
|
_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 -> Starface", "Starface -> Outlook" });
|
||||||
_cmbDirection.SelectedIndex = 0;
|
_cmbDirection.SelectedIndex = 0;
|
||||||
panel.Controls.Add(_cmbDirection); y += 32;
|
panel.Controls.Add(_cmbDirection); y += 28;
|
||||||
|
|
||||||
|
_lblDirectionHint = new Label
|
||||||
|
{
|
||||||
|
Left = 12, Top = y, Width = 360, Height = 32,
|
||||||
|
ForeColor = Color.FromArgb(150, 80, 0),
|
||||||
|
Font = new Font("Segoe UI", 8.25f)
|
||||||
|
};
|
||||||
|
_cmbDirection.SelectedIndexChanged += (s, e) => UpdateDirectionHint();
|
||||||
|
panel.Controls.Add(_lblDirectionHint);
|
||||||
|
UpdateDirectionHint();
|
||||||
|
y += 36;
|
||||||
|
|
||||||
panel.Controls.Add(MakeLabel("Auto-Sync Intervall (Minuten, 0 = manuell):", 12, y)); y += 22;
|
panel.Controls.Add(MakeLabel("Auto-Sync Intervall (Minuten, 0 = manuell):", 12, y)); y += 22;
|
||||||
_numAutoSync = new NumericUpDown { Left = 12, Top = y, Width = 80, Minimum = 0, Maximum = 1440, Value = 0 };
|
_numAutoSync = new NumericUpDown { Left = 12, Top = y, Width = 80, Minimum = 0, Maximum = 1440, Value = 0 };
|
||||||
@@ -122,6 +134,22 @@ namespace StarfaceOutlookSync.UI
|
|||||||
CancelButton = _btnCancel;
|
CancelButton = _btnCancel;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void UpdateDirectionHint()
|
||||||
|
{
|
||||||
|
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.";
|
||||||
|
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.";
|
||||||
|
break;
|
||||||
|
default: // Bidirektional
|
||||||
|
_lblDirectionHint.Text = "Aenderungen werden in beide Richtungen abgeglichen.";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private Label MakeLabel(string text, int x, int y)
|
private Label MakeLabel(string text, int x, int y)
|
||||||
{
|
{
|
||||||
return new Label { Text = text, Left = x, Top = y, AutoSize = true };
|
return new Label { Text = text, Left = x, Top = y, AutoSize = true };
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ namespace StarfaceOutlookSync.UI
|
|||||||
public class SettingsForm : Form
|
public class SettingsForm : Form
|
||||||
{
|
{
|
||||||
private CheckBox _chkStartMinimized, _chkSyncOnStart, _chkAutoAcceptOutlook;
|
private CheckBox _chkStartMinimized, _chkSyncOnStart, _chkAutoAcceptOutlook;
|
||||||
|
private TextBox _txtSharedDir;
|
||||||
|
private Button _btnBrowseShared;
|
||||||
private Button _btnSave, _btnCancel;
|
private Button _btnSave, _btnCancel;
|
||||||
private readonly UserSettings _settings;
|
private readonly UserSettings _settings;
|
||||||
|
|
||||||
@@ -47,38 +49,84 @@ namespace StarfaceOutlookSync.UI
|
|||||||
Checked = _settings.AutoAcceptOutlookPrompt
|
Checked = _settings.AutoAcceptOutlookPrompt
|
||||||
};
|
};
|
||||||
|
|
||||||
|
var hintText = "Hinweis: Outlook muss nach Aenderung neu gestartet werden.";
|
||||||
|
if (UserSettings.IsOutlookSecurityLockedByPolicy())
|
||||||
|
hintText += "\nAuf Domaenen-PCs: App einmalig als Admin starten!";
|
||||||
|
|
||||||
var lblHint = new Label
|
var lblHint = new Label
|
||||||
{
|
{
|
||||||
Text = "Hinweis: Outlook muss nach Aenderung dieser Option\nneu gestartet werden.",
|
Text = hintText,
|
||||||
Left = 38, Top = 102, Width = 300, Height = 32,
|
Left = 38, Top = 102, Width = 320, Height = 36,
|
||||||
ForeColor = Color.Gray,
|
ForeColor = UserSettings.IsOutlookSecurityLockedByPolicy() ? Color.OrangeRed : Color.Gray,
|
||||||
Font = new Font("Segoe UI", 8)
|
Font = new Font("Segoe UI", 8)
|
||||||
};
|
};
|
||||||
|
|
||||||
|
var lblShared = new Label
|
||||||
|
{
|
||||||
|
Text = "Gemeinsames Verzeichnis fuer Sync-Sperre (Mehrplatz, optional):",
|
||||||
|
Left = 20, Top = 150, AutoSize = true
|
||||||
|
};
|
||||||
|
|
||||||
|
_txtSharedDir = new TextBox
|
||||||
|
{
|
||||||
|
Left = 20, Top = 172, Width = 250,
|
||||||
|
Text = _settings.SharedDirectory
|
||||||
|
};
|
||||||
|
|
||||||
|
_btnBrowseShared = new Button
|
||||||
|
{
|
||||||
|
Text = "...", Left = 274, Top = 171, Width = 36, Height = 24
|
||||||
|
};
|
||||||
|
_btnBrowseShared.Click += (s, e) => BrowseSharedDir();
|
||||||
|
|
||||||
|
var lblSharedHint = new Label
|
||||||
|
{
|
||||||
|
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,
|
||||||
|
ForeColor = Color.Gray, Font = new Font("Segoe UI", 8)
|
||||||
|
};
|
||||||
|
|
||||||
_btnSave = new Button
|
_btnSave = new Button
|
||||||
{
|
{
|
||||||
Text = "Speichern", Left = 95, Top = 170, Width = 85, Height = 28,
|
Text = "Speichern", Left = 95, Top = 240, Width = 85, Height = 28,
|
||||||
DialogResult = DialogResult.None
|
DialogResult = DialogResult.None
|
||||||
};
|
};
|
||||||
_btnSave.Click += (s, e) => Save();
|
_btnSave.Click += (s, e) => Save();
|
||||||
|
|
||||||
_btnCancel = new Button
|
_btnCancel = new Button
|
||||||
{
|
{
|
||||||
Text = "Abbrechen", Left = 189, Top = 170, Width = 85, Height = 28,
|
Text = "Abbrechen", Left = 189, Top = 240, Width = 85, Height = 28,
|
||||||
DialogResult = DialogResult.Cancel
|
DialogResult = DialogResult.Cancel
|
||||||
};
|
};
|
||||||
|
|
||||||
Size = new Size(380, 260);
|
Size = new Size(380, 330);
|
||||||
Controls.AddRange(new Control[] { _chkStartMinimized, _chkSyncOnStart, _chkAutoAcceptOutlook, lblHint, _btnSave, _btnCancel });
|
Controls.AddRange(new Control[] { _chkStartMinimized, _chkSyncOnStart, _chkAutoAcceptOutlook, lblHint,
|
||||||
|
lblShared, _txtSharedDir, _btnBrowseShared, lblSharedHint, _btnSave, _btnCancel });
|
||||||
AcceptButton = _btnSave;
|
AcceptButton = _btnSave;
|
||||||
CancelButton = _btnCancel;
|
CancelButton = _btnCancel;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void BrowseSharedDir()
|
||||||
|
{
|
||||||
|
using (var dlg = new FolderBrowserDialog())
|
||||||
|
{
|
||||||
|
dlg.Description = "Gemeinsames Verzeichnis fuer die Sync-Sperre waehlen";
|
||||||
|
if (!string.IsNullOrWhiteSpace(_txtSharedDir.Text))
|
||||||
|
{
|
||||||
|
try { dlg.SelectedPath = _txtSharedDir.Text; } catch { }
|
||||||
|
}
|
||||||
|
if (dlg.ShowDialog(this) == DialogResult.OK)
|
||||||
|
_txtSharedDir.Text = dlg.SelectedPath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void Save()
|
private void Save()
|
||||||
{
|
{
|
||||||
_settings.StartMinimized = _chkStartMinimized.Checked;
|
_settings.StartMinimized = _chkStartMinimized.Checked;
|
||||||
_settings.SyncOnStart = _chkSyncOnStart.Checked;
|
_settings.SyncOnStart = _chkSyncOnStart.Checked;
|
||||||
_settings.AutoAcceptOutlookPrompt = _chkAutoAcceptOutlook.Checked;
|
_settings.AutoAcceptOutlookPrompt = _chkAutoAcceptOutlook.Checked;
|
||||||
|
_settings.SharedDirectory = _txtSharedDir.Text.Trim();
|
||||||
_settings.Save();
|
_settings.Save();
|
||||||
DialogResult = DialogResult.OK;
|
DialogResult = DialogResult.OK;
|
||||||
Close();
|
Close();
|
||||||
|
|||||||
Reference in New Issue
Block a user