using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Forms; using System.Windows.Input; using System.Windows.Media; using System.Windows.Navigation; using System.Windows.Threading; using ChatController.ChatKlassen; using ChatController.HauptKlassen; using ChatController.LoginKlassen; using ChatController.Utilities; using ChatController.Utilities.Extensions; using Button = System.Windows.Controls.Button; using Cursors = System.Windows.Input.Cursors; using DataFormats = System.Windows.DataFormats; using KeyEventArgs = System.Windows.Input.KeyEventArgs; using MenuItem = System.Windows.Controls.MenuItem; using MessageBox = System.Windows.MessageBox; using Orientation = System.Windows.Controls.Orientation; using Panel = System.Windows.Controls.Panel; using Path = System.IO.Path; using ScrollBar = System.Windows.Controls.Primitives.ScrollBar; using Timer = System.Windows.Forms.Timer; namespace ChatController { public partial class ChatMainControl { private readonly Dictionary _Group2NotifyIcons = new Dictionary(); private readonly Dictionary _GroupId2DateTime = new Dictionary(); private Window _ContainingWindow; public Window ContainingWindow { get => _ContainingWindow; set { _ContainingWindow = value; if(value != null) { _ContainingWindow.Deactivated += ContainingWindowOnDeactivated; _ContainingWindow.Activated += ContainingWindowOnActivated; } } } private Chat _Chat; private CurrentContact _CurrentContact; private bool _IsChatBoxOnFocus; private IOrderedEnumerable _ContactList; private bool _ScrollPrueferAktivieren; public bool ShouldInterruptContactsThread = true; private readonly List _CreatedTempFiles = new List(); private readonly Dictionary> _MenuItemName2Callback = new Dictionary>(); private bool _IsDesktopVersion = true; private bool _IsInBackground; public ChatMainControl() { InitializeComponent(); ReloadGruppen.Visibility = Visibility.Collapsed; } private void ContainingWindowOnDeactivated(object sender, EventArgs e) { _IsInBackground = true; } private void ContainingWindowOnActivated(object sender, EventArgs e) { _IsInBackground = false; } public void InitMitChatdaten(ChatDatenUebergabe cdu) { _Chat = new Chat(cdu); _ContactList = _Chat.AddContacts(); Clientlist.ItemsSource = _ContactList; ReadNewSyncFile(); foreach (var contact in _ContactList) { if (_GroupId2DateTime.ContainsKey(contact.GroupId)) { var dateTimeFromFile = _GroupId2DateTime[contact.GroupId].TimeStamp; var isUnread = _GroupId2DateTime[contact.GroupId].IsUnread; var isYounger = contact.TimeStamp > dateTimeFromFile; contact.IsNewMessage = isUnread; contact.HasUnreadMessages = contact.IsNewMessage; } } var view = (CollectionView) CollectionViewSource.GetDefaultView(Clientlist.ItemsSource); view.Filter = UserFilter; GlobalListeningThreadtimer?.Stop(); GlobalListeningThreadtimer = null; InitGlobalListeningThread(); Clientlist.Items.Refresh(); } public void ShowNotification(string pTitle, string pMessage, int pGroupId) { if (!_Group2NotifyIcons.ContainsKey(pGroupId)) { var notificationIcon = Resource.ownchat_favicon; var contact = _ContactList.FirstOrDefault(a => a.GroupId == pGroupId); if(contact != null) { notificationIcon = Utils.ImageSourceToIcon(contact.Image); } var notifyIcon = new NotifyIcon { Icon = notificationIcon, Visible = true }; notifyIcon.BalloonTipClicked += (sender, args) => { DisposeAndRemoveNotification((NotifyIcon)sender, pGroupId); if (_ContainingWindow.WindowState == WindowState.Minimized) { _ContainingWindow.WindowState = WindowState.Normal; } _ContainingWindow.Activate(); SelectContact(_ContactList.FirstOrDefault(f => f.GroupId.Equals(pGroupId))); }; notifyIcon.BalloonTipClosed += (sender, args) => { DisposeAndRemoveNotification((NotifyIcon)sender, pGroupId); }; _Group2NotifyIcons.Add(pGroupId, notifyIcon); } _Group2NotifyIcons[pGroupId].ShowBalloonTip(Constants.NotificationTimeout, pTitle, pMessage, ToolTipIcon.None); } public void ClearNotifications() { foreach(var group2NotifyIcon in _Group2NotifyIcons) { group2NotifyIcon.Value.Dispose(); } _Group2NotifyIcons.Clear(); } private void DisposeAndRemoveNotification(IDisposable pNotification, long pGroupId) { pNotification.Dispose(); _Group2NotifyIcons.Remove(pGroupId); } public void ResetStyle() { EmojiButton.Style = null; MediaButton.Style = null; ReloadGruppen.Visibility = Visibility.Visible; _IsDesktopVersion = false; } private void AktChatUser_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) { _Chat.ShowProfilePicture(_CurrentContact); } private void Clientlist_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if(Clientlist.SelectedItem != null) { SelectContact((Contact) Clientlist.SelectedItem); } } private void SelectContact(Contact pContact) { if(pContact == null) { return; } ShouldInterruptContactsThread = true; Cursor = Cursors.Wait; _ScrollPrueferAktivieren = false; AktChatUserList.Items.Clear(); if (pContact.HasUnreadMessages) { pContact.HasUnreadMessages = false; Clientlist.Items.Refresh(); } var currentContact = new CurrentContact(pContact); pContact.IsNewMessage = false; var shouldChangeIcon = _ContactList.Any(contact => contact.IsNewMessage); if(shouldChangeIcon) { ContainingWindow.Icon = Utils.GetImageSourceFromIcon(Resource.ownchat_favicon); } AktChatUserList.Items.Add(currentContact); _CurrentContact = currentContact; if(Clientlist.Items.Contains(pContact)) { Clientlist.SelectedItem = pContact; } var chatMessages = _Chat.LoadChatMessagesForContact(currentContact); ChatListBox.ItemsSource = chatMessages; if (VisualTreeHelper.GetChildrenCount(ChatListBox) > 0) { var border = (Border) VisualTreeHelper.GetChild(ChatListBox, 0); var scrollViewer = (ScrollViewer) VisualTreeHelper.GetChild(border, 0); scrollViewer.ScrollToBottom(); } ChatListBox.ContextMenu = _Chat.ErstelleKontextMenue(); SetContextHandler(); _ScrollPrueferAktivieren = true; ListenForMessages(); Cursor = Cursors.Arrow; WriteToNewSyncFile(); ShouldInterruptContactsThread = false; } private void SetContextHandler() { var contextItems = ChatListBox?.ContextMenu?.Items; foreach (var menuItemText in _MenuItemName2Callback.Keys) { var cb = _MenuItemName2Callback[menuItemText]; var menuItem = new MenuItem(); menuItem.Click += (s, e2) => { cb(menuItemText); }; menuItem.Header = menuItemText; contextItems.Add(menuItem); } var item2 = (MenuItem)contextItems[0]; item2.Click += Item2OnClick; // umbenenen in Speichern unter var item3 = (MenuItem)contextItems[1]; item3.Click += Item3OnClick; //Umbenenen in Einfügen // neu und vor Einfügen setzen und anpassen var item4 = (MenuItem) contextItems[2]; item4.Click += Item4OnClick; //Umbenenen in Kopieren } private void Item2OnClick(object sender, RoutedEventArgs routedEventArgs) { foreach (var items in ChatListBox.SelectedItems) { var item = (ChatMessage)items; _Chat.SaveFileAs(item); } } private void Item3OnClick(object sender, RoutedEventArgs routedEventArgs) { var kontakt = (CurrentContact)AktChatUserList.Items[0]; _Chat.Paste(kontakt.GroupId,this); } private void Item4OnClick(object sender, RoutedEventArgs routedEventArgs) { string chatmessages = ""; foreach (var items in ChatListBox.SelectedItems) { var item = (ChatMessage)items; chatmessages += item.UserMessage + "\n"; } if(!chatmessages.Equals("")) _Chat.Copy(chatmessages, 1); } private void Chat_OnContextMenuOpening(object sender, ContextMenuEventArgs e) { var chatItems = ChatListBox.SelectedItems; if (chatItems.Count > 0) { foreach (var items in chatItems) { var item = items as ChatMessage; if (item != null && item.ImageSources != null) { var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem)contextItems[0]; ContextItemSpeichernUnter.Visibility = Visibility.Visible; } else { var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem)contextItems[0]; ContextItemSpeichernUnter.Visibility = Visibility.Collapsed; } if (item.ImageSources == null && item.FilePath == null) { var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem) contextItems[2]; ContextItemSpeichernUnter.Visibility = Visibility.Visible; } else { var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem)contextItems[2]; ContextItemSpeichernUnter.Visibility = Visibility.Collapsed; } } } else { //Schalte speichern unter Aus var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem)contextItems[0]; ContextItemSpeichernUnter.Visibility = Visibility.Collapsed; } //prüfe ob was in dem Speicher vorhanden ist //Einfügen var d = System.Windows.Forms.Clipboard.GetDataObject(); if (d.GetDataPresent(DataFormats.FileDrop)) { var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem)contextItems[1]; ContextItemSpeichernUnter.Visibility = Visibility.Visible; } else if (d.GetDataPresent(DataFormats.Text)) { var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem)contextItems[1]; ContextItemSpeichernUnter.Visibility = Visibility.Visible; } else if (d.GetDataPresent(DataFormats.Bitmap)) { var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem)contextItems[1]; ContextItemSpeichernUnter.Visibility = Visibility.Visible; } else { var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem)contextItems[1]; ContextItemSpeichernUnter.Visibility = Visibility.Collapsed; } //prüfe ob dokumentation erlaubt var kontakt = (CurrentContact)AktChatUserList.Items[0]; if (kontakt.UserIdManage == null && ChatListBox.ContextMenu.Items.Count > 3) { var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem)contextItems[3]; ContextItemSpeichernUnter.Visibility = Visibility.Collapsed; } else if (ChatListBox.ContextMenu.Items.Count > 3) { var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem)contextItems[3]; ContextItemSpeichernUnter.Visibility = Visibility.Visible; } if (ChatListBox.ContextMenu.Items.Count == 0) { ChatListBox.ContextMenu.Visibility = Visibility.Collapsed; } } private void MediaButton_OnClick(object sender, RoutedEventArgs e) { if (AktChatUserList.Items.Count > 0) { var kontakt = (CurrentContact)AktChatUserList.Items[0]; var medium = _Chat.OpenFile(); if(medium != null) { string convertetMedia = _Chat.ScaleImage(medium, Path.GetExtension(medium.ToUpperInvariant())); if (!convertetMedia.Equals("")) { _Chat.AddNewFile(convertetMedia,medium,kontakt.GroupId); CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); ChatListBox.Items.MoveCurrentToLast(); ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); _Chat.SendFileToContact(kontakt, convertetMedia,medium); if (!convertetMedia.Equals("") && !convertetMedia.Equals(medium) && File.Exists(convertetMedia)) { File.Delete(convertetMedia); } } else { MessageBox.Show("Die gewählte Datei ist zu groß!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Exclamation); } } } else { MessageBox.Show("Bitte wählen Sie einen Kontakt aus.","ownChat",MessageBoxButton.OK, MessageBoxImage.Information); } } private void SendButton_OnClick(object sender, RoutedEventArgs e) { if (!AktChatUserList.Items.IsEmpty && !Chatbox.Text.Equals("") && _IsChatBoxOnFocus) { if (!Chatbox.Text.Equals("")) { var kontakt = (CurrentContact)AktChatUserList.Items[0]; _Chat.AddNewMessage(Chatbox.Text, kontakt.GroupId); CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); ChatListBox.Items.MoveCurrentToLast(); ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); _Chat.SendMessage(Chatbox.Text, kontakt.GroupId); Chatbox.Text = ""; if (Chatbox.Text.Equals("")) { Chatbox.Text = "Nachricht schreiben"; Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray); _IsChatBoxOnFocus = false; } } } else { if (AktChatUserList.Items.IsEmpty) { MessageBox.Show("Bitte wählen Sie einen Chatpartner aus.", "Fehler", MessageBoxButton.OK); if (string.IsNullOrEmpty(Chatbox.Text)) { Chatbox.Text = "Nachricht schreiben"; Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray); _IsChatBoxOnFocus = false; } } else if (string.IsNullOrEmpty(Chatbox.Text)) { MessageBox.Show("Sie können keine leere Nachricht verschicken.", "Fehler", MessageBoxButton.OK); Chatbox.Text = "Nachricht schreiben"; Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray); _IsChatBoxOnFocus = false; } } } private void Chatbox_OnGotFocus(object sender, RoutedEventArgs e) { if (Chatbox.Text.Equals("Nachricht schreiben")) { Chatbox.Text = ""; Chatbox.Foreground = new SolidColorBrush(Colors.Black); _IsChatBoxOnFocus = true; } } private void Chatbox_OnKeyDownHandler(object sender, KeyEventArgs e) { try { if (e.Key == Key.Return) { if (!AktChatUserList.Items.IsEmpty && !Chatbox.Text.Equals("")) { var kontakt = (CurrentContact)AktChatUserList.Items[0]; _Chat.AddNewMessage(Chatbox.Text, kontakt.GroupId); CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); ChatListBox.Items.MoveCurrentToLast(); ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); _Chat.SendMessage(Chatbox.Text, kontakt.GroupId); Chatbox.Text = ""; } else { if (AktChatUserList.Items.IsEmpty) { MessageBox.Show("Bitte wählen Sie einen Chatpartner aus.", "Fehler", MessageBoxButton.OK); } else if (Chatbox.Text.Equals("")) { MessageBox.Show("Sie können keine lehre Nachricht verschicken.", "Fehler", MessageBoxButton.OK); } } } } catch (Exception ed) { MessageBox.Show("Beim Senden einer Nachricht ist ein Fehler aufgetreten. " + ed.Message + "\n" + ed.StackTrace, "Fehler", MessageBoxButton.OK); } } public delegate void EmojiiDelegate(Button button); public event EmojiiDelegate OnEmojii; private void EmojiButton_OnClick(object sender, RoutedEventArgs e) { //hier wie bei login if (OnEmojii != null) { OnEmojii(EmojiButton); } } private void Chat_OnScrollChanged(object sender, ScrollChangedEventArgs e) { var scrollBarList = GetVisualChildCollection(ChatListBox); foreach (var scrollBar in scrollBarList) { if (scrollBar.Orientation == Orientation.Horizontal) { _ScrollPrueferAktivieren = true; } else { scrollBar.ValueChanged += VerticalScrollbarChanged; } } } private void VerticalScrollbarChanged(object sender, RoutedPropertyChangedEventArgs routedPropertyChangedEventArgs) { if (_ScrollPrueferAktivieren == true) { var x = (ScrollBar) sender; if (x.Value > 0) { //nix } else { Cursor = Cursors.Wait; //StartWaiting(); _ScrollPrueferAktivieren = false; ChatListBox.Items.MoveCurrentToFirst(); ChatMessage item = ChatListBox.Items.CurrentItem as ChatMessage; ChatListBox.ItemsSource = null; var kontakt = (Contact)Clientlist.SelectedItem; var xy = _Chat.LoadMoreMessages(kontakt); ChatListBox.ItemsSource = xy; ChatListBox.ScrollIntoView(item); //EndWaiting(); Cursor = Cursors.Arrow; } } } private static List GetVisualChildCollection(object parent) where T : Visual { var visualCollection = new List(); GetVisualChildCollection(parent as DependencyObject, visualCollection); return visualCollection; } private static void GetVisualChildCollection(DependencyObject parent, ICollection visualCollection) where T : Visual { var count = VisualTreeHelper.GetChildrenCount(parent); for (var i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(parent, i); if (child is T item) { visualCollection.Add(item); } else { GetVisualChildCollection(child, visualCollection); } } } private void ListenForMessages() { _ListeningThreadTimer?.Stop(); _ListeningThreadTimer = null; InitListeningThread((CurrentContact)AktChatUserList.Items[0]); } public Timer _ListeningThreadTimer; public Timer GlobalListeningThreadtimer { get; set; } private void InitGlobalListeningThread() { GlobalListeningThreadtimer = new Timer(); GlobalListeningThreadtimer.Tick += GlobalListeningThreadTimerTickEvent; GlobalListeningThreadtimer.Interval = 2000; GlobalListeningThreadtimer.Start(); } private void GlobalListeningThreadTimerTickEvent(object sender, EventArgs e) { ListenGloballyForMessages(); } private void ListenGloballyForMessages() { var numberOfNewMessages = _Chat.GetNumberOfAllNewMessages(); if (numberOfNewMessages > 0) { Dispatcher.BeginInvoke( DispatcherPriority.Normal, (Action)delegate { var contacts = _Chat.NeueGroupklassenKontakte().ToList(); CurrentContact currentContact = null; if (AktChatUserList.HasItems) { currentContact = (CurrentContact)AktChatUserList.Items[0]; } foreach (var contact in _ContactList) { foreach (var newContact in contacts) { if (contact.GroupId == newContact.GroupId) { if (!contact.ReceivedMessage.Equals(newContact.ReceivedMessage)) { contact.ReceivedMessage = newContact.ReceivedMessage; contact.TimeStamp = newContact.TimeStamp; // TODO: Prüfen, ob die App im Hintergrund oder minimiert ist if ((Clientlist.SelectedItem != null && !((Contact)Clientlist.SelectedItem).GroupId.Equals(newContact.GroupId) || Clientlist.SelectedItem == null) || _IsInBackground) { ContainingWindow.Icon = Utils.GetImageSourceFromIcon(Resource.oC_favico_NewMessage); ShowNotification(newContact.Name, "Sie haben eine neue Nachricht", newContact.GroupId); } // Wenn der momentan ausgewählte Kontakt der aktuelle Kontakt in der Schleife ist, werden die Nachrichten nicht als ungelesen angezeigt, sonst schon. if (currentContact != null && newContact.GroupId == currentContact.GroupId) { contact.HasUnreadMessages = false; } else { contact.HasUnreadMessages = true; contact.IsNewMessage = true; } } } if (!_ContactList.Contains(newContact)) { _ContactList.ToList().Add(newContact); } } if (!contacts.Contains(contact)) { _ContactList.ToList().Remove(contact); } } Clientlist.Items.Refresh(); }); } } private void InitListeningThread(CurrentContact pCurrentContacObject) { _ListeningThreadTimer = new Timer {Tag = pCurrentContacObject}; _ListeningThreadTimer.Tick += ListeningThreadTimerTickEvent; _ListeningThreadTimer.Interval = 2000; _ListeningThreadTimer.Start(); } private void ListeningThreadTimerTickEvent(object sender, EventArgs e) { ListenForMessagesForCurrentContact((CurrentContact) ((Timer) sender).Tag); } private void ListenForMessagesForCurrentContact(CurrentContact pCurrentContact) { if (!ShouldInterruptContactsThread) { var hasNewMessages = _Chat.CheckIfNewMessagesExist(pCurrentContact); if (hasNewMessages) { Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)delegate { _Chat.LoadChatMessagesForContact(pCurrentContact); CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); ChatListBox.Items.MoveCurrentToLast(); ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); }); } } } private void Suche_OnTextChanged(object sender, TextChangedEventArgs e) { CollectionViewSource.GetDefaultView(Clientlist.ItemsSource).Refresh(); } private bool UserFilter(object item) { if (String.IsNullOrEmpty(Suche.Text)) return true; else return ((item as Contact).Name.IndexOf(Suche.Text, StringComparison.OrdinalIgnoreCase) >= 0); } private void Chat_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) { Cursor = Cursors.Wait; var chatItems = ChatListBox.SelectedItems; if (chatItems.Count > 0) { foreach (var items in chatItems) { var item = items as ChatMessage; if (item != null && item.ImageSources != null) { StartWaiting(); _Chat.ShowPicture(item, EndWaiting); } else if(item != null && item.FilePath != null) { var filename = Path.GetFileName(item.FilePath.ToString()); LoadDocument(item.FilePath.ToString(), filename); } } Cursor = Cursors.Arrow; } else { Cursor = Cursors.Arrow; } } private void LoadDocument(string link, string filename) { try { StartWaiting(); var path = Path.Combine(Path.GetTempPath(), filename); _CreatedTempFiles.Add(path); if (!File.Exists(path)) { using (var webClient = new WebClient()) { webClient.DownloadFile(link, path); } if (File.Exists(path)) { Process.Start(path); } } else { Process.Start(path); } } catch (Exception e) { } finally { EndWaiting(); } } private ChatControlWaitLayer _waitLayer; public void StartWaiting() { Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)StartWaitingImmediately); } public void StartWaitingImmediately() { if (_waitLayer == null) { _waitLayer = new ChatControlWaitLayer(); //Grid.SetColumnSpan(_waitLayer, 3); Grid.SetRowSpan(_waitLayer, 3); GridRechts.Children.Add(_waitLayer); Panel.SetZIndex(_waitLayer, int.MaxValue); _waitLayer.RefreshChatUI(); } } public void EndWaiting() { Dispatcher.BeginInvoke( DispatcherPriority.Background, (Action)delegate { if (_waitLayer != null) { GridRechts.Children.Remove(_waitLayer); _waitLayer = null; } }); } private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e) { Process.Start(e.Uri.ToString()); } private void ButtonReloadGruppen_OnClick(object sender, RoutedEventArgs e) { DoSynchro(); } private void DoSynchro() { try { Cursor = Cursors.Wait; WriteToNewSyncFile(); var aktuelleGruppen = _Chat.UpdateGroups(); _ContactList = _Chat.GroupklassenAktuallisieren(aktuelleGruppen); ReadNewSyncFile(); Clientlist.Items.Refresh(); Cursor = Cursors.Arrow; } catch (Exception e) { MessageBox.Show("Ein Fehler bei der Synchronisation ist aufgetreten.\nFehler:\n" + e.Message, "Fehler", MessageBoxButton.OK); } } // Speichert die TimeStamps der zuletzt empfangenen Nachrichten public void WriteToNewSyncFile() { try { if (File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name))) { File.SetAttributes(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name), FileAttributes.Normal); File.Delete(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name)); } using (var streamWriter = new StreamWriter(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name))) { Encoding enc = new UTF8Encoding(); foreach (var contact in _ContactList.ToList().Where(contact => contact.ReceivedMessage != null)) { var text = contact.GroupId + ";" + contact.TimeStamp.ToUniversalTime() + ";" + contact.IsNewMessage + ";"; var bytes = enc.GetBytes(text); var base64String = Convert.ToBase64String(bytes); streamWriter.WriteLine(base64String); } File.SetAttributes(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name), FileAttributes.ReadOnly); } } catch (Exception exception) { } } public void ReadNewSyncFile() { try { if(File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name))) { using (var streamReader = new StreamReader(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name), true)) { string line; _GroupId2DateTime.Clear(); while ((line = streamReader.ReadLine()) != null) { var encodedTextBytes = Convert.FromBase64String(line); var plainText = Encoding.UTF8.GetString(encodedTextBytes); var splitPlainText = plainText.Split(';'); // Ist kein Datum vorhanden -> 01.01.0001 00:00:00 var groupId = int.Parse(splitPlainText[0]); var dateTime = DateTime.Parse(splitPlainText[1]); var isUnread = splitPlainText.Length <= 2 || string.IsNullOrEmpty(splitPlainText[2]) || bool.Parse(splitPlainText[2]); _GroupId2DateTime.Add(groupId, new SyncFileInfoStruct(isUnread, dateTime)); } } var latestDateTime = Utils.DefaultDate; foreach(var id2dateTime in _GroupId2DateTime) { if(id2dateTime.Value.TimeStamp > latestDateTime) { latestDateTime = id2dateTime.Value.TimeStamp; } } _Chat.LastTimeStamp = latestDateTime.GetUnixTimeStamp(); } } catch (Exception e) { } } public List GetContactsWithoutUnreadMessages() { var contacts = new List(); Clientlist.Items.Refresh(); foreach(var contactItem in Clientlist.Items) { if(contactItem is Contact contact && contact.HasUnreadMessages && !string.IsNullOrEmpty(contact.ReceivedMessage)) { contacts.Add(contact); } } return contacts; } public void ResetNumberOfUnreadMessages(Dictionary pGroupId2DateTime) { if(pGroupId2DateTime != null) { foreach(var contact in _ContactList) { foreach(var groupId2DateTime in pGroupId2DateTime) { if(contact.GroupId == groupId2DateTime.Key) { contact.HasUnreadMessages = false; } } } } } public List GetSelectedMessages() { var messages = (from object selectedItem in ChatListBox.SelectedItems select selectedItem as ChatMessage).ToList(); return messages.Count > 0 ? messages : null; } public CurrentContact GetCurrentContact() { if(AktChatUserList != null && AktChatUserList.Items.Count > 0) { var contact = (CurrentContact) AktChatUserList.Items[0]; return contact.UserIdManage == null ? null : contact; } return null; } public void AddContextMenu(string menuItemText, Action callBackAction) { if (!_MenuItemName2Callback.ContainsKey(menuItemText)) { _MenuItemName2Callback.Add(menuItemText, callBackAction); } } public void DeleteTempFiles() { foreach (var file in _CreatedTempFiles) { try { if (File.Exists(file)) { File.Delete(file); } } catch (Exception e) { //ignore } } } } }