Rewrite as standalone C# WinForms app
Replace the Office Web Add-in with a native Windows application. The web add-in required Exchange/M365 for registration which is not available in all customer environments (standalone Office, POP/IMAP only). The new app: - Uses COM Interop to access Outlook contacts directly - Communicates with Starface REST API (accepts self-signed certs) - Runs as System Tray app with optional auto-sync - Profile-based config stored in %AppData% - No webserver, no certificates, no Exchange, no M365 needed - Inno Setup installer for clean MSI-style deployment - Works with any Outlook version (Classic and New) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
namespace StarfaceOutlookSync.Models
|
||||
{
|
||||
public enum SyncDirection
|
||||
{
|
||||
Both,
|
||||
OutlookToStarface,
|
||||
StarfaceToOutlook
|
||||
}
|
||||
|
||||
public class StarfaceConnection
|
||||
{
|
||||
public string Host { get; set; } = "";
|
||||
public int Port { get; set; } = 443;
|
||||
public bool UseSsl { get; set; } = true;
|
||||
public string LoginId { get; set; } = "";
|
||||
public string Password { get; set; } = "";
|
||||
}
|
||||
|
||||
public class StarfaceAddressBook
|
||||
{
|
||||
public string Type { get; set; } = "central"; // central, user, tag
|
||||
public string UserId { get; set; } = "";
|
||||
public string TagId { get; set; } = "";
|
||||
public string Name { get; set; } = "";
|
||||
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
public class SyncProfile
|
||||
{
|
||||
public string Id { get; set; } = "";
|
||||
public string Name { get; set; } = "";
|
||||
public StarfaceConnection StarfaceConnection { get; set; } = new StarfaceConnection();
|
||||
public StarfaceAddressBook StarfaceAddressBook { get; set; } = new StarfaceAddressBook();
|
||||
public string OutlookFolderPath { get; set; } = "";
|
||||
public string OutlookFolderName { get; set; } = "Kontakte";
|
||||
public SyncDirection SyncDirection { get; set; } = SyncDirection.Both;
|
||||
public string LastSync { get; set; } = "";
|
||||
public bool Enabled { get; set; } = true;
|
||||
public int AutoSyncIntervalMinutes { get; set; } = 0; // 0 = manuell
|
||||
}
|
||||
|
||||
public class SyncMapping
|
||||
{
|
||||
public string ProfileId { get; set; } = "";
|
||||
public string OutlookEntryId { get; set; } = "";
|
||||
public string StarfaceId { get; set; } = "";
|
||||
public string LastSyncHash { get; set; } = "";
|
||||
}
|
||||
|
||||
public class SyncResult
|
||||
{
|
||||
public string ProfileName { get; set; } = "";
|
||||
public string Timestamp { get; set; } = "";
|
||||
public int Created { get; set; }
|
||||
public int Updated { get; set; }
|
||||
public int Errors { get; set; }
|
||||
public System.Collections.Generic.List<string> ErrorMessages { get; set; } = new System.Collections.Generic.List<string>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
namespace StarfaceOutlookSync.Models
|
||||
{
|
||||
public class UnifiedContact
|
||||
{
|
||||
public string OutlookEntryId { get; set; } = "";
|
||||
public string StarfaceId { get; set; } = "";
|
||||
public string FirstName { get; set; } = "";
|
||||
public string LastName { get; set; } = "";
|
||||
public string Company { get; set; } = "";
|
||||
public string JobTitle { get; set; } = "";
|
||||
public string Email { get; set; } = "";
|
||||
public string EmailSecondary { get; set; } = "";
|
||||
public string PhoneWork { get; set; } = "";
|
||||
public string PhoneMobile { get; set; } = "";
|
||||
public string PhoneHome { get; set; } = "";
|
||||
public string Fax { get; set; } = "";
|
||||
public string Street { get; set; } = "";
|
||||
public string City { get; set; } = "";
|
||||
public string PostalCode { get; set; } = "";
|
||||
public string State { get; set; } = "";
|
||||
public string Country { get; set; } = "";
|
||||
public string Website { get; set; } = "";
|
||||
public string Notes { get; set; } = "";
|
||||
public string Salutation { get; set; } = "";
|
||||
public string Title { get; set; } = "";
|
||||
public string Birthday { get; set; } = "";
|
||||
|
||||
public string DisplayName => string.IsNullOrEmpty(LastName)
|
||||
? (string.IsNullOrEmpty(Company) ? Email : Company)
|
||||
: $"{FirstName} {LastName}".Trim();
|
||||
|
||||
public string GetHash()
|
||||
{
|
||||
var fields = new[]
|
||||
{
|
||||
FirstName, LastName, Company, JobTitle,
|
||||
Email, EmailSecondary,
|
||||
PhoneWork, PhoneMobile, PhoneHome, Fax,
|
||||
Street, City, PostalCode, State, Country,
|
||||
Website, Notes, Salutation, Title, Birthday
|
||||
};
|
||||
return string.Join("|", fields);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace StarfaceOutlookSync
|
||||
{
|
||||
static class Program
|
||||
{
|
||||
private static Mutex _mutex;
|
||||
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
// Nur eine Instanz erlauben
|
||||
const string mutexName = "StarfaceOutlookSync_SingleInstance";
|
||||
_mutex = new Mutex(true, mutexName, out bool createdNew);
|
||||
|
||||
if (!createdNew)
|
||||
{
|
||||
MessageBox.Show(
|
||||
"Starface Outlook Sync laeuft bereits.",
|
||||
"Starface Outlook Sync",
|
||||
MessageBoxButtons.OK,
|
||||
MessageBoxIcon.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
Application.EnableVisualStyles();
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
Application.Run(new UI.MainForm());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using StarfaceOutlookSync.Models;
|
||||
using Outlook = Microsoft.Office.Interop.Outlook;
|
||||
|
||||
namespace StarfaceOutlookSync.Services
|
||||
{
|
||||
public class OutlookContactsService : IDisposable
|
||||
{
|
||||
private Outlook.Application _outlookApp;
|
||||
private bool _weStartedOutlook;
|
||||
|
||||
private Outlook.Application GetOutlookApp()
|
||||
{
|
||||
if (_outlookApp != null) return _outlookApp;
|
||||
|
||||
try
|
||||
{
|
||||
// Versuche laufende Outlook-Instanz zu finden
|
||||
_outlookApp = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
|
||||
_weStartedOutlook = false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Outlook starten falls nicht laufend
|
||||
_outlookApp = new Outlook.Application();
|
||||
_weStartedOutlook = true;
|
||||
}
|
||||
|
||||
return _outlookApp;
|
||||
}
|
||||
|
||||
public List<string> GetContactFolderPaths()
|
||||
{
|
||||
var folders = new List<string>();
|
||||
try
|
||||
{
|
||||
var app = GetOutlookApp();
|
||||
var ns = app.GetNamespace("MAPI");
|
||||
|
||||
// Standard-Kontaktordner
|
||||
var defaultFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
|
||||
folders.Add(defaultFolder.FolderPath);
|
||||
|
||||
// Unterordner
|
||||
AddSubFolders(defaultFolder, folders);
|
||||
|
||||
// Weitere Kontaktordner in anderen Stores
|
||||
foreach (Outlook.Store store in ns.Stores)
|
||||
{
|
||||
try
|
||||
{
|
||||
var rootFolder = store.GetRootFolder();
|
||||
FindContactFolders(rootFolder, folders);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
Marshal.ReleaseComObject(ns);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"Error getting folders: {ex.Message}");
|
||||
}
|
||||
|
||||
return folders;
|
||||
}
|
||||
|
||||
private void AddSubFolders(Outlook.MAPIFolder folder, List<string> paths)
|
||||
{
|
||||
foreach (Outlook.MAPIFolder sub in folder.Folders)
|
||||
{
|
||||
if (sub.DefaultItemType == Outlook.OlItemType.olContactItem)
|
||||
{
|
||||
if (!paths.Contains(sub.FolderPath))
|
||||
paths.Add(sub.FolderPath);
|
||||
AddSubFolders(sub, paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void FindContactFolders(Outlook.MAPIFolder folder, List<string> paths)
|
||||
{
|
||||
if (folder.DefaultItemType == Outlook.OlItemType.olContactItem)
|
||||
{
|
||||
if (!paths.Contains(folder.FolderPath))
|
||||
paths.Add(folder.FolderPath);
|
||||
}
|
||||
|
||||
foreach (Outlook.MAPIFolder sub in folder.Folders)
|
||||
{
|
||||
FindContactFolders(sub, paths);
|
||||
}
|
||||
}
|
||||
|
||||
private Outlook.MAPIFolder GetFolderByPath(string folderPath)
|
||||
{
|
||||
var app = GetOutlookApp();
|
||||
var ns = app.GetNamespace("MAPI");
|
||||
|
||||
// Standard-Kontaktordner als Fallback
|
||||
if (string.IsNullOrEmpty(folderPath))
|
||||
return ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
|
||||
|
||||
try
|
||||
{
|
||||
// Pfad durchlaufen
|
||||
var parts = folderPath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
Outlook.MAPIFolder current = null;
|
||||
|
||||
foreach (Outlook.Store store in ns.Stores)
|
||||
{
|
||||
if (store.GetRootFolder().Name == parts[0] ||
|
||||
store.GetRootFolder().FolderPath.TrimStart('\\') == parts[0])
|
||||
{
|
||||
current = store.GetRootFolder();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (current == null)
|
||||
return ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
|
||||
|
||||
for (int i = 1; i < parts.Length; i++)
|
||||
{
|
||||
bool found = false;
|
||||
foreach (Outlook.MAPIFolder sub in current.Folders)
|
||||
{
|
||||
if (sub.Name == parts[i])
|
||||
{
|
||||
current = sub;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found)
|
||||
return ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
|
||||
}
|
||||
}
|
||||
|
||||
public List<UnifiedContact> GetContacts(string folderPath)
|
||||
{
|
||||
var contacts = new List<UnifiedContact>();
|
||||
|
||||
try
|
||||
{
|
||||
var folder = GetFolderByPath(folderPath);
|
||||
var items = folder.Items;
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (item is Outlook.ContactItem ci)
|
||||
{
|
||||
contacts.Add(MapFromOutlook(ci));
|
||||
Marshal.ReleaseComObject(ci);
|
||||
}
|
||||
}
|
||||
|
||||
Marshal.ReleaseComObject(items);
|
||||
Marshal.ReleaseComObject(folder);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"Error reading contacts: {ex.Message}");
|
||||
}
|
||||
|
||||
return contacts;
|
||||
}
|
||||
|
||||
public UnifiedContact CreateContact(UnifiedContact contact, string folderPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
var folder = GetFolderByPath(folderPath);
|
||||
var ci = (Outlook.ContactItem)folder.Items.Add(Outlook.OlItemType.olContactItem);
|
||||
|
||||
MapToOutlook(contact, ci);
|
||||
ci.Save();
|
||||
|
||||
contact.OutlookEntryId = ci.EntryID;
|
||||
|
||||
Marshal.ReleaseComObject(ci);
|
||||
Marshal.ReleaseComObject(folder);
|
||||
|
||||
return contact;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"Error creating contact: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public bool UpdateContact(string entryId, UnifiedContact contact)
|
||||
{
|
||||
try
|
||||
{
|
||||
var app = GetOutlookApp();
|
||||
var ns = app.GetNamespace("MAPI");
|
||||
var ci = (Outlook.ContactItem)ns.GetItemFromID(entryId);
|
||||
|
||||
MapToOutlook(contact, ci);
|
||||
ci.Save();
|
||||
|
||||
Marshal.ReleaseComObject(ci);
|
||||
Marshal.ReleaseComObject(ns);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"Error updating contact: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool DeleteContact(string entryId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var app = GetOutlookApp();
|
||||
var ns = app.GetNamespace("MAPI");
|
||||
var ci = (Outlook.ContactItem)ns.GetItemFromID(entryId);
|
||||
|
||||
ci.Delete();
|
||||
Marshal.ReleaseComObject(ci);
|
||||
Marshal.ReleaseComObject(ns);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"Error deleting contact: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private UnifiedContact MapFromOutlook(Outlook.ContactItem ci)
|
||||
{
|
||||
return new UnifiedContact
|
||||
{
|
||||
OutlookEntryId = ci.EntryID ?? "",
|
||||
FirstName = ci.FirstName ?? "",
|
||||
LastName = ci.LastName ?? "",
|
||||
Company = ci.CompanyName ?? "",
|
||||
JobTitle = ci.JobTitle ?? "",
|
||||
Email = ci.Email1Address ?? "",
|
||||
EmailSecondary = ci.Email2Address ?? "",
|
||||
PhoneWork = ci.BusinessTelephoneNumber ?? "",
|
||||
PhoneMobile = ci.MobileTelephoneNumber ?? "",
|
||||
PhoneHome = ci.HomeTelephoneNumber ?? "",
|
||||
Fax = ci.BusinessFaxNumber ?? "",
|
||||
Street = ci.BusinessAddressStreet ?? "",
|
||||
City = ci.BusinessAddressCity ?? "",
|
||||
PostalCode = ci.BusinessAddressPostalCode ?? "",
|
||||
State = ci.BusinessAddressState ?? "",
|
||||
Country = ci.BusinessAddressCountry ?? "",
|
||||
Website = ci.WebPage ?? "",
|
||||
Notes = ci.Body ?? "",
|
||||
Salutation = ci.Title ?? "",
|
||||
Title = ci.Suffix ?? "",
|
||||
Birthday = ci.Birthday != DateTime.MinValue && ci.Birthday.Year > 1900
|
||||
? ci.Birthday.ToString("yyyy-MM-dd") : ""
|
||||
};
|
||||
}
|
||||
|
||||
private void MapToOutlook(UnifiedContact contact, Outlook.ContactItem ci)
|
||||
{
|
||||
ci.FirstName = contact.FirstName;
|
||||
ci.LastName = contact.LastName;
|
||||
ci.CompanyName = contact.Company;
|
||||
ci.JobTitle = contact.JobTitle;
|
||||
ci.Email1Address = contact.Email;
|
||||
if (!string.IsNullOrEmpty(contact.EmailSecondary))
|
||||
ci.Email2Address = contact.EmailSecondary;
|
||||
ci.BusinessTelephoneNumber = contact.PhoneWork;
|
||||
ci.MobileTelephoneNumber = contact.PhoneMobile;
|
||||
ci.HomeTelephoneNumber = contact.PhoneHome;
|
||||
ci.BusinessFaxNumber = contact.Fax;
|
||||
ci.BusinessAddressStreet = contact.Street;
|
||||
ci.BusinessAddressCity = contact.City;
|
||||
ci.BusinessAddressPostalCode = contact.PostalCode;
|
||||
ci.BusinessAddressState = contact.State;
|
||||
ci.BusinessAddressCountry = contact.Country;
|
||||
ci.WebPage = contact.Website;
|
||||
ci.Body = contact.Notes;
|
||||
ci.Title = contact.Salutation;
|
||||
|
||||
if (!string.IsNullOrEmpty(contact.Birthday) &&
|
||||
DateTime.TryParse(contact.Birthday, out var bday) && bday.Year > 1900)
|
||||
{
|
||||
ci.Birthday = bday;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_outlookApp != null)
|
||||
{
|
||||
if (_weStartedOutlook)
|
||||
{
|
||||
try { _outlookApp.Quit(); } catch { }
|
||||
}
|
||||
Marshal.ReleaseComObject(_outlookApp);
|
||||
_outlookApp = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using StarfaceOutlookSync.Models;
|
||||
|
||||
namespace StarfaceOutlookSync.Services
|
||||
{
|
||||
public class ProfileManager
|
||||
{
|
||||
private readonly string _dataDir;
|
||||
private readonly string _profilesFile;
|
||||
private readonly string _mappingsDir;
|
||||
|
||||
public ProfileManager()
|
||||
{
|
||||
_dataDir = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"StarfaceOutlookSync");
|
||||
_mappingsDir = Path.Combine(_dataDir, "mappings");
|
||||
_profilesFile = Path.Combine(_dataDir, "profiles.json");
|
||||
|
||||
Directory.CreateDirectory(_dataDir);
|
||||
Directory.CreateDirectory(_mappingsDir);
|
||||
}
|
||||
|
||||
public List<SyncProfile> GetProfiles()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(_profilesFile)) return new List<SyncProfile>();
|
||||
var json = File.ReadAllText(_profilesFile);
|
||||
return JsonConvert.DeserializeObject<List<SyncProfile>>(json) ?? new List<SyncProfile>();
|
||||
}
|
||||
catch { return new List<SyncProfile>(); }
|
||||
}
|
||||
|
||||
public void SaveProfiles(List<SyncProfile> profiles)
|
||||
{
|
||||
var json = JsonConvert.SerializeObject(profiles, Formatting.Indented);
|
||||
File.WriteAllText(_profilesFile, json);
|
||||
}
|
||||
|
||||
public SyncProfile GetProfile(string id)
|
||||
{
|
||||
return GetProfiles().FirstOrDefault(p => p.Id == id);
|
||||
}
|
||||
|
||||
public void AddProfile(SyncProfile profile)
|
||||
{
|
||||
var profiles = GetProfiles();
|
||||
profiles.Add(profile);
|
||||
SaveProfiles(profiles);
|
||||
}
|
||||
|
||||
public void UpdateProfile(SyncProfile profile)
|
||||
{
|
||||
var profiles = GetProfiles();
|
||||
var idx = profiles.FindIndex(p => p.Id == profile.Id);
|
||||
if (idx >= 0)
|
||||
{
|
||||
profiles[idx] = profile;
|
||||
SaveProfiles(profiles);
|
||||
}
|
||||
}
|
||||
|
||||
public void DeleteProfile(string id)
|
||||
{
|
||||
var profiles = GetProfiles().Where(p => p.Id != id).ToList();
|
||||
SaveProfiles(profiles);
|
||||
var mappingFile = Path.Combine(_mappingsDir, $"{id}.json");
|
||||
if (File.Exists(mappingFile)) File.Delete(mappingFile);
|
||||
}
|
||||
|
||||
public void UpdateLastSync(string profileId)
|
||||
{
|
||||
var profiles = GetProfiles();
|
||||
var profile = profiles.FirstOrDefault(p => p.Id == profileId);
|
||||
if (profile != null)
|
||||
{
|
||||
profile.LastSync = DateTime.Now.ToString("o");
|
||||
SaveProfiles(profiles);
|
||||
}
|
||||
}
|
||||
|
||||
public List<SyncMapping> GetMappings(string profileId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var file = Path.Combine(_mappingsDir, $"{profileId}.json");
|
||||
if (!File.Exists(file)) return new List<SyncMapping>();
|
||||
return JsonConvert.DeserializeObject<List<SyncMapping>>(File.ReadAllText(file))
|
||||
?? new List<SyncMapping>();
|
||||
}
|
||||
catch { return new List<SyncMapping>(); }
|
||||
}
|
||||
|
||||
public void SaveMappings(string profileId, List<SyncMapping> mappings)
|
||||
{
|
||||
var file = Path.Combine(_mappingsDir, $"{profileId}.json");
|
||||
File.WriteAllText(file, JsonConvert.SerializeObject(mappings, Formatting.Indented));
|
||||
}
|
||||
|
||||
public void AddOrUpdateMapping(SyncMapping mapping)
|
||||
{
|
||||
var mappings = GetMappings(mapping.ProfileId);
|
||||
var existing = mappings.FindIndex(m =>
|
||||
m.OutlookEntryId == mapping.OutlookEntryId || m.StarfaceId == mapping.StarfaceId);
|
||||
if (existing >= 0)
|
||||
mappings[existing] = mapping;
|
||||
else
|
||||
mappings.Add(mapping);
|
||||
SaveMappings(mapping.ProfileId, mappings);
|
||||
}
|
||||
|
||||
public string GenerateId()
|
||||
{
|
||||
return DateTime.Now.Ticks.ToString("x") + Guid.NewGuid().ToString("N").Substring(0, 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using StarfaceOutlookSync.Models;
|
||||
|
||||
namespace StarfaceOutlookSync.Services
|
||||
{
|
||||
public class StarfaceApiClient : IDisposable
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
private readonly StarfaceConnection _connection;
|
||||
private readonly string _baseUrl;
|
||||
private string _token;
|
||||
|
||||
public StarfaceApiClient(StarfaceConnection connection)
|
||||
{
|
||||
_connection = connection;
|
||||
|
||||
var handler = new HttpClientHandler();
|
||||
// Self-signed Zertifikate der Starface akzeptieren
|
||||
handler.ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) => true;
|
||||
|
||||
_http = new HttpClient(handler);
|
||||
_http.DefaultRequestHeaders.Add("X-Version", "2");
|
||||
_http.Timeout = TimeSpan.FromSeconds(30);
|
||||
|
||||
var protocol = connection.UseSsl ? "https" : "http";
|
||||
var portPart = (connection.UseSsl && connection.Port == 443) ||
|
||||
(!connection.UseSsl && connection.Port == 80)
|
||||
? "" : $":{connection.Port}";
|
||||
_baseUrl = $"{protocol}://{connection.Host}{portPart}/rest";
|
||||
}
|
||||
|
||||
private static string Sha512(string input)
|
||||
{
|
||||
using (var sha = SHA512.Create())
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(input);
|
||||
var hash = sha.ComputeHash(bytes);
|
||||
var sb = new StringBuilder(128);
|
||||
foreach (var b in hash)
|
||||
sb.Append(b.ToString("x2"));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> LoginAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Schritt 1: Nonce holen
|
||||
var nonceResp = await _http.GetAsync($"{_baseUrl}/login");
|
||||
if (!nonceResp.IsSuccessStatusCode) return false;
|
||||
|
||||
var nonceJson = JObject.Parse(await nonceResp.Content.ReadAsStringAsync());
|
||||
var loginType = nonceJson["loginType"]?.ToString() ?? "Internal";
|
||||
var nonce = nonceJson["nonce"]?.ToString() ?? "";
|
||||
|
||||
// Schritt 2: Secret berechnen
|
||||
var passwordHash = Sha512(_connection.Password);
|
||||
var combined = _connection.LoginId + nonce + passwordHash;
|
||||
var combinedHash = Sha512(combined);
|
||||
var secret = $"{_connection.LoginId}:{combinedHash}";
|
||||
|
||||
// Schritt 3: Login
|
||||
var loginBody = new { loginType, nonce, secret };
|
||||
var content = new StringContent(JsonConvert.SerializeObject(loginBody), Encoding.UTF8, "application/json");
|
||||
var loginResp = await _http.PostAsync($"{_baseUrl}/login", content);
|
||||
if (!loginResp.IsSuccessStatusCode) return false;
|
||||
|
||||
var tokenJson = JObject.Parse(await loginResp.Content.ReadAsStringAsync());
|
||||
_token = tokenJson["token"]?.ToString();
|
||||
|
||||
if (!string.IsNullOrEmpty(_token))
|
||||
{
|
||||
_http.DefaultRequestHeaders.Remove("authToken");
|
||||
_http.DefaultRequestHeaders.Add("authToken", _token);
|
||||
}
|
||||
|
||||
return !string.IsNullOrEmpty(_token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"Starface login failed: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task LogoutAsync()
|
||||
{
|
||||
if (string.IsNullOrEmpty(_token)) return;
|
||||
try { await _http.DeleteAsync($"{_baseUrl}/login"); } catch { }
|
||||
_token = null;
|
||||
}
|
||||
|
||||
public async Task<string> GetCurrentUserIdAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var resp = await _http.GetAsync($"{_baseUrl}/users/me");
|
||||
if (!resp.IsSuccessStatusCode) return null;
|
||||
var json = JObject.Parse(await resp.Content.ReadAsStringAsync());
|
||||
return json["id"]?.ToString();
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
public async Task<List<StarfaceAddressBook>> GetAddressBooksAsync()
|
||||
{
|
||||
var books = new List<StarfaceAddressBook>();
|
||||
|
||||
books.Add(new StarfaceAddressBook
|
||||
{
|
||||
Type = "central",
|
||||
Name = "Zentrales Adressbuch"
|
||||
});
|
||||
|
||||
var userId = await GetCurrentUserIdAsync();
|
||||
if (!string.IsNullOrEmpty(userId))
|
||||
{
|
||||
books.Add(new StarfaceAddressBook
|
||||
{
|
||||
Type = "user",
|
||||
UserId = userId,
|
||||
Name = "Persoenliches Adressbuch"
|
||||
});
|
||||
}
|
||||
|
||||
// Tags als virtuelle Adressbuecher
|
||||
try
|
||||
{
|
||||
var resp = await _http.GetAsync($"{_baseUrl}/contacts/tags");
|
||||
if (resp.IsSuccessStatusCode)
|
||||
{
|
||||
var tags = JArray.Parse(await resp.Content.ReadAsStringAsync());
|
||||
foreach (var tag in tags)
|
||||
{
|
||||
books.Add(new StarfaceAddressBook
|
||||
{
|
||||
Type = "tag",
|
||||
TagId = tag["id"]?.ToString() ?? "",
|
||||
Name = $"Tag: {tag["name"]}"
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
return books;
|
||||
}
|
||||
|
||||
public async Task<List<UnifiedContact>> GetContactsAsync(StarfaceAddressBook book)
|
||||
{
|
||||
var contacts = new List<UnifiedContact>();
|
||||
int page = 0;
|
||||
const int pageSize = 200;
|
||||
|
||||
while (true)
|
||||
{
|
||||
var query = $"page={page}&pagesize={pageSize}";
|
||||
if (book.Type == "user" && !string.IsNullOrEmpty(book.UserId))
|
||||
query += $"&userId={book.UserId}";
|
||||
if (book.Type == "tag" && !string.IsNullOrEmpty(book.TagId))
|
||||
query += $"&tags={book.TagId}";
|
||||
|
||||
var resp = await _http.GetAsync($"{_baseUrl}/contacts?{query}");
|
||||
if (!resp.IsSuccessStatusCode) break;
|
||||
|
||||
var array = JArray.Parse(await resp.Content.ReadAsStringAsync());
|
||||
if (array.Count == 0) break;
|
||||
|
||||
foreach (var item in array)
|
||||
contacts.Add(MapFromStarface(item));
|
||||
|
||||
if (array.Count < pageSize) break;
|
||||
page++;
|
||||
}
|
||||
|
||||
return contacts;
|
||||
}
|
||||
|
||||
public async Task<UnifiedContact> CreateContactAsync(UnifiedContact contact, StarfaceAddressBook book)
|
||||
{
|
||||
var sfContact = MapToStarface(contact);
|
||||
var query = "";
|
||||
if (book.Type == "user" && !string.IsNullOrEmpty(book.UserId))
|
||||
query = $"?userId={book.UserId}";
|
||||
|
||||
var content = new StringContent(sfContact.ToString(), Encoding.UTF8, "application/json");
|
||||
var resp = await _http.PostAsync($"{_baseUrl}/contacts{query}", content);
|
||||
if (!resp.IsSuccessStatusCode) return null;
|
||||
|
||||
var created = JObject.Parse(await resp.Content.ReadAsStringAsync());
|
||||
return MapFromStarface(created);
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateContactAsync(string contactId, UnifiedContact contact, StarfaceAddressBook book)
|
||||
{
|
||||
var sfContact = MapToStarface(contact);
|
||||
sfContact["id"] = contactId;
|
||||
var query = "";
|
||||
if (book.Type == "user" && !string.IsNullOrEmpty(book.UserId))
|
||||
query = $"?userId={book.UserId}";
|
||||
|
||||
var content = new StringContent(sfContact.ToString(), Encoding.UTF8, "application/json");
|
||||
var resp = await _http.PutAsync($"{_baseUrl}/contacts/{contactId}{query}", content);
|
||||
return resp.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteContactAsync(string contactId)
|
||||
{
|
||||
var resp = await _http.DeleteAsync($"{_baseUrl}/contacts/{contactId}");
|
||||
return resp.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
private UnifiedContact MapFromStarface(JToken item)
|
||||
{
|
||||
var contact = new UnifiedContact();
|
||||
contact.StarfaceId = item["id"]?.ToString() ?? "";
|
||||
|
||||
var attrs = new Dictionary<string, string>();
|
||||
var blocks = item["blocks"] as JArray;
|
||||
if (blocks != null)
|
||||
{
|
||||
foreach (var block in blocks)
|
||||
{
|
||||
var blockAttrs = block["attributes"] as JArray;
|
||||
if (blockAttrs == null) continue;
|
||||
foreach (var attr in blockAttrs)
|
||||
{
|
||||
var key = attr["displayKey"]?.ToString() ?? "";
|
||||
var val = attr["value"]?.ToString() ?? "";
|
||||
if (!string.IsNullOrEmpty(val))
|
||||
attrs[key] = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
contact.FirstName = attrs.GetValueOrDefault("NAME", "");
|
||||
contact.LastName = attrs.GetValueOrDefault("SURNAME", "");
|
||||
contact.Company = attrs.GetValueOrDefault("COMPANY", "");
|
||||
contact.JobTitle = attrs.GetValueOrDefault("JOB_TITLE", "");
|
||||
contact.Email = attrs.GetValueOrDefault("EMAIL", "");
|
||||
contact.PhoneWork = attrs.GetValueOrDefault("OFFICE_PHONE_NUMBER", "");
|
||||
contact.PhoneMobile = attrs.GetValueOrDefault("MOBILE_PHONE_NUMBER", "");
|
||||
contact.PhoneHome = attrs.GetValueOrDefault("PRIVATE_PHONE_NUMBER", "");
|
||||
contact.Fax = attrs.GetValueOrDefault("FAX_NUMBER", "");
|
||||
contact.Street = attrs.GetValueOrDefault("STREET", "");
|
||||
contact.City = attrs.GetValueOrDefault("CITY", "");
|
||||
contact.PostalCode = attrs.GetValueOrDefault("POSTAL_CODE", "");
|
||||
contact.State = attrs.GetValueOrDefault("STATE", "");
|
||||
contact.Country = attrs.GetValueOrDefault("COUNTRY", "");
|
||||
contact.Website = attrs.GetValueOrDefault("URL", "");
|
||||
contact.Notes = attrs.GetValueOrDefault("NOTE", "");
|
||||
contact.Salutation = attrs.GetValueOrDefault("SALUTATION", "");
|
||||
contact.Title = attrs.GetValueOrDefault("TITLE", "");
|
||||
contact.Birthday = attrs.GetValueOrDefault("BIRTHDAY", "");
|
||||
|
||||
return contact;
|
||||
}
|
||||
|
||||
private JObject MapToStarface(UnifiedContact contact)
|
||||
{
|
||||
var attrs = new JArray();
|
||||
|
||||
void AddAttr(string displayKey, string name, string value)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
attrs.Add(new JObject { ["displayKey"] = displayKey, ["name"] = name, ["value"] = value });
|
||||
}
|
||||
|
||||
AddAttr("NAME", "firstName", contact.FirstName);
|
||||
AddAttr("SURNAME", "lastName", contact.LastName);
|
||||
AddAttr("COMPANY", "company", contact.Company);
|
||||
AddAttr("JOB_TITLE", "jobTitle", contact.JobTitle);
|
||||
AddAttr("EMAIL", "email", contact.Email);
|
||||
AddAttr("OFFICE_PHONE_NUMBER", "businessPhone", contact.PhoneWork);
|
||||
AddAttr("MOBILE_PHONE_NUMBER", "mobilePhone", contact.PhoneMobile);
|
||||
AddAttr("PRIVATE_PHONE_NUMBER", "homePhone", contact.PhoneHome);
|
||||
AddAttr("FAX_NUMBER", "fax", contact.Fax);
|
||||
AddAttr("STREET", "street", contact.Street);
|
||||
AddAttr("CITY", "city", contact.City);
|
||||
AddAttr("POSTAL_CODE", "postalCode", contact.PostalCode);
|
||||
AddAttr("STATE", "state", contact.State);
|
||||
AddAttr("COUNTRY", "country", contact.Country);
|
||||
AddAttr("URL", "website", contact.Website);
|
||||
AddAttr("NOTE", "notes", contact.Notes);
|
||||
AddAttr("SALUTATION", "salutation", contact.Salutation);
|
||||
AddAttr("TITLE", "title", contact.Title);
|
||||
AddAttr("BIRTHDAY", "birthday", contact.Birthday);
|
||||
|
||||
return new JObject
|
||||
{
|
||||
["id"] = contact.StarfaceId ?? "",
|
||||
["blocks"] = new JArray
|
||||
{
|
||||
new JObject
|
||||
{
|
||||
["name"] = "contact",
|
||||
["resourceKey"] = "contact",
|
||||
["attributes"] = attrs
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_http?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
internal static class DictionaryExtensions
|
||||
{
|
||||
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue)
|
||||
{
|
||||
return dict.TryGetValue(key, out var value) ? value : defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using StarfaceOutlookSync.Models;
|
||||
|
||||
namespace StarfaceOutlookSync.Services
|
||||
{
|
||||
public class SyncEngine
|
||||
{
|
||||
private readonly ProfileManager _profileManager = new ProfileManager();
|
||||
private readonly OutlookContactsService _outlookService = new OutlookContactsService();
|
||||
|
||||
public event Action<string> OnProgress;
|
||||
|
||||
private void Log(string message) => OnProgress?.Invoke(message);
|
||||
|
||||
private static UnifiedContact FindMatch(UnifiedContact contact, List<UnifiedContact> candidates)
|
||||
{
|
||||
// Erst E-Mail-Match
|
||||
if (!string.IsNullOrEmpty(contact.Email))
|
||||
{
|
||||
var byEmail = candidates.FirstOrDefault(c =>
|
||||
!string.IsNullOrEmpty(c.Email) &&
|
||||
c.Email.Equals(contact.Email, StringComparison.OrdinalIgnoreCase));
|
||||
if (byEmail != null) return byEmail;
|
||||
}
|
||||
|
||||
// Dann Name-Match
|
||||
if (!string.IsNullOrEmpty(contact.FirstName) || !string.IsNullOrEmpty(contact.LastName))
|
||||
{
|
||||
var byName = candidates.FirstOrDefault(c =>
|
||||
c.FirstName.Equals(contact.FirstName, StringComparison.OrdinalIgnoreCase) &&
|
||||
c.LastName.Equals(contact.LastName, StringComparison.OrdinalIgnoreCase) &&
|
||||
(!string.IsNullOrEmpty(c.FirstName) || !string.IsNullOrEmpty(c.LastName)));
|
||||
if (byName != null) return byName;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public async Task<SyncResult> SyncProfileAsync(SyncProfile profile)
|
||||
{
|
||||
var result = new SyncResult
|
||||
{
|
||||
ProfileName = profile.Name,
|
||||
Timestamp = DateTime.Now.ToString("o")
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
// Starface verbinden
|
||||
Log("Verbinde mit Starface...");
|
||||
using (var starface = new StarfaceApiClient(profile.StarfaceConnection))
|
||||
{
|
||||
var loginOk = await starface.LoginAsync();
|
||||
if (!loginOk)
|
||||
{
|
||||
result.ErrorMessages.Add("Starface-Login fehlgeschlagen");
|
||||
result.Errors++;
|
||||
return result;
|
||||
}
|
||||
|
||||
var mappings = _profileManager.GetMappings(profile.Id);
|
||||
var mappingByOutlook = mappings.ToDictionary(m => m.OutlookEntryId, m => m);
|
||||
var mappingByStarface = mappings.ToDictionary(m => m.StarfaceId, m => m);
|
||||
|
||||
// Kontakte laden
|
||||
Log("Lade Outlook-Kontakte...");
|
||||
var outlookContacts = _outlookService.GetContacts(profile.OutlookFolderPath);
|
||||
Log($"{outlookContacts.Count} Outlook-Kontakte geladen");
|
||||
|
||||
Log("Lade Starface-Kontakte...");
|
||||
var starfaceContacts = await starface.GetContactsAsync(profile.StarfaceAddressBook);
|
||||
Log($"{starfaceContacts.Count} Starface-Kontakte geladen");
|
||||
|
||||
// Outlook -> Starface
|
||||
if (profile.SyncDirection == SyncDirection.Both ||
|
||||
profile.SyncDirection == SyncDirection.OutlookToStarface)
|
||||
{
|
||||
Log("Synchronisiere Outlook -> Starface...");
|
||||
foreach (var oc in outlookContacts)
|
||||
{
|
||||
try
|
||||
{
|
||||
SyncMapping existing = null;
|
||||
if (!string.IsNullOrEmpty(oc.OutlookEntryId))
|
||||
mappingByOutlook.TryGetValue(oc.OutlookEntryId, out existing);
|
||||
|
||||
if (existing != null)
|
||||
{
|
||||
var hash = oc.GetHash();
|
||||
if (hash != existing.LastSyncHash)
|
||||
{
|
||||
if (await starface.UpdateContactAsync(existing.StarfaceId, oc, profile.StarfaceAddressBook))
|
||||
{
|
||||
existing.LastSyncHash = hash;
|
||||
result.Updated++;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var match = FindMatch(oc, starfaceContacts);
|
||||
if (match != null && !string.IsNullOrEmpty(match.StarfaceId))
|
||||
{
|
||||
if (await starface.UpdateContactAsync(match.StarfaceId, oc, profile.StarfaceAddressBook))
|
||||
{
|
||||
_profileManager.AddOrUpdateMapping(new SyncMapping
|
||||
{
|
||||
ProfileId = profile.Id,
|
||||
OutlookEntryId = oc.OutlookEntryId,
|
||||
StarfaceId = match.StarfaceId,
|
||||
LastSyncHash = oc.GetHash()
|
||||
});
|
||||
result.Updated++;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var created = await starface.CreateContactAsync(oc, profile.StarfaceAddressBook);
|
||||
if (created != null && !string.IsNullOrEmpty(created.StarfaceId))
|
||||
{
|
||||
_profileManager.AddOrUpdateMapping(new SyncMapping
|
||||
{
|
||||
ProfileId = profile.Id,
|
||||
OutlookEntryId = oc.OutlookEntryId,
|
||||
StarfaceId = created.StarfaceId,
|
||||
LastSyncHash = oc.GetHash()
|
||||
});
|
||||
result.Created++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
result.Errors++;
|
||||
result.ErrorMessages.Add($"{oc.DisplayName}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Starface -> Outlook
|
||||
if (profile.SyncDirection == SyncDirection.Both ||
|
||||
profile.SyncDirection == SyncDirection.StarfaceToOutlook)
|
||||
{
|
||||
Log("Synchronisiere Starface -> Outlook...");
|
||||
foreach (var sc in starfaceContacts)
|
||||
{
|
||||
try
|
||||
{
|
||||
SyncMapping existing = null;
|
||||
if (!string.IsNullOrEmpty(sc.StarfaceId))
|
||||
mappingByStarface.TryGetValue(sc.StarfaceId, out existing);
|
||||
|
||||
if (existing != null)
|
||||
{
|
||||
var hash = sc.GetHash();
|
||||
if (hash != existing.LastSyncHash)
|
||||
{
|
||||
if (_outlookService.UpdateContact(existing.OutlookEntryId, sc))
|
||||
{
|
||||
existing.LastSyncHash = hash;
|
||||
result.Updated++;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var match = FindMatch(sc, outlookContacts);
|
||||
if (match != null && !string.IsNullOrEmpty(match.OutlookEntryId))
|
||||
{
|
||||
if (_outlookService.UpdateContact(match.OutlookEntryId, sc))
|
||||
{
|
||||
_profileManager.AddOrUpdateMapping(new SyncMapping
|
||||
{
|
||||
ProfileId = profile.Id,
|
||||
OutlookEntryId = match.OutlookEntryId,
|
||||
StarfaceId = sc.StarfaceId,
|
||||
LastSyncHash = sc.GetHash()
|
||||
});
|
||||
result.Updated++;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var created = _outlookService.CreateContact(sc, profile.OutlookFolderPath);
|
||||
if (created != null && !string.IsNullOrEmpty(created.OutlookEntryId))
|
||||
{
|
||||
_profileManager.AddOrUpdateMapping(new SyncMapping
|
||||
{
|
||||
ProfileId = profile.Id,
|
||||
OutlookEntryId = created.OutlookEntryId,
|
||||
StarfaceId = sc.StarfaceId,
|
||||
LastSyncHash = sc.GetHash()
|
||||
});
|
||||
result.Created++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
result.Errors++;
|
||||
result.ErrorMessages.Add($"{sc.DisplayName}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_profileManager.UpdateLastSync(profile.Id);
|
||||
_profileManager.SaveMappings(profile.Id, mappings);
|
||||
await starface.LogoutAsync();
|
||||
Log("Synchronisation abgeschlossen!");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
result.Errors++;
|
||||
result.ErrorMessages.Add($"Allgemeiner Fehler: {ex.Message}");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net4.8</TargetFramework>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<ApplicationIcon>Resources\app.ico</ApplicationIcon>
|
||||
<AssemblyTitle>Starface Outlook Sync</AssemblyTitle>
|
||||
<Company>HackerSoft - Hacker-Net Telekommunikation</Company>
|
||||
<Product>Starface Outlook Sync</Product>
|
||||
<Version>0.0.0.1</Version>
|
||||
<AssemblyVersion>0.0.0.1</AssemblyVersion>
|
||||
<FileVersion>0.0.0.1</FileVersion>
|
||||
<Description>Synchronisiert Outlook-Kontakte mit Starface Telefonanlage</Description>
|
||||
<Copyright>Stefan Hacker - HackerSoft</Copyright>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.Office.Interop.Outlook">
|
||||
<HintPath>$(ProgramFiles)\Microsoft Office\root\Office16\ADDINS\Microsoft.Office.Interop.Outlook.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Resources\app.ico" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Drawing;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace StarfaceOutlookSync.UI
|
||||
{
|
||||
public class AboutForm : Form
|
||||
{
|
||||
public AboutForm()
|
||||
{
|
||||
Text = "Info";
|
||||
Size = new Size(360, 280);
|
||||
FormBorderStyle = FormBorderStyle.FixedDialog;
|
||||
MaximizeBox = false;
|
||||
MinimizeBox = false;
|
||||
StartPosition = FormStartPosition.CenterParent;
|
||||
Font = new Font("Segoe UI", 9);
|
||||
BackColor = Color.White;
|
||||
|
||||
var lblProduct = new Label
|
||||
{
|
||||
Text = "Outlook-SYNC \u2194 Starface",
|
||||
Left = 0, Top = 24, Width = 340, Height = 30,
|
||||
TextAlign = ContentAlignment.MiddleCenter,
|
||||
Font = new Font("Segoe UI", 14, FontStyle.Bold),
|
||||
ForeColor = Color.FromArgb(0, 120, 212)
|
||||
};
|
||||
|
||||
var lblVersion = new Label
|
||||
{
|
||||
Text = "Version 0.0.0.1",
|
||||
Left = 0, Top = 56, Width = 340, Height = 20,
|
||||
TextAlign = ContentAlignment.MiddleCenter,
|
||||
ForeColor = Color.Gray
|
||||
};
|
||||
|
||||
var separator = new Label
|
||||
{
|
||||
Left = 40, Top = 86, Width = 260, Height = 1,
|
||||
BorderStyle = BorderStyle.Fixed3D
|
||||
};
|
||||
|
||||
var lblCompany = new Label
|
||||
{
|
||||
Text = "HackerSoft",
|
||||
Left = 0, Top = 100, Width = 340, Height = 24,
|
||||
TextAlign = ContentAlignment.MiddleCenter,
|
||||
Font = new Font("Segoe UI", 11, FontStyle.Bold)
|
||||
};
|
||||
|
||||
var lblSubtitle = new Label
|
||||
{
|
||||
Text = "Hacker-Net Telekommunikation",
|
||||
Left = 0, Top = 124, Width = 340, Height = 20,
|
||||
TextAlign = ContentAlignment.MiddleCenter,
|
||||
ForeColor = Color.Gray
|
||||
};
|
||||
|
||||
var lblAddress = new Label
|
||||
{
|
||||
Text = "Stefan Hacker\r\nAm Wunderburgpark 5b\r\n26135 Oldenburg",
|
||||
Left = 0, Top = 152, Width = 340, Height = 56,
|
||||
TextAlign = ContentAlignment.MiddleCenter,
|
||||
ForeColor = Color.FromArgb(96, 94, 92)
|
||||
};
|
||||
|
||||
var btnOk = new Button
|
||||
{
|
||||
Text = "OK", Left = 130, Top = 212, Width = 80, Height = 28,
|
||||
DialogResult = DialogResult.OK
|
||||
};
|
||||
|
||||
Controls.AddRange(new Control[] { lblProduct, lblVersion, separator, lblCompany, lblSubtitle, lblAddress, btnOk });
|
||||
AcceptButton = btnOk;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Timers;
|
||||
using System.Windows.Forms;
|
||||
using StarfaceOutlookSync.Models;
|
||||
using StarfaceOutlookSync.Services;
|
||||
using Timer = System.Timers.Timer;
|
||||
|
||||
namespace StarfaceOutlookSync.UI
|
||||
{
|
||||
public class MainForm : Form
|
||||
{
|
||||
private readonly ProfileManager _profileManager = new ProfileManager();
|
||||
private readonly SyncEngine _syncEngine = new SyncEngine();
|
||||
private NotifyIcon _trayIcon;
|
||||
private ContextMenuStrip _trayMenu;
|
||||
private ListView _profileList;
|
||||
private Button _btnNew, _btnEdit, _btnDelete, _btnSync, _btnInfo;
|
||||
private StatusStrip _statusBar;
|
||||
private ToolStripStatusLabel _statusLabel;
|
||||
private Timer _autoSyncTimer;
|
||||
|
||||
public MainForm()
|
||||
{
|
||||
InitializeComponent();
|
||||
SetupTrayIcon();
|
||||
SetupAutoSync();
|
||||
RefreshProfileList();
|
||||
}
|
||||
|
||||
private void InitializeComponent()
|
||||
{
|
||||
Text = "Starface Kontakt-Sync";
|
||||
Size = new Size(620, 450);
|
||||
MinimumSize = new Size(500, 350);
|
||||
StartPosition = FormStartPosition.CenterScreen;
|
||||
Font = new Font("Segoe UI", 9);
|
||||
|
||||
// Profil-Liste
|
||||
_profileList = new ListView
|
||||
{
|
||||
Dock = DockStyle.Fill,
|
||||
View = View.Details,
|
||||
FullRowSelect = true,
|
||||
GridLines = true,
|
||||
MultiSelect = false
|
||||
};
|
||||
_profileList.Columns.Add("Profil", 150);
|
||||
_profileList.Columns.Add("Starface", 130);
|
||||
_profileList.Columns.Add("Outlook-Ordner", 130);
|
||||
_profileList.Columns.Add("Richtung", 90);
|
||||
_profileList.Columns.Add("Letzte Sync", 130);
|
||||
_profileList.DoubleClick += (s, e) => EditProfile();
|
||||
|
||||
// Button-Panel
|
||||
var buttonPanel = new FlowLayoutPanel
|
||||
{
|
||||
Dock = DockStyle.Bottom,
|
||||
Height = 45,
|
||||
Padding = new Padding(8, 8, 8, 4),
|
||||
FlowDirection = FlowDirection.LeftToRight
|
||||
};
|
||||
|
||||
_btnNew = new Button { Text = "Neues Profil", Width = 100, Height = 30 };
|
||||
_btnNew.Click += (s, e) => NewProfile();
|
||||
|
||||
_btnEdit = new Button { Text = "Bearbeiten", Width = 90, Height = 30 };
|
||||
_btnEdit.Click += (s, e) => EditProfile();
|
||||
|
||||
_btnDelete = new Button { Text = "Loeschen", Width = 80, Height = 30 };
|
||||
_btnDelete.Click += (s, e) => DeleteProfile();
|
||||
|
||||
_btnSync = new Button { Text = "Jetzt synchronisieren", Width = 150, Height = 30 };
|
||||
_btnSync.Click += async (s, e) => await SyncSelectedProfile();
|
||||
|
||||
_btnInfo = new Button { Text = "Info", Width = 50, Height = 30 };
|
||||
_btnInfo.Click += (s, e) => ShowAbout();
|
||||
|
||||
buttonPanel.Controls.AddRange(new Control[] { _btnNew, _btnEdit, _btnDelete, _btnSync, _btnInfo });
|
||||
|
||||
// Statusbar
|
||||
_statusBar = new StatusStrip();
|
||||
_statusLabel = new ToolStripStatusLabel("Bereit");
|
||||
_statusBar.Items.Add(_statusLabel);
|
||||
|
||||
Controls.Add(_profileList);
|
||||
Controls.Add(buttonPanel);
|
||||
Controls.Add(_statusBar);
|
||||
}
|
||||
|
||||
private void SetupTrayIcon()
|
||||
{
|
||||
_trayMenu = new ContextMenuStrip();
|
||||
_trayMenu.Items.Add("Oeffnen", null, (s, e) => ShowMainWindow());
|
||||
_trayMenu.Items.Add("-");
|
||||
|
||||
// Schnell-Sync fuer jedes Profil
|
||||
var profiles = _profileManager.GetProfiles();
|
||||
foreach (var p in profiles.Where(p => p.Enabled))
|
||||
{
|
||||
var profile = p;
|
||||
_trayMenu.Items.Add($"Sync: {profile.Name}", null, async (s, e) =>
|
||||
{
|
||||
await RunSync(profile);
|
||||
});
|
||||
}
|
||||
|
||||
if (profiles.Any(p => p.Enabled))
|
||||
_trayMenu.Items.Add("-");
|
||||
|
||||
_trayMenu.Items.Add("Beenden", null, (s, e) => ExitApplication());
|
||||
|
||||
_trayIcon = new NotifyIcon
|
||||
{
|
||||
Text = "Starface Kontakt-Sync",
|
||||
Icon = SystemIcons.Application, // Placeholder, wird durch eigenes Icon ersetzt
|
||||
ContextMenuStrip = _trayMenu,
|
||||
Visible = true
|
||||
};
|
||||
|
||||
_trayIcon.DoubleClick += (s, e) => ShowMainWindow();
|
||||
}
|
||||
|
||||
private void SetupAutoSync()
|
||||
{
|
||||
_autoSyncTimer = new Timer(60000); // Jede Minute pruefen
|
||||
_autoSyncTimer.Elapsed += async (s, e) => await CheckAutoSync();
|
||||
_autoSyncTimer.Start();
|
||||
}
|
||||
|
||||
private async Task CheckAutoSync()
|
||||
{
|
||||
var profiles = _profileManager.GetProfiles();
|
||||
foreach (var profile in profiles.Where(p => p.Enabled && p.AutoSyncIntervalMinutes > 0))
|
||||
{
|
||||
if (string.IsNullOrEmpty(profile.LastSync))
|
||||
{
|
||||
await RunSync(profile);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (DateTime.TryParse(profile.LastSync, out var lastSync))
|
||||
{
|
||||
if (DateTime.Now - lastSync > TimeSpan.FromMinutes(profile.AutoSyncIntervalMinutes))
|
||||
{
|
||||
await RunSync(profile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowMainWindow()
|
||||
{
|
||||
Show();
|
||||
WindowState = FormWindowState.Normal;
|
||||
BringToFront();
|
||||
RefreshProfileList();
|
||||
}
|
||||
|
||||
private void RefreshProfileList()
|
||||
{
|
||||
_profileList.Items.Clear();
|
||||
var profiles = _profileManager.GetProfiles();
|
||||
|
||||
foreach (var p in profiles)
|
||||
{
|
||||
var dirText = p.SyncDirection == SyncDirection.Both ? "Bidirektional" :
|
||||
p.SyncDirection == SyncDirection.OutlookToStarface ? "OL -> SF" : "SF -> OL";
|
||||
var lastSync = string.IsNullOrEmpty(p.LastSync) ? "Noch nie" :
|
||||
DateTime.TryParse(p.LastSync, out var dt) ? dt.ToString("dd.MM.yyyy HH:mm") : p.LastSync;
|
||||
|
||||
var item = new ListViewItem(new[]
|
||||
{
|
||||
p.Name,
|
||||
$"{p.StarfaceConnection.Host} / {p.StarfaceAddressBook.Name}",
|
||||
p.OutlookFolderName,
|
||||
dirText,
|
||||
lastSync
|
||||
});
|
||||
item.Tag = p;
|
||||
|
||||
if (!p.Enabled)
|
||||
item.ForeColor = Color.Gray;
|
||||
|
||||
_profileList.Items.Add(item);
|
||||
}
|
||||
|
||||
// Tray-Menu aktualisieren
|
||||
SetupTrayIcon();
|
||||
}
|
||||
|
||||
private void NewProfile()
|
||||
{
|
||||
using (var editor = new ProfileEditorForm(null))
|
||||
{
|
||||
if (editor.ShowDialog(this) == DialogResult.OK)
|
||||
RefreshProfileList();
|
||||
}
|
||||
}
|
||||
|
||||
private void EditProfile()
|
||||
{
|
||||
if (_profileList.SelectedItems.Count == 0) return;
|
||||
var profile = _profileList.SelectedItems[0].Tag as SyncProfile;
|
||||
if (profile == null) return;
|
||||
|
||||
using (var editor = new ProfileEditorForm(profile))
|
||||
{
|
||||
if (editor.ShowDialog(this) == DialogResult.OK)
|
||||
RefreshProfileList();
|
||||
}
|
||||
}
|
||||
|
||||
private void DeleteProfile()
|
||||
{
|
||||
if (_profileList.SelectedItems.Count == 0) return;
|
||||
var profile = _profileList.SelectedItems[0].Tag as SyncProfile;
|
||||
if (profile == null) return;
|
||||
|
||||
if (MessageBox.Show($"Profil '{profile.Name}' wirklich loeschen?",
|
||||
"Profil loeschen", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_profileManager.DeleteProfile(profile.Id);
|
||||
RefreshProfileList();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SyncSelectedProfile()
|
||||
{
|
||||
if (_profileList.SelectedItems.Count == 0)
|
||||
{
|
||||
MessageBox.Show("Bitte ein Profil auswaehlen.", "Sync",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
var profile = _profileList.SelectedItems[0].Tag as SyncProfile;
|
||||
if (profile == null) return;
|
||||
|
||||
using (var syncForm = new SyncProgressForm(profile))
|
||||
{
|
||||
syncForm.ShowDialog(this);
|
||||
}
|
||||
|
||||
RefreshProfileList();
|
||||
}
|
||||
|
||||
private async Task RunSync(SyncProfile profile)
|
||||
{
|
||||
try
|
||||
{
|
||||
SetStatus($"Synchronisiere '{profile.Name}'...");
|
||||
_trayIcon.ShowBalloonTip(2000, "Starface Sync",
|
||||
$"Synchronisiere '{profile.Name}'...", ToolTipIcon.Info);
|
||||
|
||||
var result = await _syncEngine.SyncProfileAsync(profile);
|
||||
|
||||
var msg = $"{profile.Name}: {result.Created} erstellt, {result.Updated} aktualisiert";
|
||||
if (result.Errors > 0) msg += $", {result.Errors} Fehler";
|
||||
|
||||
_trayIcon.ShowBalloonTip(3000, "Starface Sync", msg,
|
||||
result.Errors > 0 ? ToolTipIcon.Warning : ToolTipIcon.Info);
|
||||
|
||||
SetStatus(msg);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_trayIcon.ShowBalloonTip(3000, "Starface Sync Fehler",
|
||||
ex.Message, ToolTipIcon.Error);
|
||||
SetStatus($"Fehler: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void SetStatus(string text)
|
||||
{
|
||||
if (InvokeRequired)
|
||||
Invoke(new Action(() => _statusLabel.Text = text));
|
||||
else
|
||||
_statusLabel.Text = text;
|
||||
}
|
||||
|
||||
private void ShowAbout()
|
||||
{
|
||||
using (var about = new AboutForm())
|
||||
{
|
||||
about.ShowDialog(this);
|
||||
}
|
||||
}
|
||||
|
||||
private void ExitApplication()
|
||||
{
|
||||
_autoSyncTimer?.Stop();
|
||||
_trayIcon.Visible = false;
|
||||
_trayIcon.Dispose();
|
||||
Application.Exit();
|
||||
}
|
||||
|
||||
protected override void OnFormClosing(FormClosingEventArgs e)
|
||||
{
|
||||
if (e.CloseReason == CloseReason.UserClosing)
|
||||
{
|
||||
e.Cancel = true;
|
||||
Hide(); // In den Tray minimieren
|
||||
_trayIcon.ShowBalloonTip(2000, "Starface Kontakt-Sync",
|
||||
"Laeuft im Hintergrund weiter. Rechtsklick auf das Tray-Icon fuer Optionen.",
|
||||
ToolTipIcon.Info);
|
||||
}
|
||||
else
|
||||
{
|
||||
base.OnFormClosing(e);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_autoSyncTimer?.Dispose();
|
||||
_trayIcon?.Dispose();
|
||||
_trayMenu?.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using StarfaceOutlookSync.Models;
|
||||
using StarfaceOutlookSync.Services;
|
||||
|
||||
namespace StarfaceOutlookSync.UI
|
||||
{
|
||||
public class ProfileEditorForm : Form
|
||||
{
|
||||
private readonly ProfileManager _pm = new ProfileManager();
|
||||
private readonly SyncProfile _existingProfile;
|
||||
private readonly bool _isNew;
|
||||
|
||||
// Controls
|
||||
private TextBox _txtName, _txtHost, _txtPort, _txtLoginId, _txtPassword;
|
||||
private CheckBox _chkSsl, _chkEnabled;
|
||||
private ComboBox _cmbAddressBook, _cmbOutlookFolder, _cmbDirection;
|
||||
private NumericUpDown _numAutoSync;
|
||||
private Button _btnTest, _btnLoadBooks, _btnSave, _btnCancel;
|
||||
private Label _lblTestResult;
|
||||
|
||||
private List<StarfaceAddressBook> _addressBooks = new List<StarfaceAddressBook>();
|
||||
|
||||
public ProfileEditorForm(SyncProfile profile)
|
||||
{
|
||||
_existingProfile = profile;
|
||||
_isNew = profile == null;
|
||||
InitializeComponent();
|
||||
LoadData();
|
||||
}
|
||||
|
||||
private void InitializeComponent()
|
||||
{
|
||||
Text = _isNew ? "Neues Sync-Profil" : "Profil bearbeiten";
|
||||
Size = new Size(480, 620);
|
||||
FormBorderStyle = FormBorderStyle.FixedDialog;
|
||||
MaximizeBox = false;
|
||||
MinimizeBox = false;
|
||||
StartPosition = FormStartPosition.CenterParent;
|
||||
Font = new Font("Segoe UI", 9);
|
||||
|
||||
var panel = new Panel { Dock = DockStyle.Fill, AutoScroll = true, Padding = new Padding(16) };
|
||||
int y = 8;
|
||||
|
||||
// Profilname
|
||||
panel.Controls.Add(MakeLabel("Profilname:", 12, y)); y += 22;
|
||||
_txtName = new TextBox { Left = 12, Top = y, Width = 420 }; panel.Controls.Add(_txtName); y += 32;
|
||||
|
||||
// === Starface ===
|
||||
panel.Controls.Add(MakeSectionLabel("Starface-Verbindung", 12, y)); y += 26;
|
||||
|
||||
panel.Controls.Add(MakeLabel("Host / IP-Adresse:", 12, y)); y += 22;
|
||||
_txtHost = new TextBox { Left = 12, Top = y, Width = 320 };
|
||||
_txtPort = new TextBox { Left = 340, Top = y, Width = 60, Text = "443" };
|
||||
panel.Controls.Add(_txtHost);
|
||||
panel.Controls.Add(MakeLabel("Port:", 340, y - 22));
|
||||
panel.Controls.Add(_txtPort); y += 32;
|
||||
|
||||
_chkSsl = new CheckBox { Text = "HTTPS verwenden", Left = 12, Top = y, Checked = true, AutoSize = true };
|
||||
panel.Controls.Add(_chkSsl); y += 28;
|
||||
|
||||
panel.Controls.Add(MakeLabel("Login-ID:", 12, y)); y += 22;
|
||||
_txtLoginId = new TextBox { Left = 12, Top = y, Width = 200 }; panel.Controls.Add(_txtLoginId); y += 32;
|
||||
|
||||
panel.Controls.Add(MakeLabel("Kennwort:", 12, y)); y += 22;
|
||||
_txtPassword = new TextBox { Left = 12, Top = y, Width = 200, UseSystemPasswordChar = true };
|
||||
panel.Controls.Add(_txtPassword); y += 32;
|
||||
|
||||
_btnTest = new Button { Text = "Verbindung testen", Left = 12, Top = y, Width = 130, Height = 28 };
|
||||
_btnTest.Click += async (s, e) => await TestConnection();
|
||||
_btnLoadBooks = new Button { Text = "Adressbuecher laden", Left = 150, Top = y, Width = 140, Height = 28 };
|
||||
_btnLoadBooks.Click += async (s, e) => await LoadAddressBooks();
|
||||
panel.Controls.Add(_btnTest);
|
||||
panel.Controls.Add(_btnLoadBooks); y += 32;
|
||||
|
||||
_lblTestResult = new Label { Left = 12, Top = y, Width = 420, Height = 20, ForeColor = Color.Gray };
|
||||
panel.Controls.Add(_lblTestResult); y += 26;
|
||||
|
||||
panel.Controls.Add(MakeLabel("Starface-Adressbuch:", 12, y)); y += 22;
|
||||
_cmbAddressBook = new ComboBox { Left = 12, Top = y, Width = 420, DropDownStyle = ComboBoxStyle.DropDownList };
|
||||
panel.Controls.Add(_cmbAddressBook); y += 32;
|
||||
|
||||
// === Outlook ===
|
||||
panel.Controls.Add(MakeSectionLabel("Outlook-Einstellungen", 12, y)); y += 26;
|
||||
|
||||
panel.Controls.Add(MakeLabel("Kontakte-Ordner:", 12, y)); y += 22;
|
||||
_cmbOutlookFolder = new ComboBox { Left = 12, Top = y, Width = 420, DropDownStyle = ComboBoxStyle.DropDownList };
|
||||
panel.Controls.Add(_cmbOutlookFolder); y += 32;
|
||||
|
||||
panel.Controls.Add(MakeLabel("Sync-Richtung:", 12, y)); y += 22;
|
||||
_cmbDirection = new ComboBox { Left = 12, Top = y, Width = 250, DropDownStyle = ComboBoxStyle.DropDownList };
|
||||
_cmbDirection.Items.AddRange(new object[] { "Bidirektional", "Outlook -> Starface", "Starface -> Outlook" });
|
||||
_cmbDirection.SelectedIndex = 0;
|
||||
panel.Controls.Add(_cmbDirection); y += 32;
|
||||
|
||||
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 };
|
||||
panel.Controls.Add(_numAutoSync); y += 32;
|
||||
|
||||
_chkEnabled = new CheckBox { Text = "Profil aktiviert", Left = 12, Top = y, Checked = true, AutoSize = true };
|
||||
panel.Controls.Add(_chkEnabled); y += 36;
|
||||
|
||||
// Buttons
|
||||
_btnSave = new Button { Text = "Speichern", Left = 12, Top = y, Width = 100, Height = 30, DialogResult = DialogResult.None };
|
||||
_btnSave.Click += (s, e) => SaveProfile();
|
||||
_btnCancel = new Button { Text = "Abbrechen", Left = 120, Top = y, Width = 100, Height = 30, DialogResult = DialogResult.Cancel };
|
||||
panel.Controls.Add(_btnSave);
|
||||
panel.Controls.Add(_btnCancel);
|
||||
|
||||
Controls.Add(panel);
|
||||
AcceptButton = _btnSave;
|
||||
CancelButton = _btnCancel;
|
||||
}
|
||||
|
||||
private Label MakeLabel(string text, int x, int y)
|
||||
{
|
||||
return new Label { Text = text, Left = x, Top = y, AutoSize = true };
|
||||
}
|
||||
|
||||
private Label MakeSectionLabel(string text, int x, int y)
|
||||
{
|
||||
return new Label { Text = text, Left = x, Top = y, AutoSize = true, Font = new Font("Segoe UI", 10, FontStyle.Bold) };
|
||||
}
|
||||
|
||||
private void LoadData()
|
||||
{
|
||||
// Outlook-Ordner laden
|
||||
try
|
||||
{
|
||||
using (var outlook = new OutlookContactsService())
|
||||
{
|
||||
var folders = outlook.GetContactFolderPaths();
|
||||
_cmbOutlookFolder.Items.Clear();
|
||||
foreach (var f in folders)
|
||||
_cmbOutlookFolder.Items.Add(f);
|
||||
if (folders.Count > 0)
|
||||
_cmbOutlookFolder.SelectedIndex = 0;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
_cmbOutlookFolder.Items.Add("\\\\Kontakte");
|
||||
_cmbOutlookFolder.SelectedIndex = 0;
|
||||
}
|
||||
|
||||
// Bestehende Werte laden
|
||||
if (_existingProfile != null)
|
||||
{
|
||||
_txtName.Text = _existingProfile.Name;
|
||||
_txtHost.Text = _existingProfile.StarfaceConnection.Host;
|
||||
_txtPort.Text = _existingProfile.StarfaceConnection.Port.ToString();
|
||||
_chkSsl.Checked = _existingProfile.StarfaceConnection.UseSsl;
|
||||
_txtLoginId.Text = _existingProfile.StarfaceConnection.LoginId;
|
||||
_txtPassword.Text = _existingProfile.StarfaceConnection.Password;
|
||||
_chkEnabled.Checked = _existingProfile.Enabled;
|
||||
_numAutoSync.Value = _existingProfile.AutoSyncIntervalMinutes;
|
||||
|
||||
_cmbDirection.SelectedIndex = (int)_existingProfile.SyncDirection;
|
||||
|
||||
// Outlook-Ordner auswaehlen
|
||||
for (int i = 0; i < _cmbOutlookFolder.Items.Count; i++)
|
||||
{
|
||||
if (_cmbOutlookFolder.Items[i].ToString() == _existingProfile.OutlookFolderPath)
|
||||
{
|
||||
_cmbOutlookFolder.SelectedIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Adressbuch
|
||||
if (_existingProfile.StarfaceAddressBook != null)
|
||||
{
|
||||
_addressBooks.Add(_existingProfile.StarfaceAddressBook);
|
||||
_cmbAddressBook.Items.Add(_existingProfile.StarfaceAddressBook.Name);
|
||||
_cmbAddressBook.SelectedIndex = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private StarfaceConnection GetConnection()
|
||||
{
|
||||
return new StarfaceConnection
|
||||
{
|
||||
Host = _txtHost.Text.Trim(),
|
||||
Port = int.TryParse(_txtPort.Text, out var p) ? p : 443,
|
||||
UseSsl = _chkSsl.Checked,
|
||||
LoginId = _txtLoginId.Text.Trim(),
|
||||
Password = _txtPassword.Text
|
||||
};
|
||||
}
|
||||
|
||||
private async Task TestConnection()
|
||||
{
|
||||
_lblTestResult.Text = "Teste Verbindung...";
|
||||
_lblTestResult.ForeColor = Color.Gray;
|
||||
_btnTest.Enabled = false;
|
||||
|
||||
try
|
||||
{
|
||||
using (var client = new StarfaceApiClient(GetConnection()))
|
||||
{
|
||||
var ok = await client.LoginAsync();
|
||||
if (ok)
|
||||
{
|
||||
_lblTestResult.Text = "Verbindung erfolgreich!";
|
||||
_lblTestResult.ForeColor = Color.Green;
|
||||
await client.LogoutAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_lblTestResult.Text = "Login fehlgeschlagen. Zugangsdaten pruefen.";
|
||||
_lblTestResult.ForeColor = Color.Red;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_lblTestResult.Text = $"Fehler: {ex.Message}";
|
||||
_lblTestResult.ForeColor = Color.Red;
|
||||
}
|
||||
|
||||
_btnTest.Enabled = true;
|
||||
}
|
||||
|
||||
private async Task LoadAddressBooks()
|
||||
{
|
||||
_lblTestResult.Text = "Lade Adressbuecher...";
|
||||
_lblTestResult.ForeColor = Color.Gray;
|
||||
_btnLoadBooks.Enabled = false;
|
||||
|
||||
try
|
||||
{
|
||||
using (var client = new StarfaceApiClient(GetConnection()))
|
||||
{
|
||||
var ok = await client.LoginAsync();
|
||||
if (!ok)
|
||||
{
|
||||
_lblTestResult.Text = "Login fehlgeschlagen.";
|
||||
_lblTestResult.ForeColor = Color.Red;
|
||||
_btnLoadBooks.Enabled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_addressBooks = await client.GetAddressBooksAsync();
|
||||
await client.LogoutAsync();
|
||||
|
||||
_cmbAddressBook.Items.Clear();
|
||||
foreach (var book in _addressBooks)
|
||||
_cmbAddressBook.Items.Add(book.Name);
|
||||
|
||||
if (_addressBooks.Count > 0)
|
||||
{
|
||||
_cmbAddressBook.SelectedIndex = 0;
|
||||
_lblTestResult.Text = $"{_addressBooks.Count} Adressbuch/buecher gefunden.";
|
||||
_lblTestResult.ForeColor = Color.Green;
|
||||
}
|
||||
else
|
||||
{
|
||||
_lblTestResult.Text = "Keine Adressbuecher gefunden.";
|
||||
_lblTestResult.ForeColor = Color.Orange;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_lblTestResult.Text = $"Fehler: {ex.Message}";
|
||||
_lblTestResult.ForeColor = Color.Red;
|
||||
}
|
||||
|
||||
_btnLoadBooks.Enabled = true;
|
||||
}
|
||||
|
||||
private void SaveProfile()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_txtName.Text))
|
||||
{
|
||||
MessageBox.Show("Bitte Profilnamen eingeben.", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(_txtHost.Text))
|
||||
{
|
||||
MessageBox.Show("Bitte Starface-Host eingeben.", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
return;
|
||||
}
|
||||
if (_cmbAddressBook.SelectedIndex < 0 || _addressBooks.Count == 0)
|
||||
{
|
||||
MessageBox.Show("Bitte ein Starface-Adressbuch auswaehlen.\nZuerst 'Adressbuecher laden' klicken.",
|
||||
"Fehler", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
return;
|
||||
}
|
||||
|
||||
var selectedFolder = _cmbOutlookFolder.SelectedItem?.ToString() ?? "";
|
||||
var folderName = selectedFolder;
|
||||
if (folderName.Contains("\\"))
|
||||
folderName = folderName.Substring(folderName.LastIndexOf('\\') + 1);
|
||||
|
||||
var profile = new SyncProfile
|
||||
{
|
||||
Id = _existingProfile?.Id ?? _pm.GenerateId(),
|
||||
Name = _txtName.Text.Trim(),
|
||||
StarfaceConnection = GetConnection(),
|
||||
StarfaceAddressBook = _addressBooks[_cmbAddressBook.SelectedIndex],
|
||||
OutlookFolderPath = selectedFolder,
|
||||
OutlookFolderName = folderName,
|
||||
SyncDirection = (SyncDirection)_cmbDirection.SelectedIndex,
|
||||
Enabled = _chkEnabled.Checked,
|
||||
AutoSyncIntervalMinutes = (int)_numAutoSync.Value,
|
||||
LastSync = _existingProfile?.LastSync ?? ""
|
||||
};
|
||||
|
||||
if (_isNew)
|
||||
_pm.AddProfile(profile);
|
||||
else
|
||||
_pm.UpdateProfile(profile);
|
||||
|
||||
DialogResult = DialogResult.OK;
|
||||
Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using StarfaceOutlookSync.Models;
|
||||
using StarfaceOutlookSync.Services;
|
||||
|
||||
namespace StarfaceOutlookSync.UI
|
||||
{
|
||||
public class SyncProgressForm : Form
|
||||
{
|
||||
private readonly SyncProfile _profile;
|
||||
private readonly SyncEngine _engine = new SyncEngine();
|
||||
private TextBox _txtLog;
|
||||
private ProgressBar _progressBar;
|
||||
private Button _btnClose, _btnStart;
|
||||
private Label _lblResult;
|
||||
|
||||
public SyncProgressForm(SyncProfile profile)
|
||||
{
|
||||
_profile = profile;
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void InitializeComponent()
|
||||
{
|
||||
Text = $"Synchronisation - {_profile.Name}";
|
||||
Size = new Size(500, 400);
|
||||
FormBorderStyle = FormBorderStyle.FixedDialog;
|
||||
MaximizeBox = false;
|
||||
MinimizeBox = false;
|
||||
StartPosition = FormStartPosition.CenterParent;
|
||||
Font = new Font("Segoe UI", 9);
|
||||
|
||||
var infoLabel = new Label
|
||||
{
|
||||
Text = $"{_profile.StarfaceConnection.Host} ({_profile.StarfaceAddressBook.Name}) <-> {_profile.OutlookFolderName}",
|
||||
Left = 12, Top = 12, Width = 460, AutoSize = false, Height = 20
|
||||
};
|
||||
|
||||
_progressBar = new ProgressBar
|
||||
{
|
||||
Left = 12, Top = 38, Width = 460, Height = 22,
|
||||
Style = ProgressBarStyle.Marquee
|
||||
};
|
||||
|
||||
_txtLog = new TextBox
|
||||
{
|
||||
Left = 12, Top = 68, Width = 460, Height = 200,
|
||||
Multiline = true, ReadOnly = true, ScrollBars = ScrollBars.Vertical,
|
||||
BackColor = Color.FromArgb(30, 30, 30), ForeColor = Color.FromArgb(212, 212, 212),
|
||||
Font = new Font("Consolas", 9)
|
||||
};
|
||||
|
||||
_lblResult = new Label
|
||||
{
|
||||
Left = 12, Top = 276, Width = 460, Height = 40,
|
||||
AutoSize = false, ForeColor = Color.Gray
|
||||
};
|
||||
|
||||
_btnStart = new Button
|
||||
{
|
||||
Text = "Synchronisation starten", Left = 12, Top = 322, Width = 180, Height = 30
|
||||
};
|
||||
_btnStart.Click += async (s, e) => await RunSync();
|
||||
|
||||
_btnClose = new Button
|
||||
{
|
||||
Text = "Schliessen", Left = 380, Top = 322, Width = 90, Height = 30,
|
||||
DialogResult = DialogResult.Cancel
|
||||
};
|
||||
|
||||
Controls.AddRange(new Control[] { infoLabel, _progressBar, _txtLog, _lblResult, _btnStart, _btnClose });
|
||||
CancelButton = _btnClose;
|
||||
}
|
||||
|
||||
private void AppendLog(string message)
|
||||
{
|
||||
if (InvokeRequired)
|
||||
{
|
||||
Invoke(new Action(() => AppendLog(message)));
|
||||
return;
|
||||
}
|
||||
_txtLog.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}\r\n");
|
||||
}
|
||||
|
||||
private async Task RunSync()
|
||||
{
|
||||
_btnStart.Enabled = false;
|
||||
_btnClose.Enabled = false;
|
||||
_progressBar.Style = ProgressBarStyle.Marquee;
|
||||
_lblResult.Text = "";
|
||||
|
||||
_engine.OnProgress += AppendLog;
|
||||
|
||||
try
|
||||
{
|
||||
var result = await Task.Run(() => _engine.SyncProfileAsync(_profile));
|
||||
|
||||
_progressBar.Style = ProgressBarStyle.Blocks;
|
||||
_progressBar.Value = 100;
|
||||
|
||||
var resultText = $"Erstellt: {result.Created} | Aktualisiert: {result.Updated} | Fehler: {result.Errors}";
|
||||
_lblResult.Text = resultText;
|
||||
_lblResult.ForeColor = result.Errors > 0 ? Color.OrangeRed : Color.Green;
|
||||
|
||||
if (result.ErrorMessages.Count > 0)
|
||||
{
|
||||
AppendLog("--- Fehler ---");
|
||||
foreach (var err in result.ErrorMessages)
|
||||
AppendLog(err);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_lblResult.Text = $"Fehler: {ex.Message}";
|
||||
_lblResult.ForeColor = Color.Red;
|
||||
AppendLog($"FEHLER: {ex.Message}");
|
||||
}
|
||||
|
||||
_engine.OnProgress -= AppendLog;
|
||||
_btnStart.Enabled = true;
|
||||
_btnStart.Text = "Erneut synchronisieren";
|
||||
_btnClose.Enabled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
/** Unified contact model used for sync between Outlook and Starface */
|
||||
export interface UnifiedContact {
|
||||
id?: string;
|
||||
outlookId?: string;
|
||||
starfaceId?: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
company: string;
|
||||
jobTitle: string;
|
||||
email: string;
|
||||
emailSecondary: string;
|
||||
phoneWork: string;
|
||||
phoneMobile: string;
|
||||
phoneHome: string;
|
||||
fax: string;
|
||||
street: string;
|
||||
city: string;
|
||||
postalCode: string;
|
||||
state: string;
|
||||
country: string;
|
||||
website: string;
|
||||
notes: string;
|
||||
salutation: string;
|
||||
title: string;
|
||||
birthday: string;
|
||||
lastModified?: string;
|
||||
}
|
||||
|
||||
export function emptyContact(): UnifiedContact {
|
||||
return {
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
company: "",
|
||||
jobTitle: "",
|
||||
email: "",
|
||||
emailSecondary: "",
|
||||
phoneWork: "",
|
||||
phoneMobile: "",
|
||||
phoneHome: "",
|
||||
fax: "",
|
||||
street: "",
|
||||
city: "",
|
||||
postalCode: "",
|
||||
state: "",
|
||||
country: "",
|
||||
website: "",
|
||||
notes: "",
|
||||
salutation: "",
|
||||
title: "",
|
||||
birthday: "",
|
||||
};
|
||||
}
|
||||
|
||||
/** Starface connection settings */
|
||||
export interface StarfaceConnection {
|
||||
host: string;
|
||||
port: number;
|
||||
useSsl: boolean;
|
||||
loginId: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
/** A Starface address book (represented by userId scope or tag) */
|
||||
export interface StarfaceAddressBook {
|
||||
type: "central" | "user" | "tag";
|
||||
userId?: string;
|
||||
tagId?: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** An Outlook contact folder */
|
||||
export interface OutlookContactFolder {
|
||||
id: string;
|
||||
displayName: string;
|
||||
parentFolderId?: string;
|
||||
}
|
||||
|
||||
/** A sync profile mapping one Outlook folder to one Starface address book */
|
||||
export interface SyncProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
starfaceConnection: StarfaceConnection;
|
||||
starfaceAddressBook: StarfaceAddressBook;
|
||||
outlookFolderId: string;
|
||||
outlookFolderName: string;
|
||||
syncDirection: "both" | "outlook-to-starface" | "starface-to-outlook";
|
||||
lastSync?: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/** Tracks which contacts have been synced to detect changes */
|
||||
export interface SyncMapping {
|
||||
profileId: string;
|
||||
outlookId: string;
|
||||
starfaceId: string;
|
||||
lastSyncHash: string;
|
||||
}
|
||||
|
||||
/** Result of a sync operation */
|
||||
export interface SyncResult {
|
||||
profileId: string;
|
||||
profileName: string;
|
||||
timestamp: string;
|
||||
created: number;
|
||||
updated: number;
|
||||
deleted: number;
|
||||
errors: string[];
|
||||
direction: string;
|
||||
}
|
||||
@@ -1,246 +0,0 @@
|
||||
import { UnifiedContact, OutlookContactFolder, emptyContact } from "../models/types";
|
||||
|
||||
/**
|
||||
* Outlook contacts service using Office.js REST API and EWS.
|
||||
* Works in both classic and new Outlook via Office.js mailbox REST API.
|
||||
*/
|
||||
export class OutlookContactsService {
|
||||
private accessToken: string | null = null;
|
||||
|
||||
/** Get REST API access token from Office.js */
|
||||
async getAccessToken(): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof Office === "undefined" || !Office.context?.mailbox) {
|
||||
reject(new Error("Office.js nicht verfügbar"));
|
||||
return;
|
||||
}
|
||||
|
||||
Office.context.mailbox.getCallbackTokenAsync(
|
||||
{ isRest: true },
|
||||
(result) => {
|
||||
if (result.status === Office.AsyncResultStatus.Succeeded) {
|
||||
this.accessToken = result.value;
|
||||
resolve(result.value);
|
||||
} else {
|
||||
reject(new Error(result.error?.message || "Token-Fehler"));
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private getRestUrl(): string {
|
||||
if (!Office.context?.mailbox?.restUrl) {
|
||||
return "https://outlook.office.com/api/v2.0";
|
||||
}
|
||||
return Office.context.mailbox.restUrl + "/v2.0";
|
||||
}
|
||||
|
||||
private async fetchApi(endpoint: string, options: RequestInit = {}): Promise<Response> {
|
||||
if (!this.accessToken) {
|
||||
await this.getAccessToken();
|
||||
}
|
||||
|
||||
const url = `${this.getRestUrl()}${endpoint}`;
|
||||
return fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
...((options.headers as Record<string, string>) || {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getContactFolders(): Promise<OutlookContactFolder[]> {
|
||||
try {
|
||||
const resp = await this.fetchApi("/me/contactfolders");
|
||||
if (!resp.ok) {
|
||||
console.error("Failed to get contact folders:", resp.status);
|
||||
return [];
|
||||
}
|
||||
const data = await resp.json();
|
||||
const folders: OutlookContactFolder[] = [
|
||||
{ id: "default", displayName: "Kontakte (Standard)" },
|
||||
];
|
||||
|
||||
for (const f of data.value || []) {
|
||||
folders.push({
|
||||
id: f.Id,
|
||||
displayName: f.DisplayName,
|
||||
parentFolderId: f.ParentFolderId,
|
||||
});
|
||||
}
|
||||
|
||||
return folders;
|
||||
} catch (err) {
|
||||
console.error("Error getting contact folders:", err);
|
||||
return [{ id: "default", displayName: "Kontakte (Standard)" }];
|
||||
}
|
||||
}
|
||||
|
||||
async getContacts(folderId: string): Promise<UnifiedContact[]> {
|
||||
const allContacts: UnifiedContact[] = [];
|
||||
let nextLink: string | null = null;
|
||||
const pageSize = 100;
|
||||
|
||||
const basePath =
|
||||
folderId === "default"
|
||||
? `/me/contacts?$top=${pageSize}`
|
||||
: `/me/contactfolders/${folderId}/contacts?$top=${pageSize}`;
|
||||
|
||||
let endpoint = basePath;
|
||||
|
||||
do {
|
||||
const resp = await this.fetchApi(endpoint);
|
||||
if (!resp.ok) break;
|
||||
|
||||
const data = await resp.json();
|
||||
for (const c of data.value || []) {
|
||||
allContacts.push(this.mapFromOutlook(c));
|
||||
}
|
||||
|
||||
nextLink = data["@odata.nextLink"] || null;
|
||||
if (nextLink) {
|
||||
// Extract relative path from full URL
|
||||
const restUrl = this.getRestUrl();
|
||||
endpoint = nextLink.replace(restUrl, "");
|
||||
}
|
||||
} while (nextLink);
|
||||
|
||||
return allContacts;
|
||||
}
|
||||
|
||||
async createContact(
|
||||
contact: UnifiedContact,
|
||||
folderId: string
|
||||
): Promise<UnifiedContact | null> {
|
||||
const outlookContact = this.mapToOutlook(contact);
|
||||
const endpoint =
|
||||
folderId === "default"
|
||||
? "/me/contacts"
|
||||
: `/me/contactfolders/${folderId}/contacts`;
|
||||
|
||||
const resp = await this.fetchApi(endpoint, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(outlookContact),
|
||||
});
|
||||
|
||||
if (!resp.ok) return null;
|
||||
const created = await resp.json();
|
||||
return this.mapFromOutlook(created);
|
||||
}
|
||||
|
||||
async updateContact(
|
||||
outlookId: string,
|
||||
contact: UnifiedContact
|
||||
): Promise<boolean> {
|
||||
const outlookContact = this.mapToOutlook(contact);
|
||||
const resp = await this.fetchApi(`/me/contacts/${outlookId}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(outlookContact),
|
||||
});
|
||||
return resp.ok;
|
||||
}
|
||||
|
||||
async deleteContact(outlookId: string): Promise<boolean> {
|
||||
const resp = await this.fetchApi(`/me/contacts/${outlookId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
return resp.ok;
|
||||
}
|
||||
|
||||
private mapFromOutlook(c: Record<string, unknown>): UnifiedContact {
|
||||
const contact = emptyContact();
|
||||
contact.outlookId = (c.Id as string) || "";
|
||||
contact.firstName = (c.GivenName as string) || "";
|
||||
contact.lastName = (c.Surname as string) || "";
|
||||
contact.company = (c.CompanyName as string) || "";
|
||||
contact.jobTitle = (c.JobTitle as string) || "";
|
||||
contact.salutation = (c.Title as string) || "";
|
||||
|
||||
const emails = (c.EmailAddresses as Array<{ Address: string }>) || [];
|
||||
contact.email = emails[0]?.Address || "";
|
||||
contact.emailSecondary = emails[1]?.Address || "";
|
||||
|
||||
const phones = (c.Phones as Array<{ Type: string; Number: string }>) || [];
|
||||
for (const p of phones) {
|
||||
switch (p.Type) {
|
||||
case "Business":
|
||||
contact.phoneWork = p.Number || "";
|
||||
break;
|
||||
case "Mobile":
|
||||
contact.phoneMobile = p.Number || "";
|
||||
break;
|
||||
case "Home":
|
||||
contact.phoneHome = p.Number || "";
|
||||
break;
|
||||
case "BusinessFax":
|
||||
contact.fax = p.Number || "";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const addr = (c.BusinessAddress || c.HomeAddress || {}) as Record<string, string>;
|
||||
contact.street = addr.Street || "";
|
||||
contact.city = addr.City || "";
|
||||
contact.postalCode = addr.PostalCode || "";
|
||||
contact.state = addr.State || "";
|
||||
contact.country = addr.CountryOrRegion || "";
|
||||
|
||||
const websites = (c.Websites as Array<{ Address: string }>) || [];
|
||||
contact.website = websites[0]?.Address || "";
|
||||
contact.notes = (c.PersonalNotes as string) || "";
|
||||
contact.birthday = (c.Birthday as string) || "";
|
||||
contact.lastModified = (c.LastModifiedDateTime as string) || "";
|
||||
|
||||
return contact;
|
||||
}
|
||||
|
||||
private mapToOutlook(contact: UnifiedContact): Record<string, unknown> {
|
||||
const c: Record<string, unknown> = {
|
||||
GivenName: contact.firstName,
|
||||
Surname: contact.lastName,
|
||||
CompanyName: contact.company,
|
||||
JobTitle: contact.jobTitle,
|
||||
Title: contact.salutation,
|
||||
PersonalNotes: contact.notes,
|
||||
};
|
||||
|
||||
const emails = [];
|
||||
if (contact.email) {
|
||||
emails.push({ Address: contact.email, Name: contact.email });
|
||||
}
|
||||
if (contact.emailSecondary) {
|
||||
emails.push({ Address: contact.emailSecondary, Name: contact.emailSecondary });
|
||||
}
|
||||
if (emails.length > 0) c.EmailAddresses = emails;
|
||||
|
||||
const phones = [];
|
||||
if (contact.phoneWork) phones.push({ Type: "Business", Number: contact.phoneWork });
|
||||
if (contact.phoneMobile) phones.push({ Type: "Mobile", Number: contact.phoneMobile });
|
||||
if (contact.phoneHome) phones.push({ Type: "Home", Number: contact.phoneHome });
|
||||
if (contact.fax) phones.push({ Type: "BusinessFax", Number: contact.fax });
|
||||
if (phones.length > 0) c.Phones = phones;
|
||||
|
||||
if (contact.street || contact.city || contact.postalCode) {
|
||||
c.BusinessAddress = {
|
||||
Street: contact.street,
|
||||
City: contact.city,
|
||||
PostalCode: contact.postalCode,
|
||||
State: contact.state,
|
||||
CountryOrRegion: contact.country,
|
||||
};
|
||||
}
|
||||
|
||||
if (contact.website) {
|
||||
c.Websites = [{ Type: "Work", Address: contact.website, Name: contact.website }];
|
||||
}
|
||||
|
||||
if (contact.birthday) {
|
||||
c.Birthday = contact.birthday;
|
||||
}
|
||||
|
||||
return c;
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import { SyncProfile, SyncMapping } from "../models/types";
|
||||
|
||||
const PROFILES_KEY = "starface-sync-profiles";
|
||||
const MAPPINGS_KEY_PREFIX = "starface-sync-mappings-";
|
||||
|
||||
export class ProfileManager {
|
||||
getProfiles(): SyncProfile[] {
|
||||
try {
|
||||
const data = localStorage.getItem(PROFILES_KEY);
|
||||
return data ? JSON.parse(data) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
saveProfiles(profiles: SyncProfile[]): void {
|
||||
localStorage.setItem(PROFILES_KEY, JSON.stringify(profiles));
|
||||
}
|
||||
|
||||
getProfile(id: string): SyncProfile | null {
|
||||
return this.getProfiles().find((p) => p.id === id) || null;
|
||||
}
|
||||
|
||||
addProfile(profile: SyncProfile): void {
|
||||
const profiles = this.getProfiles();
|
||||
profiles.push(profile);
|
||||
this.saveProfiles(profiles);
|
||||
}
|
||||
|
||||
updateProfile(profile: SyncProfile): void {
|
||||
const profiles = this.getProfiles();
|
||||
const index = profiles.findIndex((p) => p.id === profile.id);
|
||||
if (index >= 0) {
|
||||
profiles[index] = profile;
|
||||
this.saveProfiles(profiles);
|
||||
}
|
||||
}
|
||||
|
||||
deleteProfile(id: string): void {
|
||||
const profiles = this.getProfiles().filter((p) => p.id !== id);
|
||||
this.saveProfiles(profiles);
|
||||
localStorage.removeItem(MAPPINGS_KEY_PREFIX + id);
|
||||
}
|
||||
|
||||
updateLastSync(profileId: string): void {
|
||||
const profiles = this.getProfiles();
|
||||
const profile = profiles.find((p) => p.id === profileId);
|
||||
if (profile) {
|
||||
profile.lastSync = new Date().toISOString();
|
||||
this.saveProfiles(profiles);
|
||||
}
|
||||
}
|
||||
|
||||
getSyncMappings(profileId: string): SyncMapping[] {
|
||||
try {
|
||||
const data = localStorage.getItem(MAPPINGS_KEY_PREFIX + profileId);
|
||||
return data ? JSON.parse(data) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
saveSyncMappings(profileId: string, mappings: SyncMapping[]): void {
|
||||
localStorage.setItem(
|
||||
MAPPINGS_KEY_PREFIX + profileId,
|
||||
JSON.stringify(mappings)
|
||||
);
|
||||
}
|
||||
|
||||
addSyncMapping(mapping: SyncMapping): void {
|
||||
const mappings = this.getSyncMappings(mapping.profileId);
|
||||
const existing = mappings.findIndex(
|
||||
(m) =>
|
||||
m.outlookId === mapping.outlookId ||
|
||||
m.starfaceId === mapping.starfaceId
|
||||
);
|
||||
if (existing >= 0) {
|
||||
mappings[existing] = mapping;
|
||||
} else {
|
||||
mappings.push(mapping);
|
||||
}
|
||||
this.saveSyncMappings(mapping.profileId, mappings);
|
||||
}
|
||||
|
||||
generateId(): string {
|
||||
return Date.now().toString(36) + Math.random().toString(36).substring(2, 9);
|
||||
}
|
||||
}
|
||||
@@ -1,358 +0,0 @@
|
||||
import {
|
||||
StarfaceConnection,
|
||||
StarfaceAddressBook,
|
||||
UnifiedContact,
|
||||
emptyContact,
|
||||
} from "../models/types";
|
||||
|
||||
interface LoginResponse {
|
||||
loginType: string;
|
||||
nonce: string;
|
||||
secret: string | null;
|
||||
}
|
||||
|
||||
interface StarfaceContactAttribute {
|
||||
displayKey: string;
|
||||
name: string;
|
||||
value: string;
|
||||
i18nDisplayName?: string;
|
||||
additionalValues?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface StarfaceContactBlock {
|
||||
name: string;
|
||||
resourceKey: string;
|
||||
attributes: StarfaceContactAttribute[];
|
||||
}
|
||||
|
||||
interface StarfaceContact {
|
||||
id: string;
|
||||
blocks: StarfaceContactBlock[];
|
||||
}
|
||||
|
||||
interface StarfaceTag {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
async function sha512(input: string): Promise<string> {
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(input);
|
||||
const hashBuffer = await crypto.subtle.digest("SHA-512", data);
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
||||
return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
export class StarfaceApiClient {
|
||||
private baseUrl: string;
|
||||
private token: string | null = null;
|
||||
private connection: StarfaceConnection;
|
||||
|
||||
constructor(connection: StarfaceConnection) {
|
||||
this.connection = connection;
|
||||
const protocol = connection.useSsl ? "https" : "http";
|
||||
const portPart =
|
||||
(connection.useSsl && connection.port === 443) ||
|
||||
(!connection.useSsl && connection.port === 80)
|
||||
? ""
|
||||
: `:${connection.port}`;
|
||||
this.baseUrl = `${protocol}://${connection.host}${portPart}/rest`;
|
||||
}
|
||||
|
||||
private headers(withAuth = true): Record<string, string> {
|
||||
const h: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
"X-Version": "2",
|
||||
};
|
||||
if (withAuth && this.token) {
|
||||
h["authToken"] = this.token;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
async login(): Promise<boolean> {
|
||||
try {
|
||||
// Step 1: get nonce
|
||||
const nonceResp = await fetch(`${this.baseUrl}/login`, {
|
||||
method: "GET",
|
||||
headers: this.headers(false),
|
||||
});
|
||||
if (!nonceResp.ok) throw new Error(`Login GET failed: ${nonceResp.status}`);
|
||||
const loginData: LoginResponse = await nonceResp.json();
|
||||
|
||||
// Step 2: calculate secret
|
||||
const { loginId, password } = this.connection;
|
||||
const passwordHash = await sha512(password);
|
||||
const combined = loginId + loginData.nonce + passwordHash;
|
||||
const combinedHash = await sha512(combined);
|
||||
const secret = `${loginId}:${combinedHash}`;
|
||||
|
||||
// Step 3: post login
|
||||
const loginResp = await fetch(`${this.baseUrl}/login`, {
|
||||
method: "POST",
|
||||
headers: this.headers(false),
|
||||
body: JSON.stringify({
|
||||
loginType: loginData.loginType,
|
||||
nonce: loginData.nonce,
|
||||
secret,
|
||||
}),
|
||||
});
|
||||
if (!loginResp.ok) throw new Error(`Login POST failed: ${loginResp.status}`);
|
||||
const tokenData = await loginResp.json();
|
||||
this.token = tokenData.token;
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error("Starface login failed:", err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async logout(): Promise<void> {
|
||||
if (!this.token) return;
|
||||
try {
|
||||
await fetch(`${this.baseUrl}/login`, {
|
||||
method: "DELETE",
|
||||
headers: this.headers(),
|
||||
});
|
||||
} finally {
|
||||
this.token = null;
|
||||
}
|
||||
}
|
||||
|
||||
async getCurrentUserId(): Promise<string | null> {
|
||||
try {
|
||||
const resp = await fetch(`${this.baseUrl}/users/me`, {
|
||||
headers: this.headers(),
|
||||
});
|
||||
if (!resp.ok) return null;
|
||||
const user = await resp.json();
|
||||
return user.id || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async getTags(): Promise<StarfaceTag[]> {
|
||||
try {
|
||||
const resp = await fetch(`${this.baseUrl}/contacts/tags`, {
|
||||
headers: this.headers(),
|
||||
});
|
||||
if (!resp.ok) return [];
|
||||
return await resp.json();
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async getAvailableAddressBooks(): Promise<StarfaceAddressBook[]> {
|
||||
const books: StarfaceAddressBook[] = [];
|
||||
|
||||
// Central address book
|
||||
books.push({
|
||||
type: "central",
|
||||
name: "Zentrales Adressbuch",
|
||||
});
|
||||
|
||||
// Current user's private address book
|
||||
const userId = await this.getCurrentUserId();
|
||||
if (userId) {
|
||||
books.push({
|
||||
type: "user",
|
||||
userId,
|
||||
name: "Persönliches Adressbuch",
|
||||
});
|
||||
}
|
||||
|
||||
// Tags as virtual address books
|
||||
const tags = await this.getTags();
|
||||
for (const tag of tags) {
|
||||
books.push({
|
||||
type: "tag",
|
||||
tagId: tag.id,
|
||||
name: `Tag: ${tag.name}`,
|
||||
});
|
||||
}
|
||||
|
||||
return books;
|
||||
}
|
||||
|
||||
async getContacts(
|
||||
addressBook: StarfaceAddressBook,
|
||||
page = 0,
|
||||
pageSize = 200
|
||||
): Promise<UnifiedContact[]> {
|
||||
const params = new URLSearchParams({
|
||||
page: page.toString(),
|
||||
pagesize: pageSize.toString(),
|
||||
});
|
||||
|
||||
if (addressBook.type === "user" && addressBook.userId) {
|
||||
params.set("userId", addressBook.userId);
|
||||
}
|
||||
if (addressBook.type === "tag" && addressBook.tagId) {
|
||||
params.set("tags", addressBook.tagId);
|
||||
}
|
||||
|
||||
const allContacts: UnifiedContact[] = [];
|
||||
let currentPage = page;
|
||||
let hasMore = true;
|
||||
|
||||
while (hasMore) {
|
||||
params.set("page", currentPage.toString());
|
||||
const resp = await fetch(`${this.baseUrl}/contacts?${params}`, {
|
||||
headers: this.headers(),
|
||||
});
|
||||
if (!resp.ok) break;
|
||||
|
||||
const contacts: StarfaceContact[] = await resp.json();
|
||||
if (contacts.length === 0) {
|
||||
hasMore = false;
|
||||
break;
|
||||
}
|
||||
|
||||
for (const sc of contacts) {
|
||||
allContacts.push(this.mapFromStarface(sc));
|
||||
}
|
||||
|
||||
if (contacts.length < pageSize) {
|
||||
hasMore = false;
|
||||
} else {
|
||||
currentPage++;
|
||||
}
|
||||
}
|
||||
|
||||
return allContacts;
|
||||
}
|
||||
|
||||
async createContact(
|
||||
contact: UnifiedContact,
|
||||
addressBook: StarfaceAddressBook
|
||||
): Promise<UnifiedContact | null> {
|
||||
const starfaceContact = this.mapToStarface(contact, addressBook);
|
||||
const params = new URLSearchParams();
|
||||
if (addressBook.type === "user" && addressBook.userId) {
|
||||
params.set("userId", addressBook.userId);
|
||||
}
|
||||
|
||||
const url = `${this.baseUrl}/contacts${params.toString() ? "?" + params : ""}`;
|
||||
const resp = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify(starfaceContact),
|
||||
});
|
||||
if (!resp.ok) return null;
|
||||
const created: StarfaceContact = await resp.json();
|
||||
return this.mapFromStarface(created);
|
||||
}
|
||||
|
||||
async updateContact(
|
||||
contactId: string,
|
||||
contact: UnifiedContact,
|
||||
addressBook: StarfaceAddressBook
|
||||
): Promise<boolean> {
|
||||
const starfaceContact = this.mapToStarface(contact, addressBook);
|
||||
starfaceContact.id = contactId;
|
||||
const params = new URLSearchParams();
|
||||
if (addressBook.type === "user" && addressBook.userId) {
|
||||
params.set("userId", addressBook.userId);
|
||||
}
|
||||
|
||||
const url = `${this.baseUrl}/contacts/${contactId}${params.toString() ? "?" + params : ""}`;
|
||||
const resp = await fetch(url, {
|
||||
method: "PUT",
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify(starfaceContact),
|
||||
});
|
||||
return resp.ok;
|
||||
}
|
||||
|
||||
async deleteContact(contactId: string): Promise<boolean> {
|
||||
const resp = await fetch(`${this.baseUrl}/contacts/${contactId}`, {
|
||||
method: "DELETE",
|
||||
headers: this.headers(),
|
||||
});
|
||||
return resp.ok;
|
||||
}
|
||||
|
||||
private mapFromStarface(sc: StarfaceContact): UnifiedContact {
|
||||
const contact = emptyContact();
|
||||
contact.starfaceId = sc.id;
|
||||
|
||||
const attrs: Record<string, string> = {};
|
||||
for (const block of sc.blocks || []) {
|
||||
for (const attr of block.attributes || []) {
|
||||
if (attr.value) {
|
||||
attrs[attr.displayKey] = attr.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
contact.firstName = attrs["NAME"] || "";
|
||||
contact.lastName = attrs["SURNAME"] || "";
|
||||
contact.company = attrs["COMPANY"] || "";
|
||||
contact.jobTitle = attrs["JOB_TITLE"] || "";
|
||||
contact.email = attrs["EMAIL"] || "";
|
||||
contact.phoneWork = attrs["OFFICE_PHONE_NUMBER"] || "";
|
||||
contact.phoneMobile = attrs["MOBILE_PHONE_NUMBER"] || "";
|
||||
contact.phoneHome = attrs["PRIVATE_PHONE_NUMBER"] || "";
|
||||
contact.fax = attrs["FAX_NUMBER"] || "";
|
||||
contact.street = attrs["STREET"] || "";
|
||||
contact.city = attrs["CITY"] || "";
|
||||
contact.postalCode = attrs["POSTAL_CODE"] || "";
|
||||
contact.state = attrs["STATE"] || "";
|
||||
contact.country = attrs["COUNTRY"] || "";
|
||||
contact.website = attrs["URL"] || "";
|
||||
contact.notes = attrs["NOTE"] || "";
|
||||
contact.salutation = attrs["SALUTATION"] || "";
|
||||
contact.title = attrs["TITLE"] || "";
|
||||
contact.birthday = attrs["BIRTHDAY"] || "";
|
||||
|
||||
return contact;
|
||||
}
|
||||
|
||||
private mapToStarface(
|
||||
contact: UnifiedContact,
|
||||
addressBook: StarfaceAddressBook
|
||||
): StarfaceContact {
|
||||
const attributes: StarfaceContactAttribute[] = [];
|
||||
|
||||
const addAttr = (displayKey: string, name: string, value: string) => {
|
||||
if (value) {
|
||||
attributes.push({ displayKey, name: name.toLowerCase(), value });
|
||||
}
|
||||
};
|
||||
|
||||
addAttr("NAME", "firstName", contact.firstName);
|
||||
addAttr("SURNAME", "lastName", contact.lastName);
|
||||
addAttr("COMPANY", "company", contact.company);
|
||||
addAttr("JOB_TITLE", "jobTitle", contact.jobTitle);
|
||||
addAttr("EMAIL", "email", contact.email);
|
||||
addAttr("OFFICE_PHONE_NUMBER", "businessPhone", contact.phoneWork);
|
||||
addAttr("MOBILE_PHONE_NUMBER", "mobilePhone", contact.phoneMobile);
|
||||
addAttr("PRIVATE_PHONE_NUMBER", "homePhone", contact.phoneHome);
|
||||
addAttr("FAX_NUMBER", "fax", contact.fax);
|
||||
addAttr("STREET", "street", contact.street);
|
||||
addAttr("CITY", "city", contact.city);
|
||||
addAttr("POSTAL_CODE", "postalCode", contact.postalCode);
|
||||
addAttr("STATE", "state", contact.state);
|
||||
addAttr("COUNTRY", "country", contact.country);
|
||||
addAttr("URL", "website", contact.website);
|
||||
addAttr("NOTE", "notes", contact.notes);
|
||||
addAttr("SALUTATION", "salutation", contact.salutation);
|
||||
addAttr("TITLE", "title", contact.title);
|
||||
addAttr("BIRTHDAY", "birthday", contact.birthday);
|
||||
|
||||
const sc: StarfaceContact = {
|
||||
id: contact.starfaceId || "",
|
||||
blocks: [
|
||||
{
|
||||
name: "contact",
|
||||
resourceKey: "contact",
|
||||
attributes,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return sc;
|
||||
}
|
||||
}
|
||||
@@ -1,296 +0,0 @@
|
||||
import {
|
||||
SyncProfile,
|
||||
SyncMapping,
|
||||
SyncResult,
|
||||
UnifiedContact,
|
||||
} from "../models/types";
|
||||
import { StarfaceApiClient } from "./starface-api";
|
||||
import { OutlookContactsService } from "./outlook-contacts";
|
||||
import { ProfileManager } from "./profile-manager";
|
||||
|
||||
/** Simple hash of contact fields for change detection */
|
||||
function hashContact(c: UnifiedContact): string {
|
||||
const fields = [
|
||||
c.firstName, c.lastName, c.company, c.jobTitle,
|
||||
c.email, c.emailSecondary,
|
||||
c.phoneWork, c.phoneMobile, c.phoneHome, c.fax,
|
||||
c.street, c.city, c.postalCode, c.state, c.country,
|
||||
c.website, c.notes, c.salutation, c.title, c.birthday,
|
||||
];
|
||||
return fields.join("|");
|
||||
}
|
||||
|
||||
/** Match contacts by name + email (since IDs differ between systems) */
|
||||
function findMatch(
|
||||
contact: UnifiedContact,
|
||||
candidates: UnifiedContact[]
|
||||
): UnifiedContact | null {
|
||||
// First try exact email match
|
||||
if (contact.email) {
|
||||
const byEmail = candidates.find(
|
||||
(c) => c.email && c.email.toLowerCase() === contact.email.toLowerCase()
|
||||
);
|
||||
if (byEmail) return byEmail;
|
||||
}
|
||||
|
||||
// Then try name match
|
||||
if (contact.firstName || contact.lastName) {
|
||||
const byName = candidates.find(
|
||||
(c) =>
|
||||
c.firstName.toLowerCase() === contact.firstName.toLowerCase() &&
|
||||
c.lastName.toLowerCase() === contact.lastName.toLowerCase() &&
|
||||
(c.firstName !== "" || c.lastName !== "")
|
||||
);
|
||||
if (byName) return byName;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export class SyncEngine {
|
||||
private outlookService: OutlookContactsService;
|
||||
private profileManager: ProfileManager;
|
||||
|
||||
constructor() {
|
||||
this.outlookService = new OutlookContactsService();
|
||||
this.profileManager = new ProfileManager();
|
||||
}
|
||||
|
||||
async syncProfile(
|
||||
profile: SyncProfile,
|
||||
onProgress?: (msg: string) => void
|
||||
): Promise<SyncResult> {
|
||||
const result: SyncResult = {
|
||||
profileId: profile.id,
|
||||
profileName: profile.name,
|
||||
timestamp: new Date().toISOString(),
|
||||
created: 0,
|
||||
updated: 0,
|
||||
deleted: 0,
|
||||
errors: [],
|
||||
direction: profile.syncDirection,
|
||||
};
|
||||
|
||||
const log = (msg: string) => {
|
||||
onProgress?.(msg);
|
||||
};
|
||||
|
||||
try {
|
||||
// Connect to Starface
|
||||
log("Verbinde mit Starface...");
|
||||
const starface = new StarfaceApiClient(profile.starfaceConnection);
|
||||
const loginOk = await starface.login();
|
||||
if (!loginOk) {
|
||||
result.errors.push("Starface-Login fehlgeschlagen");
|
||||
return result;
|
||||
}
|
||||
|
||||
// Load existing sync mappings
|
||||
const mappings = this.profileManager.getSyncMappings(profile.id);
|
||||
|
||||
// Get contacts from both systems
|
||||
log("Lade Outlook-Kontakte...");
|
||||
const outlookContacts = await this.outlookService.getContacts(
|
||||
profile.outlookFolderId
|
||||
);
|
||||
log(`${outlookContacts.length} Outlook-Kontakte geladen`);
|
||||
|
||||
log("Lade Starface-Kontakte...");
|
||||
const starfaceContacts = await starface.getContacts(
|
||||
profile.starfaceAddressBook
|
||||
);
|
||||
log(`${starfaceContacts.length} Starface-Kontakte geladen`);
|
||||
|
||||
// Build lookup maps from existing mappings
|
||||
const mappingByOutlook = new Map<string, SyncMapping>();
|
||||
const mappingByStarface = new Map<string, SyncMapping>();
|
||||
for (const m of mappings) {
|
||||
mappingByOutlook.set(m.outlookId, m);
|
||||
mappingByStarface.set(m.starfaceId, m);
|
||||
}
|
||||
|
||||
// Sync Outlook -> Starface
|
||||
if (
|
||||
profile.syncDirection === "both" ||
|
||||
profile.syncDirection === "outlook-to-starface"
|
||||
) {
|
||||
log("Synchronisiere Outlook → Starface...");
|
||||
for (const oc of outlookContacts) {
|
||||
try {
|
||||
const existingMapping = oc.outlookId
|
||||
? mappingByOutlook.get(oc.outlookId)
|
||||
: null;
|
||||
|
||||
if (existingMapping) {
|
||||
// Known contact - check if changed
|
||||
const currentHash = hashContact(oc);
|
||||
if (currentHash !== existingMapping.lastSyncHash) {
|
||||
const ok = await starface.updateContact(
|
||||
existingMapping.starfaceId,
|
||||
oc,
|
||||
profile.starfaceAddressBook
|
||||
);
|
||||
if (ok) {
|
||||
existingMapping.lastSyncHash = currentHash;
|
||||
result.updated++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// New contact - check if exists in Starface by name/email
|
||||
const match = findMatch(oc, starfaceContacts);
|
||||
if (match && match.starfaceId) {
|
||||
// Link existing
|
||||
const ok = await starface.updateContact(
|
||||
match.starfaceId,
|
||||
oc,
|
||||
profile.starfaceAddressBook
|
||||
);
|
||||
if (ok) {
|
||||
this.profileManager.addSyncMapping({
|
||||
profileId: profile.id,
|
||||
outlookId: oc.outlookId || "",
|
||||
starfaceId: match.starfaceId,
|
||||
lastSyncHash: hashContact(oc),
|
||||
});
|
||||
result.updated++;
|
||||
}
|
||||
} else {
|
||||
// Create new in Starface
|
||||
const created = await starface.createContact(
|
||||
oc,
|
||||
profile.starfaceAddressBook
|
||||
);
|
||||
if (created?.starfaceId) {
|
||||
this.profileManager.addSyncMapping({
|
||||
profileId: profile.id,
|
||||
outlookId: oc.outlookId || "",
|
||||
starfaceId: created.starfaceId,
|
||||
lastSyncHash: hashContact(oc),
|
||||
});
|
||||
result.created++;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
result.errors.push(
|
||||
`Fehler bei ${oc.firstName} ${oc.lastName}: ${err}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sync Starface -> Outlook
|
||||
if (
|
||||
profile.syncDirection === "both" ||
|
||||
profile.syncDirection === "starface-to-outlook"
|
||||
) {
|
||||
log("Synchronisiere Starface → Outlook...");
|
||||
for (const sc of starfaceContacts) {
|
||||
try {
|
||||
const existingMapping = sc.starfaceId
|
||||
? mappingByStarface.get(sc.starfaceId)
|
||||
: null;
|
||||
|
||||
if (existingMapping) {
|
||||
// Known contact - check if changed on Starface side
|
||||
const currentHash = hashContact(sc);
|
||||
if (currentHash !== existingMapping.lastSyncHash) {
|
||||
const ok = await this.outlookService.updateContact(
|
||||
existingMapping.outlookId,
|
||||
sc
|
||||
);
|
||||
if (ok) {
|
||||
existingMapping.lastSyncHash = currentHash;
|
||||
result.updated++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// New in Starface - check if exists in Outlook
|
||||
const match = findMatch(sc, outlookContacts);
|
||||
if (match && match.outlookId) {
|
||||
// Link existing
|
||||
const ok = await this.outlookService.updateContact(
|
||||
match.outlookId,
|
||||
sc
|
||||
);
|
||||
if (ok) {
|
||||
this.profileManager.addSyncMapping({
|
||||
profileId: profile.id,
|
||||
outlookId: match.outlookId,
|
||||
starfaceId: sc.starfaceId || "",
|
||||
lastSyncHash: hashContact(sc),
|
||||
});
|
||||
result.updated++;
|
||||
}
|
||||
} else {
|
||||
// Create new in Outlook
|
||||
const created = await this.outlookService.createContact(
|
||||
sc,
|
||||
profile.outlookFolderId
|
||||
);
|
||||
if (created?.outlookId) {
|
||||
this.profileManager.addSyncMapping({
|
||||
profileId: profile.id,
|
||||
outlookId: created.outlookId,
|
||||
starfaceId: sc.starfaceId || "",
|
||||
lastSyncHash: hashContact(sc),
|
||||
});
|
||||
result.created++;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
result.errors.push(
|
||||
`Fehler bei ${sc.firstName} ${sc.lastName}: ${err}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update last sync time
|
||||
this.profileManager.updateLastSync(profile.id);
|
||||
|
||||
// Save updated mappings
|
||||
this.profileManager.saveSyncMappings(profile.id, mappings);
|
||||
|
||||
// Logout
|
||||
await starface.logout();
|
||||
log("Synchronisation abgeschlossen!");
|
||||
} catch (err) {
|
||||
result.errors.push(`Allgemeiner Fehler: ${err}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async testStarfaceConnection(
|
||||
connection: import("../models/types").StarfaceConnection
|
||||
): Promise<{ success: boolean; message: string }> {
|
||||
try {
|
||||
const client = new StarfaceApiClient(connection);
|
||||
const ok = await client.login();
|
||||
if (ok) {
|
||||
await client.logout();
|
||||
return { success: true, message: "Verbindung erfolgreich!" };
|
||||
}
|
||||
return { success: false, message: "Login fehlgeschlagen" };
|
||||
} catch (err) {
|
||||
return { success: false, message: `Fehler: ${err}` };
|
||||
}
|
||||
}
|
||||
|
||||
async loadStarfaceAddressBooks(
|
||||
connection: import("../models/types").StarfaceConnection
|
||||
): Promise<import("../models/types").StarfaceAddressBook[]> {
|
||||
const client = new StarfaceApiClient(connection);
|
||||
const ok = await client.login();
|
||||
if (!ok) return [];
|
||||
const books = await client.getAvailableAddressBooks();
|
||||
await client.logout();
|
||||
return books;
|
||||
}
|
||||
|
||||
async loadOutlookFolders(): Promise<import("../models/types").OutlookContactFolder[]> {
|
||||
return this.outlookService.getContactFolders();
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import React from "react";
|
||||
import {
|
||||
Modal,
|
||||
IconButton,
|
||||
Stack,
|
||||
Text,
|
||||
} from "@fluentui/react";
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export const AboutDialog: React.FC<Props> = ({ isOpen, onClose }) => {
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onDismiss={onClose}
|
||||
isBlocking={false}
|
||||
containerClassName="about-modal"
|
||||
>
|
||||
<div className="about-dialog">
|
||||
<div className="about-header">
|
||||
<Text variant="xLarge">Info</Text>
|
||||
<IconButton
|
||||
iconProps={{ iconName: "Cancel" }}
|
||||
onClick={onClose}
|
||||
ariaLabel="Schließen"
|
||||
className="about-close-btn"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="about-content">
|
||||
<div className="about-logo">
|
||||
<Text variant="xxLarge" className="about-product-name">
|
||||
Outlook-SYNC ↔ Starface
|
||||
</Text>
|
||||
<Text variant="small" className="about-version">
|
||||
Version 0.0.0.1
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<div className="about-divider" />
|
||||
|
||||
<div className="about-company">
|
||||
<Text variant="large" block className="about-company-name">
|
||||
HackerSoft
|
||||
</Text>
|
||||
<Text variant="medium" block className="about-company-sub">
|
||||
Hacker-Net Telekommunikation
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<div className="about-address">
|
||||
<Text variant="small" block>Stefan Hacker</Text>
|
||||
<Text variant="small" block>Am Wunderburgpark 5b</Text>
|
||||
<Text variant="small" block>26135 Oldenburg</Text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
@@ -1,82 +0,0 @@
|
||||
import React, { useState } from "react";
|
||||
import { ThemeProvider, createTheme, IconButton } from "@fluentui/react";
|
||||
import { ProfileList } from "./ProfileList";
|
||||
import { ProfileEditor } from "./ProfileEditor";
|
||||
import { SyncView } from "./SyncView";
|
||||
import { AboutDialog } from "./AboutDialog";
|
||||
import { SyncProfile } from "../../models/types";
|
||||
|
||||
const theme = createTheme({
|
||||
palette: {
|
||||
themePrimary: "#0078d4",
|
||||
themeDark: "#005a9e",
|
||||
neutralLight: "#f3f2f1",
|
||||
},
|
||||
});
|
||||
|
||||
type View = "list" | "edit" | "sync";
|
||||
|
||||
export const App: React.FC = () => {
|
||||
const [view, setView] = useState<View>("list");
|
||||
const [editProfile, setEditProfile] = useState<SyncProfile | null>(null);
|
||||
const [syncProfileId, setSyncProfileId] = useState<string | null>(null);
|
||||
const [showAbout, setShowAbout] = useState(false);
|
||||
|
||||
const handleNewProfile = () => {
|
||||
setEditProfile(null);
|
||||
setView("edit");
|
||||
};
|
||||
|
||||
const handleEditProfile = (profile: SyncProfile) => {
|
||||
setEditProfile(profile);
|
||||
setView("edit");
|
||||
};
|
||||
|
||||
const handleSync = (profileId: string) => {
|
||||
setSyncProfileId(profileId);
|
||||
setView("sync");
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
setView("list");
|
||||
setEditProfile(null);
|
||||
setSyncProfileId(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeProvider theme={theme}>
|
||||
<div className="app-container">
|
||||
<header className="app-header">
|
||||
<h1>Starface Kontakt-Sync</h1>
|
||||
<IconButton
|
||||
iconProps={{ iconName: "Info" }}
|
||||
title="Info"
|
||||
ariaLabel="Info"
|
||||
onClick={() => setShowAbout(true)}
|
||||
className="header-info-btn"
|
||||
/>
|
||||
</header>
|
||||
<AboutDialog isOpen={showAbout} onClose={() => setShowAbout(false)} />
|
||||
<main className="app-main">
|
||||
{view === "list" && (
|
||||
<ProfileList
|
||||
onNew={handleNewProfile}
|
||||
onEdit={handleEditProfile}
|
||||
onSync={handleSync}
|
||||
/>
|
||||
)}
|
||||
{view === "edit" && (
|
||||
<ProfileEditor
|
||||
profile={editProfile}
|
||||
onSave={handleBack}
|
||||
onCancel={handleBack}
|
||||
/>
|
||||
)}
|
||||
{view === "sync" && syncProfileId && (
|
||||
<SyncView profileId={syncProfileId} onBack={handleBack} />
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
</ThemeProvider>
|
||||
);
|
||||
};
|
||||
@@ -1,355 +0,0 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import {
|
||||
PrimaryButton,
|
||||
DefaultButton,
|
||||
TextField,
|
||||
Dropdown,
|
||||
IDropdownOption,
|
||||
Stack,
|
||||
Text,
|
||||
Toggle,
|
||||
Spinner,
|
||||
SpinnerSize,
|
||||
MessageBar,
|
||||
MessageBarType,
|
||||
} from "@fluentui/react";
|
||||
import {
|
||||
SyncProfile,
|
||||
StarfaceConnection,
|
||||
StarfaceAddressBook,
|
||||
OutlookContactFolder,
|
||||
} from "../../models/types";
|
||||
import { ProfileManager } from "../../services/profile-manager";
|
||||
import { SyncEngine } from "../../services/sync-engine";
|
||||
|
||||
interface Props {
|
||||
profile: SyncProfile | null;
|
||||
onSave: () => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
const defaultConnection: StarfaceConnection = {
|
||||
host: "",
|
||||
port: 443,
|
||||
useSsl: true,
|
||||
loginId: "",
|
||||
password: "",
|
||||
};
|
||||
|
||||
export const ProfileEditor: React.FC<Props> = ({
|
||||
profile,
|
||||
onSave,
|
||||
onCancel,
|
||||
}) => {
|
||||
const pm = new ProfileManager();
|
||||
const engine = new SyncEngine();
|
||||
const isNew = !profile;
|
||||
|
||||
const [name, setName] = useState(profile?.name || "");
|
||||
const [connection, setConnection] = useState<StarfaceConnection>(
|
||||
profile?.starfaceConnection || { ...defaultConnection }
|
||||
);
|
||||
const [addressBooks, setAddressBooks] = useState<StarfaceAddressBook[]>([]);
|
||||
const [selectedBook, setSelectedBook] = useState<StarfaceAddressBook | null>(
|
||||
profile?.starfaceAddressBook || null
|
||||
);
|
||||
const [outlookFolders, setOutlookFolders] = useState<OutlookContactFolder[]>(
|
||||
[]
|
||||
);
|
||||
const [selectedFolderId, setSelectedFolderId] = useState(
|
||||
profile?.outlookFolderId || ""
|
||||
);
|
||||
const [syncDirection, setSyncDirection] = useState<SyncProfile["syncDirection"]>(
|
||||
profile?.syncDirection || "both"
|
||||
);
|
||||
const [enabled, setEnabled] = useState(profile?.enabled ?? true);
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [testResult, setTestResult] = useState<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
} | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
// Load Outlook folders on mount
|
||||
useEffect(() => {
|
||||
loadOutlookFolders();
|
||||
}, []);
|
||||
|
||||
const loadOutlookFolders = async () => {
|
||||
try {
|
||||
const folders = await engine.loadOutlookFolders();
|
||||
setOutlookFolders(folders);
|
||||
if (!selectedFolderId && folders.length > 0) {
|
||||
setSelectedFolderId(folders[0].id);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to load Outlook folders:", err);
|
||||
// Provide a default folder option
|
||||
setOutlookFolders([{ id: "default", displayName: "Kontakte (Standard)" }]);
|
||||
if (!selectedFolderId) setSelectedFolderId("default");
|
||||
}
|
||||
};
|
||||
|
||||
const handleTestConnection = async () => {
|
||||
setLoading(true);
|
||||
setTestResult(null);
|
||||
const result = await engine.testStarfaceConnection(connection);
|
||||
setTestResult(result);
|
||||
if (!result.success && result.message.toLowerCase().includes("fetch")) {
|
||||
result.message +=
|
||||
"\n\nMögliche Ursache: Das SSL-Zertifikat der Starface ist nicht vertrauenswürdig. " +
|
||||
"Bitte als Administrator ausführen:\n" +
|
||||
`import-cert.ps1 -StarfaceHost ${connection.host} -Port ${connection.port}`;
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleLoadAddressBooks = async () => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const books = await engine.loadStarfaceAddressBooks(connection);
|
||||
setAddressBooks(books);
|
||||
if (books.length > 0 && !selectedBook) {
|
||||
setSelectedBook(books[0]);
|
||||
}
|
||||
if (books.length === 0) {
|
||||
setError("Keine Adressbücher gefunden");
|
||||
}
|
||||
} catch (err) {
|
||||
setError(`Fehler: ${err}`);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (!name.trim()) {
|
||||
setError("Bitte einen Profilnamen eingeben");
|
||||
return;
|
||||
}
|
||||
if (!connection.host.trim()) {
|
||||
setError("Bitte Starface-Host eingeben");
|
||||
return;
|
||||
}
|
||||
if (!selectedBook) {
|
||||
setError("Bitte ein Starface-Adressbuch auswählen");
|
||||
return;
|
||||
}
|
||||
if (!selectedFolderId) {
|
||||
setError("Bitte einen Outlook-Ordner auswählen");
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedFolder = outlookFolders.find(
|
||||
(f) => f.id === selectedFolderId
|
||||
);
|
||||
|
||||
const newProfile: SyncProfile = {
|
||||
id: profile?.id || pm.generateId(),
|
||||
name: name.trim(),
|
||||
starfaceConnection: connection,
|
||||
starfaceAddressBook: selectedBook,
|
||||
outlookFolderId: selectedFolderId,
|
||||
outlookFolderName:
|
||||
selectedFolder?.displayName || "Kontakte",
|
||||
syncDirection,
|
||||
lastSync: profile?.lastSync,
|
||||
enabled,
|
||||
};
|
||||
|
||||
if (isNew) {
|
||||
pm.addProfile(newProfile);
|
||||
} else {
|
||||
pm.updateProfile(newProfile);
|
||||
}
|
||||
|
||||
onSave();
|
||||
};
|
||||
|
||||
const directionOptions: IDropdownOption[] = [
|
||||
{ key: "both", text: "Bidirektional (↔)" },
|
||||
{ key: "outlook-to-starface", text: "Outlook → Starface" },
|
||||
{ key: "starface-to-outlook", text: "Starface → Outlook" },
|
||||
];
|
||||
|
||||
const bookOptions: IDropdownOption[] = addressBooks.map((b, i) => ({
|
||||
key: i.toString(),
|
||||
text: b.name,
|
||||
data: b,
|
||||
}));
|
||||
|
||||
const folderOptions: IDropdownOption[] = outlookFolders.map((f) => ({
|
||||
key: f.id,
|
||||
text: f.displayName,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="profile-editor">
|
||||
<Stack tokens={{ childrenGap: 16 }}>
|
||||
<Stack horizontal horizontalAlign="space-between" verticalAlign="center">
|
||||
<Text variant="xLarge">
|
||||
{isNew ? "Neues Profil" : "Profil bearbeiten"}
|
||||
</Text>
|
||||
<DefaultButton text="Zurück" onClick={onCancel} />
|
||||
</Stack>
|
||||
|
||||
{error && (
|
||||
<MessageBar
|
||||
messageBarType={MessageBarType.error}
|
||||
onDismiss={() => setError("")}
|
||||
>
|
||||
{error}
|
||||
</MessageBar>
|
||||
)}
|
||||
|
||||
<TextField
|
||||
label="Profilname"
|
||||
value={name}
|
||||
onChange={(_, v) => setName(v || "")}
|
||||
placeholder="z.B. Firmenkontakte Hauptanlage"
|
||||
required
|
||||
/>
|
||||
|
||||
<Text variant="large" className="section-title">
|
||||
Starface-Verbindung
|
||||
</Text>
|
||||
|
||||
<Stack horizontal tokens={{ childrenGap: 8 }}>
|
||||
<Stack.Item grow>
|
||||
<TextField
|
||||
label="Host / IP-Adresse"
|
||||
value={connection.host}
|
||||
onChange={(_, v) =>
|
||||
setConnection({ ...connection, host: v || "" })
|
||||
}
|
||||
placeholder="z.B. pbx.firma.de oder 192.168.1.100"
|
||||
required
|
||||
/>
|
||||
</Stack.Item>
|
||||
<TextField
|
||||
label="Port"
|
||||
value={connection.port.toString()}
|
||||
onChange={(_, v) =>
|
||||
setConnection({ ...connection, port: parseInt(v || "443") || 443 })
|
||||
}
|
||||
styles={{ root: { width: 80 } }}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Toggle
|
||||
label="HTTPS verwenden"
|
||||
checked={connection.useSsl}
|
||||
onChange={(_, checked) =>
|
||||
setConnection({
|
||||
...connection,
|
||||
useSsl: checked ?? true,
|
||||
port: checked ? 443 : 80,
|
||||
})
|
||||
}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
label="Login-ID"
|
||||
value={connection.loginId}
|
||||
onChange={(_, v) =>
|
||||
setConnection({ ...connection, loginId: v || "" })
|
||||
}
|
||||
required
|
||||
/>
|
||||
|
||||
<TextField
|
||||
label="Kennwort"
|
||||
type="password"
|
||||
value={connection.password}
|
||||
onChange={(_, v) =>
|
||||
setConnection({ ...connection, password: v || "" })
|
||||
}
|
||||
canRevealPassword
|
||||
required
|
||||
/>
|
||||
|
||||
<Stack horizontal tokens={{ childrenGap: 8 }}>
|
||||
<DefaultButton
|
||||
text="Verbindung testen"
|
||||
onClick={handleTestConnection}
|
||||
disabled={loading || !connection.host || !connection.loginId}
|
||||
/>
|
||||
<PrimaryButton
|
||||
text="Adressbücher laden"
|
||||
onClick={handleLoadAddressBooks}
|
||||
disabled={loading || !connection.host || !connection.loginId}
|
||||
/>
|
||||
{loading && <Spinner size={SpinnerSize.small} />}
|
||||
</Stack>
|
||||
|
||||
{testResult && (
|
||||
<MessageBar
|
||||
messageBarType={
|
||||
testResult.success
|
||||
? MessageBarType.success
|
||||
: MessageBarType.error
|
||||
}
|
||||
>
|
||||
{testResult.message.split("\n").map((line, i) => (
|
||||
<span key={i}>
|
||||
{i > 0 && <br />}
|
||||
{line}
|
||||
</span>
|
||||
))}
|
||||
</MessageBar>
|
||||
)}
|
||||
|
||||
{addressBooks.length > 0 && (
|
||||
<Dropdown
|
||||
label="Starface-Adressbuch"
|
||||
options={bookOptions}
|
||||
selectedKey={
|
||||
selectedBook
|
||||
? addressBooks.indexOf(selectedBook).toString()
|
||||
: undefined
|
||||
}
|
||||
onChange={(_, option) => {
|
||||
if (option?.data) setSelectedBook(option.data);
|
||||
}}
|
||||
required
|
||||
/>
|
||||
)}
|
||||
|
||||
<Text variant="large" className="section-title">
|
||||
Outlook-Einstellungen
|
||||
</Text>
|
||||
|
||||
<Dropdown
|
||||
label="Outlook Kontakte-Ordner"
|
||||
options={folderOptions}
|
||||
selectedKey={selectedFolderId}
|
||||
onChange={(_, option) => {
|
||||
if (option) setSelectedFolderId(option.key as string);
|
||||
}}
|
||||
required
|
||||
/>
|
||||
|
||||
<Dropdown
|
||||
label="Synchronisationsrichtung"
|
||||
options={directionOptions}
|
||||
selectedKey={syncDirection}
|
||||
onChange={(_, option) => {
|
||||
if (option) setSyncDirection(option.key as SyncProfile["syncDirection"]);
|
||||
}}
|
||||
/>
|
||||
|
||||
<Toggle
|
||||
label="Profil aktiviert"
|
||||
checked={enabled}
|
||||
onChange={(_, checked) => setEnabled(checked ?? true)}
|
||||
/>
|
||||
|
||||
<Stack horizontal tokens={{ childrenGap: 8 }}>
|
||||
<PrimaryButton text="Speichern" onClick={handleSave} />
|
||||
<DefaultButton text="Abbrechen" onClick={onCancel} />
|
||||
</Stack>
|
||||
</Stack>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,138 +0,0 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import {
|
||||
PrimaryButton,
|
||||
DefaultButton,
|
||||
IconButton,
|
||||
Stack,
|
||||
Text,
|
||||
MessageBar,
|
||||
MessageBarType,
|
||||
Toggle,
|
||||
} from "@fluentui/react";
|
||||
import { SyncProfile } from "../../models/types";
|
||||
import { ProfileManager } from "../../services/profile-manager";
|
||||
|
||||
interface Props {
|
||||
onNew: () => void;
|
||||
onEdit: (profile: SyncProfile) => void;
|
||||
onSync: (profileId: string) => void;
|
||||
}
|
||||
|
||||
export const ProfileList: React.FC<Props> = ({ onNew, onEdit, onSync }) => {
|
||||
const [profiles, setProfiles] = useState<SyncProfile[]>([]);
|
||||
const pm = new ProfileManager();
|
||||
|
||||
useEffect(() => {
|
||||
setProfiles(pm.getProfiles());
|
||||
}, []);
|
||||
|
||||
const handleDelete = (id: string) => {
|
||||
if (confirm("Profil wirklich löschen?")) {
|
||||
pm.deleteProfile(id);
|
||||
setProfiles(pm.getProfiles());
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggle = (id: string, enabled: boolean) => {
|
||||
const profile = pm.getProfile(id);
|
||||
if (profile) {
|
||||
profile.enabled = enabled;
|
||||
pm.updateProfile(profile);
|
||||
setProfiles(pm.getProfiles());
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (iso?: string) => {
|
||||
if (!iso) return "Noch nie";
|
||||
return new Date(iso).toLocaleString("de-DE");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="profile-list">
|
||||
<Stack tokens={{ childrenGap: 12 }}>
|
||||
<Stack horizontal horizontalAlign="space-between" verticalAlign="center">
|
||||
<Text variant="xLarge">Sync-Profile</Text>
|
||||
<PrimaryButton
|
||||
text="Neues Profil"
|
||||
iconProps={{ iconName: "Add" }}
|
||||
onClick={onNew}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
{profiles.length === 0 && (
|
||||
<MessageBar messageBarType={MessageBarType.info}>
|
||||
Noch keine Sync-Profile angelegt. Erstellen Sie ein neues Profil, um
|
||||
Kontakte zu synchronisieren.
|
||||
</MessageBar>
|
||||
)}
|
||||
|
||||
{profiles.map((profile) => (
|
||||
<div key={profile.id} className="profile-card">
|
||||
<Stack tokens={{ childrenGap: 8 }}>
|
||||
<Stack
|
||||
horizontal
|
||||
horizontalAlign="space-between"
|
||||
verticalAlign="center"
|
||||
>
|
||||
<Text variant="large" className="profile-name">
|
||||
{profile.name}
|
||||
</Text>
|
||||
<Toggle
|
||||
checked={profile.enabled}
|
||||
onChange={(_, checked) =>
|
||||
handleToggle(profile.id, checked ?? false)
|
||||
}
|
||||
onText="Aktiv"
|
||||
offText="Inaktiv"
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<div className="profile-details">
|
||||
<Text variant="small" block>
|
||||
<strong>Starface:</strong>{" "}
|
||||
{profile.starfaceConnection.host} →{" "}
|
||||
{profile.starfaceAddressBook.name}
|
||||
</Text>
|
||||
<Text variant="small" block>
|
||||
<strong>Outlook:</strong> {profile.outlookFolderName}
|
||||
</Text>
|
||||
<Text variant="small" block>
|
||||
<strong>Richtung:</strong>{" "}
|
||||
{profile.syncDirection === "both"
|
||||
? "Bidirektional"
|
||||
: profile.syncDirection === "outlook-to-starface"
|
||||
? "Outlook → Starface"
|
||||
: "Starface → Outlook"}
|
||||
</Text>
|
||||
<Text variant="small" block>
|
||||
<strong>Letzte Sync:</strong>{" "}
|
||||
{formatDate(profile.lastSync)}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<Stack horizontal tokens={{ childrenGap: 8 }}>
|
||||
<PrimaryButton
|
||||
text="Jetzt synchronisieren"
|
||||
iconProps={{ iconName: "Sync" }}
|
||||
onClick={() => onSync(profile.id)}
|
||||
disabled={!profile.enabled}
|
||||
/>
|
||||
<DefaultButton
|
||||
text="Bearbeiten"
|
||||
iconProps={{ iconName: "Edit" }}
|
||||
onClick={() => onEdit(profile)}
|
||||
/>
|
||||
<IconButton
|
||||
iconProps={{ iconName: "Delete" }}
|
||||
title="Löschen"
|
||||
onClick={() => handleDelete(profile.id)}
|
||||
className="delete-btn"
|
||||
/>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</div>
|
||||
))}
|
||||
</Stack>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,176 +0,0 @@
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import {
|
||||
PrimaryButton,
|
||||
DefaultButton,
|
||||
Stack,
|
||||
Text,
|
||||
ProgressIndicator,
|
||||
MessageBar,
|
||||
MessageBarType,
|
||||
} from "@fluentui/react";
|
||||
import { SyncResult } from "../../models/types";
|
||||
import { ProfileManager } from "../../services/profile-manager";
|
||||
import { SyncEngine } from "../../services/sync-engine";
|
||||
|
||||
interface Props {
|
||||
profileId: string;
|
||||
onBack: () => void;
|
||||
}
|
||||
|
||||
export const SyncView: React.FC<Props> = ({ profileId, onBack }) => {
|
||||
const pm = new ProfileManager();
|
||||
const profile = pm.getProfile(profileId);
|
||||
|
||||
const [running, setRunning] = useState(false);
|
||||
const [progress, setProgress] = useState<string[]>([]);
|
||||
const [result, setResult] = useState<SyncResult | null>(null);
|
||||
const logRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const addProgress = (msg: string) => {
|
||||
setProgress((prev) => [...prev, `[${new Date().toLocaleTimeString("de-DE")}] ${msg}`]);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (logRef.current) {
|
||||
logRef.current.scrollTop = logRef.current.scrollHeight;
|
||||
}
|
||||
}, [progress]);
|
||||
|
||||
const handleSync = async () => {
|
||||
if (!profile) return;
|
||||
|
||||
setRunning(true);
|
||||
setProgress([]);
|
||||
setResult(null);
|
||||
addProgress("Synchronisation gestartet...");
|
||||
|
||||
const engine = new SyncEngine();
|
||||
const syncResult = await engine.syncProfile(profile, (msg) => {
|
||||
addProgress(msg);
|
||||
});
|
||||
|
||||
setResult(syncResult);
|
||||
setRunning(false);
|
||||
addProgress("Fertig.");
|
||||
};
|
||||
|
||||
if (!profile) {
|
||||
return (
|
||||
<MessageBar messageBarType={MessageBarType.error}>
|
||||
Profil nicht gefunden.
|
||||
<DefaultButton text="Zurück" onClick={onBack} />
|
||||
</MessageBar>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="sync-view">
|
||||
<Stack tokens={{ childrenGap: 12 }}>
|
||||
<Stack horizontal horizontalAlign="space-between" verticalAlign="center">
|
||||
<Text variant="xLarge">Synchronisation</Text>
|
||||
<DefaultButton text="Zurück" onClick={onBack} disabled={running} />
|
||||
</Stack>
|
||||
|
||||
<div className="sync-info">
|
||||
<Text variant="medium" block>
|
||||
<strong>Profil:</strong> {profile.name}
|
||||
</Text>
|
||||
<Text variant="small" block>
|
||||
{profile.starfaceConnection.host} ({profile.starfaceAddressBook.name})
|
||||
{" ↔ "}
|
||||
{profile.outlookFolderName}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
{!running && !result && (
|
||||
<PrimaryButton
|
||||
text="Synchronisation starten"
|
||||
iconProps={{ iconName: "Sync" }}
|
||||
onClick={handleSync}
|
||||
/>
|
||||
)}
|
||||
|
||||
{running && (
|
||||
<ProgressIndicator
|
||||
label="Synchronisiere..."
|
||||
description="Bitte warten..."
|
||||
/>
|
||||
)}
|
||||
|
||||
{progress.length > 0 && (
|
||||
<div className="sync-log" ref={logRef}>
|
||||
{progress.map((msg, i) => (
|
||||
<Text key={i} variant="small" block className="log-line">
|
||||
{msg}
|
||||
</Text>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="sync-result">
|
||||
{result.errors.length === 0 ? (
|
||||
<MessageBar messageBarType={MessageBarType.success}>
|
||||
Synchronisation erfolgreich abgeschlossen!
|
||||
</MessageBar>
|
||||
) : (
|
||||
<MessageBar messageBarType={MessageBarType.warning}>
|
||||
Synchronisation mit {result.errors.length} Fehler(n)
|
||||
abgeschlossen.
|
||||
</MessageBar>
|
||||
)}
|
||||
|
||||
<div className="result-stats">
|
||||
<Stack horizontal tokens={{ childrenGap: 24 }}>
|
||||
<div className="stat">
|
||||
<Text variant="xxLarge" className="stat-number">
|
||||
{result.created}
|
||||
</Text>
|
||||
<Text variant="small">Erstellt</Text>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<Text variant="xxLarge" className="stat-number">
|
||||
{result.updated}
|
||||
</Text>
|
||||
<Text variant="small">Aktualisiert</Text>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<Text variant="xxLarge" className="stat-number">
|
||||
{result.errors.length}
|
||||
</Text>
|
||||
<Text variant="small">Fehler</Text>
|
||||
</div>
|
||||
</Stack>
|
||||
</div>
|
||||
|
||||
{result.errors.length > 0 && (
|
||||
<div className="error-list">
|
||||
<Text variant="medium" block>
|
||||
<strong>Fehler:</strong>
|
||||
</Text>
|
||||
{result.errors.map((err, i) => (
|
||||
<MessageBar
|
||||
key={i}
|
||||
messageBarType={MessageBarType.error}
|
||||
className="error-item"
|
||||
>
|
||||
{err}
|
||||
</MessageBar>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Stack horizontal tokens={{ childrenGap: 8 }} className="result-actions">
|
||||
<PrimaryButton
|
||||
text="Erneut synchronisieren"
|
||||
iconProps={{ iconName: "Sync" }}
|
||||
onClick={handleSync}
|
||||
/>
|
||||
<DefaultButton text="Zurück zur Übersicht" onClick={onBack} />
|
||||
</Stack>
|
||||
</div>
|
||||
)}
|
||||
</Stack>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,16 +0,0 @@
|
||||
import React from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./components/App";
|
||||
import "./styles/taskpane.css";
|
||||
|
||||
/* global Office */
|
||||
|
||||
Office.onReady((info) => {
|
||||
if (info.host === Office.HostType.Outlook) {
|
||||
const container = document.getElementById("root");
|
||||
if (container) {
|
||||
const root = createRoot(container);
|
||||
root.render(<App />);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,259 +0,0 @@
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: "Segoe UI", -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
font-size: 14px;
|
||||
color: #323130;
|
||||
background: #faf9f8;
|
||||
}
|
||||
|
||||
.app-container {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.app-header {
|
||||
background: linear-gradient(135deg, #0078d4, #005a9e);
|
||||
color: white;
|
||||
padding: 16px 20px;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.app-header h1 {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.header-info-btn {
|
||||
color: white !important;
|
||||
background: transparent !important;
|
||||
}
|
||||
|
||||
.header-info-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.15) !important;
|
||||
}
|
||||
|
||||
/* About Dialog */
|
||||
.about-modal {
|
||||
max-width: 360px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.about-dialog {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.about-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 20px 8px;
|
||||
}
|
||||
|
||||
.about-close-btn {
|
||||
color: #605e5c !important;
|
||||
}
|
||||
|
||||
.about-content {
|
||||
padding: 0 20px 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.about-logo {
|
||||
padding: 16px 0;
|
||||
}
|
||||
|
||||
.about-product-name {
|
||||
font-weight: 700 !important;
|
||||
color: #0078d4 !important;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.about-version {
|
||||
color: #605e5c !important;
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.about-divider {
|
||||
height: 1px;
|
||||
background: #edebe9;
|
||||
margin: 16px 0;
|
||||
}
|
||||
|
||||
.about-company {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.about-company-name {
|
||||
font-weight: 700 !important;
|
||||
}
|
||||
|
||||
.about-company-sub {
|
||||
color: #605e5c !important;
|
||||
}
|
||||
|
||||
.about-address {
|
||||
color: #605e5c;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.app-main {
|
||||
padding: 16px 20px;
|
||||
}
|
||||
|
||||
/* Profile List */
|
||||
.profile-list {
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
|
||||
.profile-card {
|
||||
background: white;
|
||||
border: 1px solid #edebe9;
|
||||
border-radius: 4px;
|
||||
padding: 16px;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
|
||||
transition: box-shadow 0.15s;
|
||||
}
|
||||
|
||||
.profile-card:hover {
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.profile-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.profile-details {
|
||||
background: #f3f2f1;
|
||||
border-radius: 4px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.profile-details .ms-Text {
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.delete-btn {
|
||||
color: #a4262c !important;
|
||||
}
|
||||
|
||||
.delete-btn:hover {
|
||||
background: #fde7e9 !important;
|
||||
}
|
||||
|
||||
/* Profile Editor */
|
||||
.profile-editor {
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-weight: 600;
|
||||
margin-top: 8px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid #edebe9;
|
||||
}
|
||||
|
||||
/* Sync View */
|
||||
.sync-view {
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
|
||||
.sync-info {
|
||||
background: #f3f2f1;
|
||||
border-radius: 4px;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.sync-log {
|
||||
background: #1e1e1e;
|
||||
color: #d4d4d4;
|
||||
border-radius: 4px;
|
||||
padding: 12px;
|
||||
max-height: 250px;
|
||||
overflow-y: auto;
|
||||
font-family: "Cascadia Code", "Consolas", monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.log-line {
|
||||
padding: 1px 0;
|
||||
font-family: inherit !important;
|
||||
color: #d4d4d4 !important;
|
||||
}
|
||||
|
||||
.sync-result {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.result-stats {
|
||||
background: white;
|
||||
border: 1px solid #edebe9;
|
||||
border-radius: 4px;
|
||||
padding: 16px;
|
||||
margin: 12px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stat {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stat-number {
|
||||
color: #0078d4;
|
||||
font-weight: 700;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.error-list {
|
||||
margin: 12px 0;
|
||||
}
|
||||
|
||||
.error-item {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.result-actions {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
/* Animations */
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(4px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Scrollbar */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #c8c6c4;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: #a19f9d;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Starface Kontakt-Sync</title>
|
||||
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user