diff --git a/ChatController/ChatControlWaitLayer.xaml b/ChatController/ChatControlWaitLayer.xaml index 9ae68b7..21785d2 100644 --- a/ChatController/ChatControlWaitLayer.xaml +++ b/ChatController/ChatControlWaitLayer.xaml @@ -4,7 +4,7 @@ xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" - Foreground="{DynamicResource BSOrangeBrush}"> + Foreground="#FF5A00"> - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - + + - - + - - + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - + - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + - - - - - - + + + + + - - - - - + + + + + - - - - - - + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - + diff --git a/ChatController/ChatMainControl.xaml.cs b/ChatController/ChatMainControl.xaml.cs index 0b78f89..73d9239 100644 --- a/ChatController/ChatMainControl.xaml.cs +++ b/ChatController/ChatMainControl.xaml.cs @@ -1,9 +1,12 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; +using System.Runtime.CompilerServices; using System.Text; using System.Windows; using System.Windows.Controls; @@ -13,14 +16,13 @@ using System.Windows.Input; using System.Windows.Media; using System.Windows.Navigation; using System.Windows.Threading; - +using ChatController.Annotations; using ChatController.ChatKlassen; using ChatController.Extensions; 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; @@ -35,7 +37,7 @@ using Timer = System.Windows.Forms.Timer; namespace ChatController { - public partial class ChatMainControl + public partial class ChatMainControl : INotifyPropertyChanged { private readonly Dictionary> _Group2NotifyIcons = new Dictionary>(); @@ -50,6 +52,7 @@ namespace ChatController set { _ContainingWindow = value; + if(value != null) { _ContainingWindow.Deactivated += ContainingWindowOnDeactivated; @@ -59,11 +62,49 @@ namespace ChatController } private Chat _Chat; - private CurrentContact _CurrentContact; + private Contact _CurrentContact; - private bool _IsChatBoxOnFocus; + public ObservableCollection CurrentChatMessages => _CurrentContact != null && _Chat != null ? new ObservableCollection(_Chat.Messages) : new ObservableCollection(); - private IOrderedEnumerable _ContactList; + public Contact CurrentContact + { + get => _CurrentContact; + + set + { + if(!Equals(_CurrentContact, value)) + { + _CurrentContact = value; + + OnPropertyChanged(nameof(CurrentContact)); + OnPropertyChanged(nameof(ChatMessageInputGridVisibility)); + OnPropertyChanged(nameof(CurrentChatMessages)); + } + } + } + + public ObservableCollection ContactList + { + get + { + return _ContactList == null ? new ObservableCollection() : new ObservableCollection(_ContactList.OrderByDescending(contact => contact.TimeStamp)); + } + } + + public Visibility ChatMessageInputGridVisibility + { + get + { + if(_CurrentContact == null) + { + return Visibility.Collapsed; + } + + return _CurrentContact.IsChatMessageInputGridVisible ? Visibility.Visible : Visibility.Collapsed; + } + } + + private List _ContactList; private bool _ScrollPrueferAktivieren; @@ -81,6 +122,8 @@ namespace ChatController { InitializeComponent(); + DataContext = this; + ReloadGruppen.Visibility = Visibility.Collapsed; } @@ -96,11 +139,15 @@ namespace ChatController public void InitMitChatdaten(ChatDatenUebergabe cdu) { - _Chat = new Chat(cdu); + _Chat = new Chat(cdu, exception => { + this.Dispatch(() => { + EndWaiting(); + MessageBox.Show($"Fehler: {exception.Message}", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + }); + }); _ContactList = _Chat.AddContacts(); - - Clientlist.ItemsSource = _ContactList; + OnPropertyChanged(nameof(ContactList)); ReadNewSyncFile(); @@ -118,9 +165,6 @@ namespace ChatController } } - var view = (CollectionView) CollectionViewSource.GetDefaultView(Clientlist.ItemsSource); - view.Filter = UserFilter; - GlobalListeningThreadtimer?.Stop(); GlobalListeningThreadtimer = null; InitGlobalListeningThread(); @@ -205,6 +249,7 @@ namespace ChatController } } + // WebRequest: LoadChatMessagesForContact private void SelectContact(Contact pContact) { if(pContact == null) @@ -226,7 +271,7 @@ namespace ChatController Clientlist.Items.Refresh(); } - var currentContact = new CurrentContact(pContact); + var currentContact = pContact; pContact.IsNewMessage = false; var shouldChangeIcon = _ContactList.Any(contact => contact.IsNewMessage); @@ -236,7 +281,7 @@ namespace ChatController } AktChatUserList.Items.Add(currentContact); - _CurrentContact = currentContact; + CurrentContact = currentContact; if(Clientlist.Items.Contains(pContact)) { @@ -245,7 +290,7 @@ namespace ChatController var chatMessages = _Chat.LoadChatMessagesForContact(currentContact); - ChatListBox.ItemsSource = chatMessages; + OnPropertyChanged(nameof(CurrentChatMessages)); if (VisualTreeHelper.GetChildrenCount(ChatListBox) > 0) { @@ -270,192 +315,215 @@ namespace ChatController { var contextItems = ChatListBox?.ContextMenu?.Items; + if(contextItems == null) + { + return; + } + foreach (var menuItemText in _MenuItemName2Callback.Keys) { - var cb = _MenuItemName2Callback[menuItemText]; + var callback = _MenuItemName2Callback[menuItemText]; var menuItem = new MenuItem(); menuItem.Click += (s, e2) => { - cb(menuItemText); + callback(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 + if(contextItems.Count > 0) + { + var saveAsMenuItem = (MenuItem) contextItems[0]; + saveAsMenuItem.Click += SaveAsOnClick; + } + + if(contextItems.Count > 1) + { + var pasteMenuItem = (MenuItem) contextItems[1]; + pasteMenuItem.Click += PasteOnClick; + } // 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) + if(contextItems.Count > 2) { - var item = (ChatMessage)items; - - _Chat.SaveFileAs(item); + var copyMenuItem = (MenuItem) contextItems[2]; + copyMenuItem.Click += CopyOnClick; } } - private void Item3OnClick(object sender, RoutedEventArgs routedEventArgs) + private void SaveAsOnClick(object sender, RoutedEventArgs routedEventArgs) { - var kontakt = (CurrentContact)AktChatUserList.Items[0]; + foreach (var items in ChatListBox.SelectedItems) + { + var chatMessage = (ChatMessage) items; + + _Chat.SaveFileAs(chatMessage); + } + } + + private void PasteOnClick(object sender, RoutedEventArgs routedEventArgs) + { + var kontakt = (Contact)AktChatUserList.Items[0]; _Chat.Paste(kontakt.GroupId,this); } - private void Item4OnClick(object sender, RoutedEventArgs routedEventArgs) + private void CopyOnClick(object sender, RoutedEventArgs routedEventArgs) { - string chatmessages = ""; + var chatMessages = string.Empty; + foreach (var items in ChatListBox.SelectedItems) { - var item = (ChatMessage)items; + var item = (ChatMessage) items; - chatmessages += item.UserMessage + "\n"; + chatMessages += item.UserMessage + "\n"; } - if(!chatmessages.Equals("")) - _Chat.Copy(chatmessages, 1); + if(!string.IsNullOrWhiteSpace(chatMessages)) + { + _Chat.Copy(chatMessages, 1); + } } private void Chat_OnContextMenuOpening(object sender, ContextMenuEventArgs e) { - var chatItems = ChatListBox.SelectedItems; - - if (chatItems.Count > 0) + if(ChatListBox?.ContextMenu == null) { - foreach (var items in chatItems) + return; + } + + if(ChatListBox.SelectedItems is List chatMessages) + { + if(chatMessages.Count > 0) { - var item = items as ChatMessage; - if (item != null && item.ImageSources != null) + foreach(var items in chatMessages) { - 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; - } + var item = items as ChatMessage; + if(item?.ImageSources != null) + { + if(ChatListBox.ContextMenu != null) + { + var contextItems = ChatListBox.ContextMenu.Items; + ((MenuItem)contextItems[0]).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; + 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 dataObject = System.Windows.Forms.Clipboard.GetDataObject(); + if(dataObject != null && dataObject.GetDataPresent(DataFormats.FileDrop)) + { + var contextItems = ChatListBox.ContextMenu.Items; + var ContextItemSpeichernUnter = (MenuItem) contextItems[1]; + ContextItemSpeichernUnter.Visibility = Visibility.Visible; + } + else if(dataObject != null && dataObject.GetDataPresent(DataFormats.Text)) + { + var contextItems = ChatListBox.ContextMenu.Items; + var ContextItemSpeichernUnter = (MenuItem) contextItems[1]; + ContextItemSpeichernUnter.Visibility = Visibility.Visible; + } + else if(dataObject != null && dataObject.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 = (Contact)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; } } - 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(); + var fileToOpen = _Chat.OpenFile(); - if(medium != null) { + if(fileToOpen != null) + { + var filePath = FileUtils.ScaleImage(fileToOpen, Path.GetExtension(fileToOpen.ToUpperInvariant()), _Chat.ChatDaten.MaxUploadSize); - string convertetMedia = _Chat.ScaleImage(medium, Path.GetExtension(medium.ToUpperInvariant())); + var isFileSizeTooLarge = FileUtils.CheckFileSize(filePath, _Chat.ChatDaten.MaxUploadSize); - if (!convertetMedia.Equals("")) + if(isFileSizeTooLarge) { - _Chat.AddNewFile(convertetMedia,medium,kontakt.GroupId); + MessageBox.Show($"Die ausgewählte Datei ist zu groß. Die maximale Größe beträgt {_Chat.ChatDaten.MaxUploadSize / 1000 / 1000} MB", "Senden nicht möglich", MessageBoxButton.OK, MessageBoxImage.Warning); + return; + } - CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); + if (!string.IsNullOrWhiteSpace(filePath)) + { + //_Chat.AddNewFile(filePath, fileToOpen, CurrentContact.GroupId); + + OnPropertyChanged(nameof(CurrentChatMessages)); + ChatListBox.Items.MoveCurrentToLast(); ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); - _Chat.SendFileToContact(kontakt, convertetMedia,medium); + _Chat.SendFileToContact(CurrentContact, filePath,fileToOpen); - if (!convertetMedia.Equals("") && !convertetMedia.Equals(medium) && File.Exists(convertetMedia)) + if (!string.IsNullOrWhiteSpace(filePath) && !filePath.Equals(fileToOpen) && File.Exists(filePath)) { - File.Delete(convertetMedia); + File.Delete(filePath); } } - else - { - MessageBox.Show("Die gewählte Datei ist zu groß!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Exclamation); - } } } else @@ -466,51 +534,18 @@ namespace ChatController private void SendButton_OnClick(object sender, RoutedEventArgs e) { - if (!AktChatUserList.Items.IsEmpty && !Chatbox.Text.Equals("") && _IsChatBoxOnFocus) + if (!AktChatUserList.Items.IsEmpty && !string.IsNullOrEmpty(Chatbox.Text)) { - if (!Chatbox.Text.Equals("")) - { - var kontakt = (CurrentContact)AktChatUserList.Items[0]; - - _Chat.AddNewMessage(Chatbox.Text, kontakt.GroupId); - - CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); + _Chat.AddNewMessage(Chatbox.Text, CurrentContact.GroupId); - ChatListBox.Items.MoveCurrentToLast(); - ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); - - _Chat.SendMessage(Chatbox.Text, kontakt.GroupId); + OnPropertyChanged(nameof(CurrentChatMessages)); - 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; - } + ChatListBox.Items.MoveCurrentToLast(); + ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); + + _Chat.SendMessage(Chatbox.Text, CurrentContact.GroupId); + + Chatbox.Text = string.Empty; } } @@ -518,9 +553,8 @@ namespace ChatController { if (Chatbox.Text.Equals("Nachricht schreiben")) { - Chatbox.Text = ""; + Chatbox.Text = string.Empty; Chatbox.Foreground = new SolidColorBrush(Colors.Black); - _IsChatBoxOnFocus = true; } } @@ -530,32 +564,18 @@ namespace ChatController { if (e.Key == Key.Return) { - if (!AktChatUserList.Items.IsEmpty && !Chatbox.Text.Equals("")) + if (!AktChatUserList.Items.IsEmpty && !string.IsNullOrEmpty(Chatbox.Text)) { - var kontakt = (CurrentContact)AktChatUserList.Items[0]; - - _Chat.AddNewMessage(Chatbox.Text, kontakt.GroupId); - - CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); + _Chat.AddNewMessage(Chatbox.Text, CurrentContact.GroupId); + + OnPropertyChanged(nameof(CurrentChatMessages)); + ChatListBox.Items.MoveCurrentToLast(); ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); - _Chat.SendMessage(Chatbox.Text, kontakt.GroupId); + _Chat.SendMessage(Chatbox.Text, CurrentContact.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 leere Nachricht verschicken.", "Fehler", MessageBoxButton.OK); - } + Chatbox.Text = string.Empty; } } } @@ -570,17 +590,13 @@ namespace ChatController public event EmojiiDelegate OnEmojii; private void EmojiButton_OnClick(object sender, RoutedEventArgs e) - { - //hier wie bei login - if (OnEmojii != null) - { - OnEmojii(EmojiButton); - } + { + OnEmojii?.Invoke(EmojiButton); } private void Chat_OnScrollChanged(object sender, ScrollChangedEventArgs e) { - var scrollBarList = GetVisualChildCollection(ChatListBox); + var scrollBarList = Utils.GetVisualChildCollection(ChatListBox); foreach (var scrollBar in scrollBarList) { if (scrollBar.Orientation == Orientation.Horizontal) @@ -594,74 +610,46 @@ namespace ChatController } } + // TODO: Asynchron machen? private void VerticalScrollbarChanged(object sender, RoutedPropertyChangedEventArgs routedPropertyChangedEventArgs) { - if (_ScrollPrueferAktivieren == true) + if (_ScrollPrueferAktivieren) { - var x = (ScrollBar) sender; + var scrollBar = (ScrollBar) sender; - if (x.Value > 0) - { - //nix - } - else + if (!(scrollBar.Value > 0)) { Cursor = Cursors.Wait; - //StartWaiting(); + _ScrollPrueferAktivieren = false; ChatListBox.Items.MoveCurrentToFirst(); - ChatMessage item = ChatListBox.Items.CurrentItem as ChatMessage; + var currentChatMessage = ChatListBox.Items.CurrentItem as ChatMessage; - ChatListBox.ItemsSource = null; + var kontakt = (Contact) Clientlist.SelectedItem; - var kontakt = (Contact)Clientlist.SelectedItem; + _Chat.LoadMoreMessages(kontakt); // Ab hier käme das ins Callback - var xy = _Chat.LoadMoreMessages(kontakt); + OnPropertyChanged(nameof(CurrentChatMessages)); - ChatListBox.ItemsSource = xy; - - ChatListBox.ScrollIntoView(item); - //EndWaiting(); + if(currentChatMessage != null) + { + ChatListBox.ScrollIntoView(currentChatMessage); + } + 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]); + EmojisListeningThreadTimer?.Stop(); + EmojisListeningThreadTimer = null; + InitListeningThread((Contact)AktChatUserList.Items[0]); } - public Timer _ListeningThreadTimer; + public Timer EmojisListeningThreadTimer; public Timer GlobalListeningThreadtimer { get; set; } private void InitGlobalListeningThread() @@ -689,11 +677,11 @@ namespace ChatController { var contacts = _Chat.NeueGroupklassenKontakte().ToList(); - CurrentContact currentContact = null; + Contact currentContact = null; if (AktChatUserList.HasItems) { - currentContact = (CurrentContact)AktChatUserList.Items[0]; + currentContact = (Contact) AktChatUserList.Items[0]; } foreach (var contact in _ContactList) @@ -709,7 +697,7 @@ namespace ChatController 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) + 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, newContact.ReceivedMessage, newContact.GroupId); @@ -745,20 +733,20 @@ namespace ChatController } } - private void InitListeningThread(CurrentContact pCurrentContacObject) + private void InitListeningThread(Contact currentContact) { - _ListeningThreadTimer = new Timer {Tag = pCurrentContacObject}; - _ListeningThreadTimer.Tick += ListeningThreadTimerTickEvent; - _ListeningThreadTimer.Interval = 2000; - _ListeningThreadTimer.Start(); + EmojisListeningThreadTimer = new Timer {Tag = currentContact}; + EmojisListeningThreadTimer.Tick += ListeningThreadTimerTickEvent; + EmojisListeningThreadTimer.Interval = 2000; + EmojisListeningThreadTimer.Start(); } private void ListeningThreadTimerTickEvent(object sender, EventArgs e) { - ListenForMessagesForCurrentContact((CurrentContact) ((Timer) sender).Tag); + ListenForMessagesForCurrentContact((Contact) ((Timer) sender).Tag); } - private void ListenForMessagesForCurrentContact(CurrentContact pCurrentContact) + private void ListenForMessagesForCurrentContact(Contact pCurrentContact) { if (!ShouldInterruptContactsThread) { @@ -771,7 +759,7 @@ namespace ChatController { _Chat.LoadChatMessagesForContact(pCurrentContact); - CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); + OnPropertyChanged(nameof(CurrentChatMessages)); ChatListBox.Items.MoveCurrentToLast(); ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); @@ -782,15 +770,18 @@ namespace ChatController private void Suche_OnTextChanged(object sender, TextChangedEventArgs e) { + OnPropertyChanged(nameof(CurrentChatMessages)); CollectionViewSource.GetDefaultView(Clientlist.ItemsSource).Refresh(); } private bool UserFilter(object item) { - if (String.IsNullOrEmpty(Suche.Text)) + if (string.IsNullOrEmpty(Suche.Text)) + { return true; - else - return ((item as Contact).Name.IndexOf(Suche.Text, StringComparison.OrdinalIgnoreCase) >= 0); + } + + return (item as Contact).Name.IndexOf(Suche.Text, StringComparison.OrdinalIgnoreCase) >= 0; } private void Chat_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) @@ -798,19 +789,20 @@ namespace ChatController 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) + if (item?.OriginalImage != null) { - StartWaiting(); - _Chat.ShowPicture(item, EndWaiting); + StartWaitingImmediately(); + + _Chat.ShowPicture(item.OriginalImage, EndWaiting); } - else if(item != null && item.FilePath != null) + else if(item?.FilePath != null) { var filename = Path.GetFileName(item.FilePath.ToString()); LoadDocument(item.FilePath.ToString(), filename); @@ -860,7 +852,7 @@ namespace ChatController } } - private ChatControlWaitLayer _waitLayer; + private ChatControlWaitLayer _WaitLayer; public void StartWaiting() { @@ -869,14 +861,13 @@ namespace ChatController public void StartWaitingImmediately() { - if (_waitLayer == null) + 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(); + _WaitLayer = new ChatControlWaitLayer(); + Grid.SetRowSpan(_WaitLayer, 3); + RootGrid.Children.Add(_WaitLayer); + Panel.SetZIndex(_WaitLayer, int.MaxValue); + _WaitLayer.RefreshChatUI(); } } @@ -884,12 +875,12 @@ namespace ChatController { Dispatcher.BeginInvoke( DispatcherPriority.Background, - (Action)delegate + (Action) delegate { - if (_waitLayer != null) + if(_WaitLayer != null) { - GridRechts.Children.Remove(_waitLayer); - _waitLayer = null; + RootGrid.Children.Remove(_WaitLayer); + _WaitLayer = null; } }); } @@ -908,22 +899,26 @@ namespace ChatController { try { - Cursor = Cursors.Wait; + StartWaitingImmediately(); WriteToNewSyncFile(); - var aktuelleGruppen = _Chat.UpdateGroups(); + _Chat.ReloadGroupsAsync(data => + { + this.Dispatch(() => + { + _ContactList = _Chat.GroupklassenAktuallisieren(data); // <- dauert eine Sekunde! + OnPropertyChanged(nameof(ContactList)); - _ContactList = _Chat.GroupklassenAktuallisieren(aktuelleGruppen); + ReadNewSyncFile(); - ReadNewSyncFile(); - - Clientlist.Items.Refresh(); - - Cursor = Cursors.Arrow; + EndWaiting(); + }); + }); } catch (Exception e) { + EndWaiting(); MessageBox.Show("Ein Fehler bei der Synchronisation ist aufgetreten.\nFehler:\n" + e.Message, "Fehler", MessageBoxButton.OK); } } @@ -1008,6 +1003,7 @@ namespace ChatController } } + // Wird im BeWoPlaner benutzt public List GetContactsWithoutUnreadMessages() { var contacts = new List(); @@ -1025,6 +1021,7 @@ namespace ChatController return contacts; } + // Wird im BeWoPlaner benutzt public void ResetNumberOfUnreadMessages(Dictionary pGroupId2DateTime) { if(pGroupId2DateTime != null) @@ -1042,6 +1039,7 @@ namespace ChatController } } + // Wird im BeWoPlaner benutzt public List GetSelectedMessages() { var messages = (from object selectedItem in ChatListBox.SelectedItems select selectedItem as ChatMessage).ToList(); @@ -1049,11 +1047,12 @@ namespace ChatController return messages.Count > 0 ? messages : null; } - public CurrentContact GetCurrentContact() + // Wird im BeWoPlaner benutzt + public Contact GetCurrentContact() { if(AktChatUserList != null && AktChatUserList.Items.Count > 0) { - var contact = (CurrentContact) AktChatUserList.Items[0]; + var contact = (Contact) AktChatUserList.Items[0]; return contact.UserIdManage == null ? null : contact; } @@ -1061,6 +1060,7 @@ namespace ChatController return null; } + // Wird im BeWoPlaner benutzt public void AddContextMenu(string menuItemText, Action callBackAction) { if (!_MenuItemName2Callback.ContainsKey(menuItemText)) @@ -1069,7 +1069,7 @@ namespace ChatController } } - public void DeleteTempFiles() + public void DeleteTempFiles() { foreach (var file in _CreatedTempFiles) { @@ -1086,5 +1086,19 @@ namespace ChatController } } } + + public event PropertyChangedEventHandler PropertyChanged; + + [NotifyPropertyChangedInvocator] + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + private void ChatMainControl_OnLoaded(object sender, RoutedEventArgs e) + { + var view = (CollectionView)CollectionViewSource.GetDefaultView(Clientlist.ItemsSource); + view.Filter = UserFilter; + } } } diff --git a/ChatController/Converter/BoolToVisibilityConverter.cs b/ChatController/Converter/BoolToVisibilityConverter.cs new file mode 100644 index 0000000..cb4d572 --- /dev/null +++ b/ChatController/Converter/BoolToVisibilityConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace ChatController.Converter +{ + public class BoolToVisibilityConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if(value is bool boolValue) + { + if(parameter is string reverseString && Equals(reverseString, "reverse")) + { + return boolValue ? Visibility.Visible : Visibility.Collapsed; + } + + return boolValue ? Visibility.Collapsed : Visibility.Visible; + } + + return Visibility.Visible; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/ChatController/Converter/StringEmptyToVisibilityConverter.cs b/ChatController/Converter/StringEmptyToVisibilityConverter.cs new file mode 100644 index 0000000..ae818c8 --- /dev/null +++ b/ChatController/Converter/StringEmptyToVisibilityConverter.cs @@ -0,0 +1,25 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace ChatController.Converter +{ + public class StringEmptyToVisibilityConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if(value is string text) + { + return string.IsNullOrWhiteSpace(text) ? Visibility.Visible : Visibility.Hidden; + } + + return Visibility.Visible; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/ChatController/Converter/StringToBoolConverter.cs b/ChatController/Converter/StringToBoolConverter.cs new file mode 100644 index 0000000..a4a7254 --- /dev/null +++ b/ChatController/Converter/StringToBoolConverter.cs @@ -0,0 +1,24 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace ChatController.Converter +{ + public class StringToBoolConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if(value is string text) + { + return !string.IsNullOrWhiteSpace(text); + } + + return false; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/ChatController/Data/LookupResult.cs b/ChatController/Data/LookupResult.cs new file mode 100644 index 0000000..dfdc83c --- /dev/null +++ b/ChatController/Data/LookupResult.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json; + +namespace ChatController.Data +{ + public class LookupResult + { + public int Status { get; set; } + + [JsonProperty("URL")] + public string Url { get; set; } + + public string SyncType { get; set; } + } +} diff --git a/ChatController/HauptKlassen/Chat.cs b/ChatController/HauptKlassen/Chat.cs index c34f8a6..e990fe7 100644 --- a/ChatController/HauptKlassen/Chat.cs +++ b/ChatController/HauptKlassen/Chat.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; -using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; @@ -18,17 +17,15 @@ using System.Windows.Data; using System.Windows.Forms; using System.Windows.Media; using System.Windows.Media.Imaging; - using ChatController.LoginKlassen; using ChatController.Utilities; using ChatController.Utilities.Extensions; - +using RestSharp; +using RestSharp.Extensions.MonoHttp; using Application = System.Windows.Forms.Application; using Clipboard = System.Windows.Forms.Clipboard; -using Color = System.Drawing.Color; using ContextMenu = System.Windows.Controls.ContextMenu; using DataFormats = System.Windows.Forms.DataFormats; -using Image = System.Windows.Controls.Image; using MessageBox = System.Windows.MessageBox; using Size = System.Drawing.Size; @@ -36,8 +33,11 @@ namespace ChatController.HauptKlassen { public class Chat { + public Action ExceptionCallback { get; set; } + private readonly List _Contacts = new List(); - public List Messages { get; } = new List(); + + public List Messages { get; set; } = new List(); public ChatDatenUebergabe ChatDaten { get; set; } @@ -49,28 +49,25 @@ namespace ChatController.HauptKlassen public long LastTimeStamp { get; set; } - public Chat(ChatDatenUebergabe chatDaten) + public Chat(ChatDatenUebergabe chatDaten, Action exceptionCallback) { ChatDaten = chatDaten; + ExceptionCallback = exceptionCallback; } - public IOrderedEnumerable AddContacts() + // WebRequest + public List AddContacts() { - foreach (var contact in ChatDaten.AlleGruppen.Response) - { - _Contacts.AddRange(GenerateContactsFromServerResponse(contact.Value, true)); - } + _Contacts.AddRange(GenerateContactsFromServerResponse(ChatDaten.AlleGruppen.Response.Groups.ToArray(), true)); - var sortedKontaktliste = _Contacts.OrderByDescending(r => r.TimeStamp); - - return sortedKontaktliste; + return _Contacts; } - public IOrderedEnumerable LoadChatMessagesForContact(CurrentContact pContact) + public IOrderedEnumerable LoadChatMessagesForContact(Contact currentContact) { - if (pContact != null) + if (currentContact != null) { - LoadMessagesFromServer(pContact.GroupId); + LoadMessagesFromServer(currentContact.GroupId); Messages.Clear(); AddMessagesFromServerResponse(_UserMessages.Response.Messages); @@ -79,7 +76,9 @@ namespace ChatController.HauptKlassen return Messages.OrderBy(r => r.SendTime); } - private static ImageSource DownloadImage(string pUri) + // WebRequest + // TODO: Auth-Token zum Header hinzufügen + private ImageSource DownloadImage(string pUri) { try { @@ -94,10 +93,12 @@ namespace ChatController.HauptKlassen } catch (Exception exception) { + ExceptionCallback?.Invoke(exception); return null; } } + // WebRequest private void LoadMessagesFromServer(long pGroupId) { try @@ -131,24 +132,58 @@ namespace ChatController.HauptKlassen } } } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + ExceptionCallback?.Invoke(exception); } } - - public IOrderedEnumerable LoadMoreMessages(Contact pContact) + + // WebRequest + public void LoadMoreMessages(Contact pContact) { if (_HasNextPage) - { + { LoadMoreMessagesFromServer(pContact.GroupId, _NextPage); - AddMessagesFromServerResponse(_AdditionalUserMessages.Response.Messages); } - - return Messages.OrderBy(r => r.SendTime); } + private void LoadMoreMessagesFromServerAsync(long groupId, string page, Action callback) + { + try + { + var pageParam = page.Split('='); + + var url = $"{ChatDaten.ServerUrl}/api/chat/messages?groupid={groupId}&page={pageParam}"; + + var client = new RestClient(url); + var request = new RestRequest(); + + request.AddHeader(Constants.Token, ChatDaten.AuthToken); + request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); + + client.ExecuteAsync(request, response => + { + _AdditionalUserMessages = null; + _AdditionalUserMessages = JsonConvert.DeserializeObject(response.Content); + + if(_AdditionalUserMessages.Response.HasMorePages) + { + _NextPage = _AdditionalUserMessages.Response.NextPage; + } + + _HasNextPage = _AdditionalUserMessages.Response.HasMorePages; + + callback?.Invoke(); + }); + } + catch(Exception exception) + { + ExceptionCallback?.Invoke(exception); + } + } + + // WebRequest private void LoadMoreMessagesFromServer(long pGroupId, string pPage) { try @@ -185,15 +220,16 @@ namespace ChatController.HauptKlassen response.Close(); } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + ExceptionCallback?.Invoke(exception); } } private double _FormerMessagesCount; - public bool CheckIfNewMessagesExist(CurrentContact pCurrentContact) + // WebRequest + public bool CheckIfNewMessagesExist(Contact currentContact) { var span = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var timespan = Convert.ToInt64(span.TotalSeconds); @@ -203,9 +239,9 @@ namespace ChatController.HauptKlassen timespan = _UserMessages.Response.Messages.First().Created_At; } - if (pCurrentContact != null) + if (currentContact != null) { - var currentMessagesCount = GetNumberOfNewMessages(pCurrentContact.GroupId, timespan); + var currentMessagesCount = GetNumberOfNewMessages(currentContact.GroupId, timespan); if (currentMessagesCount.Equals(_FormerMessagesCount)) { @@ -220,6 +256,7 @@ namespace ChatController.HauptKlassen return false; } + // WebRequest private double GetNumberOfNewMessages(long pGroupId, long pLastTimeStamp) { try @@ -242,10 +279,12 @@ namespace ChatController.HauptKlassen } catch (Exception exception) { + ExceptionCallback?.Invoke(exception); return 0; } } + // WebRequest public double GetNumberOfAllNewMessages() { var unixTime = DateTime.UtcNow.GetUnixTimeStamp(); @@ -262,6 +301,7 @@ namespace ChatController.HauptKlassen return messageCount; } + // WebRequest private double LoadNumberOfNewMessagesFromServer(long pGroupId) { try @@ -283,22 +323,21 @@ namespace ChatController.HauptKlassen return messageCounter.MessageCount; } - catch (Exception exception) + catch(Exception exception) { + ExceptionCallback?.Invoke(exception); return 0; } } + // WebRequest: LoadGroups public IOrderedEnumerable NeueGroupklassenKontakte() { var contacts = new List(); var groupData = LoadGroups(); - foreach (var contact in groupData.Response) - { - contacts.AddRange(GenerateContactsFromServerResponse(contact.Value, true)); - } + contacts.AddRange(GenerateContactsFromServerResponse(groupData.Response.Groups.ToArray(), true)); return contacts.OrderByDescending(r => r.TimeStamp); } @@ -325,9 +364,9 @@ namespace ChatController.HauptKlassen return jsonDaten; } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + ExceptionCallback?.Invoke(exception); return null; } } @@ -336,10 +375,10 @@ namespace ChatController.HauptKlassen { try { - var username = ""; + var username = string.Empty; + + var user = ChatDaten.LoggedInUser.Response.User; - //var user = ChatDaten.AngemeldeterUser.Response.Values.FirstOrDefault(); - var user = ChatDaten.AngemeldeterUser.Response.User; if(user != null) { username = $"{user.Firstname} {user.Lastname}"; @@ -348,57 +387,131 @@ namespace ChatController.HauptKlassen var time = DateTime.Now; Messages.Add(new ChatMessage(username, pMessage, time, true, pGroupId, 0)); - + + AddSeparators(); } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK); - } + ExceptionCallback?.Invoke(exception); + } } - - public async void SendMessage(string message, long groupId) + + // TODO: Funktioniert nicht mit der Version von RestSharp, die mit .NET Version 4.5 kompatibel ist + public void SendMessageAsync(string message, long groupId) { try { - var endurl = ChatDaten.ServerUrl + "/api/chat/messages/send"; + var url = ChatDaten.ServerUrl + Constants.SendMessageUrl; + var requestBody = $"{HttpUtility.UrlEncode("groupid")}={HttpUtility.UrlEncode(groupId.ToString())}&{HttpUtility.UrlEncode("text")}={HttpUtility.UrlEncode(message)}"; + var client = new RestClient(url); + var request = new RestRequest(Method.POST); - Dictionary postparameter = new Dictionary(); + request.AddHeader(Constants.ContentTypeKey, Constants.MultipartContentTypeValue); + request.AddParameter(Constants.Token, ChatDaten.AuthToken); + request.AddParameter(Constants.CustomerId, ChatDaten.Kundennummer); - postparameter.Add("groupid", groupId + ""); - postparameter.Add("text", message); - - using (MultipartFormDataContent multiPartContent = new MultipartFormDataContent()) + request.AddParameter(Constants.MultipartContentTypeValue, requestBody, ParameterType.RequestBody); + + client.PostAsync(request, (response, handle) => { - multiPartContent.Add(new StringContent(groupId + ""), "groupid"); + + }); + + /* + * + multiPartContent.Add(new StringContent(groupId.ToString()), "groupid"); multiPartContent.Add(new StringContent(message), "text"); - Uri requestUri = new Uri(endurl); - - HttpRequestMessage httpRequest = new HttpRequestMessage(); - httpRequest.Method = HttpMethod.Post; - httpRequest.RequestUri = requestUri; - //wegen Kontent nachschauen httpRequest.Content = multiPartContent; httpRequest.Headers.Add("Token", ChatDaten.AuthToken); httpRequest.Headers.Add("CustomerID", ChatDaten.Kundennummer); + --------------------------------------------------------------------------------------------------------------------------------------------------- - HttpResponseMessage httpResponse = null; + var url = _BaseUrl + Constants.LoginWithChatCodeUrl; + var requestBody = $"{HttpUtility.UrlEncode("username")}={HttpUtility.UrlEncode(_UserName)}&{HttpUtility.UrlEncode("password")}={HttpUtility.UrlEncode(_Password)}&{HttpUtility.UrlEncode("chatcode")}={HttpUtility.UrlEncode(_ChatCode)}"; - HttpClient httpClient = new HttpClient(); - //httpClient.Timeout = TimeSpan.FromSeconds(300); - httpResponse = await httpClient.SendAsync(httpRequest, CancellationToken.None).ConfigureAwait(false); - - //string antwortResponse = await httpResponse.Content.ReadAsStringAsync(); + var client = new RestClient(url); + var request = new RestRequest(Method.POST); + + request.AddHeader(Constants.ContentTypeKey, Constants.FormUrlEncodedContentTypeValue); + request.AddParameter(Constants.CustomerId, _Tenant, ParameterType.HttpHeader); + request.AddParameter(Constants.FormUrlEncodedContentTypeValue, requestBody, ParameterType.RequestBody); + + client.PostAsync(request, (response, handle) => + { + Debug.WriteLine(response.Content); + + var connectionData = JsonConvert.DeserializeObject(response.Content); + + if (connectionData.Success) + { + _AuthToken = connectionData.Response.User.Token; + _UserId = connectionData.Response.User.Oid; + + Utils.AuthToken = _AuthToken; + Utils.Tenant = _Tenant; + + _LoggedInUser = connectionData; + + callback?.Invoke(true); + } + else + { + var errorMessage = string.Empty; + + if (connectionData.Error?.ChatCodeFailed != null) + { + errorMessage = $"Fehler: {connectionData.Error.ChatCodeFailed[0]}\nBitte überprüfen Sie die Anmeldeinformationen."; + } + else if (connectionData.Error?.LoginFailed != null) + { + errorMessage = $"Fehler: {connectionData.Error.LoginFailed[0]}\nBitte überprüfen Sie die Anmeldeinformationen."; + } + + if (!string.IsNullOrWhiteSpace(errorMessage)) + { + exceptionCallback?.Invoke(errorMessage); + } + } + }); + */ + } + catch(Exception exception) + { + MessageBox.Show(exception.Message, "Fehler", MessageBoxButton.OK); + } + } + + public async void SendMessage(string message, long groupId) + { + try + { + var endurl = ChatDaten.ServerUrl + Constants.SendMessageUrl; + + using (var multiPartContent = new MultipartFormDataContent()) + { + multiPartContent.Add(new StringContent(groupId.ToString()), "groupid"); + multiPartContent.Add(new StringContent(message), "text"); + var requestUri = new Uri(endurl); + + var httpRequest = new HttpRequestMessage {Method = HttpMethod.Post, RequestUri = requestUri, Content = multiPartContent}; + + //wegen Kontent nachschauen + httpRequest.Headers.Add("Token", ChatDaten.AuthToken); + httpRequest.Headers.Add("CustomerID", ChatDaten.Kundennummer); + + var httpClient = new HttpClient(); + await httpClient.SendAsync(httpRequest, CancellationToken.None).ConfigureAwait(false); } } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show("Fehler: " + e.Message,"Fehler",MessageBoxButton.OK); + ExceptionCallback?.Invoke(exception); } } @@ -406,15 +519,18 @@ namespace ChatController.HauptKlassen { try { - var openFileDialog = new OpenFileDialog {Filter = Resource.OpenFileDialogFilter_DocumentsAndImages}; + var openFileDialog = new OpenFileDialog + { + Filter = Resource.OpenFileDialogFilter_Test //Resource.OpenFileDialogFilter_DocumentsAndImages + }; var result = openFileDialog.ShowDialog(); return result == DialogResult.OK ? openFileDialog.FileName : null; } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK); + ExceptionCallback?.Invoke(exception); return null; } } @@ -427,7 +543,7 @@ namespace ChatController.HauptKlassen { return; } - + var message = _UserMessages.Response.Messages.Last(); var sendTime = DateTime.Now; @@ -441,7 +557,7 @@ namespace ChatController.HauptKlassen } var memoryStream = new MemoryStream(file); - var image = System.Drawing.Image.FromStream(memoryStream); + var image = Image.FromStream(memoryStream); using (var bitmap = new Bitmap(image)) { @@ -488,10 +604,11 @@ namespace ChatController.HauptKlassen Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFile), sendTime, message.Smaller_Image, true, pFile, pGroupId, 0)); } + AddSeparators(); } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK); + ExceptionCallback?.Invoke(exception); } } @@ -524,27 +641,30 @@ namespace ChatController.HauptKlassen { Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFileName), sendtime, message.Smaller_Image, true, pFileName, pGroupId, 0)); } + + AddSeparators(); } - public void SendFileToContact(CurrentContact pCurrentContact, string pFile, string pOriginalFilePath) + public void SendFileToContact(Contact currentContact, string pFile, string pOriginalFilePath) { try { - SendFile(pFile, pCurrentContact, pOriginalFilePath); + SendFile(pFile, currentContact, pOriginalFilePath); } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + ExceptionCallback?.Invoke(exception); } } - private void SendFile(string pFile, CurrentContact pContact, string pOriginalFilePath) + // WebRequest + private void SendFile(string pFile, Contact currentContact, string pOriginalFilePath) { if(string.IsNullOrEmpty(pOriginalFilePath)) { return; } - + byte[] mediaFile; using (Stream reader = File.OpenRead(pFile)) { @@ -557,138 +677,24 @@ namespace ChatController.HauptKlassen fileName = fileName.Replace(".bmp", ".jpg"); - SendMediaMessage(fileName, pContact.GroupId, mediaFile); + SendMediaMessage(fileName, currentContact.GroupId, mediaFile); } else { - SendMediaMessage(fileName, pContact.GroupId, mediaFile); + SendMediaMessage(fileName, currentContact.GroupId, mediaFile); } } - - public string ScaleImage(string pFile, string pFormat) - { - try - { - byte[] mediaFile; - using (Stream reader = File.OpenRead(pFile)) - { - mediaFile = Utils.ReadFully(reader); - } - - var memoryStream = new MemoryStream(mediaFile); - var image = System.Drawing.Image.FromStream(memoryStream); - - float width, height; - - if (image.Height < image.Width ) - { - if (image.Height > 1080) - { - var factor = (float)image.Height / 1080; - - height = 1080; - - width = image.Width / factor; - } - else - { - return pFile; - } - } - else if(image.Height < 1080 && image.Width < 1080 ) - { - return pFile; - } - else - { - if (image.Width > 1080) - { - var factor = (float)image.Width / 1080; - - width = 1080; - - height = image.Height / factor; - } - else - { - return pFile; - } - } - - var scaledBitmap = new Bitmap(image, new Size((int) width, (int) height)); - - const int orientationId = 0x0112; - - if (image.PropertyIdList.Contains(orientationId)) { - var item = image.GetPropertyItem(orientationId); - - scaledBitmap.SetPropertyItem(item); - } - - using (var graphics = Graphics.FromImage(image)) - { - graphics.Clear(Color.Transparent); - - graphics.InterpolationMode = InterpolationMode.Low; - - graphics.DrawImage(scaledBitmap, (int) width, (int) height); - } - - var imageConverter = new ImageConverter(); - - var imageData = (byte[])imageConverter.ConvertTo(scaledBitmap, typeof(byte[])); - - var filePath = Path.GetTempPath() + Guid.NewGuid() + pFormat; - - if (pFormat.Equals(".JPG") || pFormat.Equals(".JPE") || pFormat.Equals(".JPEG") || pFormat.Equals(".BMP")) - { - scaledBitmap.Save(filePath, ImageFormat.Jpeg); - } - else if (pFormat.Equals(".PNG")) - { - scaledBitmap.Save(filePath, ImageFormat.Png); - } - else if (pFormat.Equals(".GIF")) - { - scaledBitmap.Save(filePath, ImageFormat.Gif); - } - - if (File.Exists(filePath)) - { - var fileInfo = new FileInfo(filePath); - var fileInfoLength = fileInfo.Length; - - if (ChatDaten.MaxUploadSize < fileInfoLength) - { - File.Delete(filePath); - return string.Empty; - } - } - else - { - return string.Empty; - } - - memoryStream.Dispose(); - memoryStream.Close(); - - return filePath; - } - catch (Exception exception) - { - return pFile; - } - } - + private HttpRequestMessage _HttpRequest; + // WebRequest private async void SendMediaMessage(string pMessage, long pGroupId, byte[] pMediaFile) { try { using (var multiPartContent = new MultipartFormDataContent()) { - var requestUri = new Uri(ChatDaten.ServerUrl + "/api/chat/messages/send"); + var requestUri = new Uri(ChatDaten.ServerUrl + Constants.SendMessageUrl); multiPartContent.Add(new ByteArrayContent(pMediaFile, 0, pMediaFile.Length), "file", pMessage); multiPartContent.Add(new StringContent(pGroupId.ToString()), "groupid"); @@ -709,9 +715,9 @@ namespace ChatController.HauptKlassen var antwortResponse = await httpResponse.Content.ReadAsStringAsync(); } } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK); + ExceptionCallback?.Invoke(exception); } } @@ -747,28 +753,31 @@ namespace ChatController.HauptKlassen } } - private static byte[] DownloadMediaFile(string pFilePath) + private byte[] DownloadMediaFile(string pFilePath) { byte[] mediaFile = null; - + try { using(var webClient = new WebClient()) { + webClient.Credentials = CredentialCache.DefaultCredentials; + webClient.Headers[Constants.Token] = ChatDaten.AuthToken; + webClient.Headers[Constants.CustomerId] = ChatDaten.Kundennummer; mediaFile = webClient.DownloadData(pFilePath); } return mediaFile; } - catch(Exception e) + catch(Exception exception) { - MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK); + ExceptionCallback?.Invoke(exception); } return mediaFile; } - private static void SaveAs(int pFilterType, string pFileName, byte[] pMediaFile) + private void SaveAs(int pFilterType, string pFileName, byte[] pMediaFile) { try { @@ -802,9 +811,9 @@ namespace ChatController.HauptKlassen fileStream.Close(); } } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show("Fehler: "+e.Message,"Fehler",MessageBoxButton.OK); + ExceptionCallback?.Invoke(exception); } } @@ -840,9 +849,9 @@ namespace ChatController.HauptKlassen } } } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK); + ExceptionCallback?.Invoke(exception); } } else @@ -900,59 +909,78 @@ namespace ChatController.HauptKlassen } } - public void ShowProfilePicture(CurrentContact pCurrentContact) + public void ShowProfilePicture(Contact currentContact) { try { using (var form = new Form()) { - var image = new Image {Source = pCurrentContact.Image}; - - var encoder = new BmpBitmapEncoder(); - var memoryStream = new MemoryStream(); - - encoder.Frames.Add(BitmapFrame.Create((BitmapSource) image.Source)); - encoder.Save(memoryStream); - - var imageFromStream = System.Drawing.Image.FromStream(memoryStream); - - var bitmap = new Bitmap(imageFromStream); + var bitmap = currentContact.ProfilePicture; form.StartPosition = FormStartPosition.CenterScreen; - form.Size = bitmap.Size; - form.Height += 60; - form.MinimumSize = new Size(150,150); - - var width = (int) Math.Round(SystemParameters.PrimaryScreenWidth / 1.25); - var height = (int) Math.Round(SystemParameters.PrimaryScreenWidth / 2); - form.MaximumSize = new Size(width,height); + var bitmapWidth = bitmap.Width; + var bitmapHeight = bitmap.Height; + + var aspectRatio = bitmapWidth / (double) bitmapHeight; + + var primaryScreenWidth = SystemParameters.PrimaryScreenWidth; + var primaryScreenHeight = SystemParameters.PrimaryScreenHeight; + + var maxWidth = bitmapWidth; + var maxHeight = bitmapHeight; + + if(maxWidth > primaryScreenWidth || maxHeight > primaryScreenHeight) + { + if(primaryScreenWidth > primaryScreenHeight) + { + maxHeight = (int) (.9 * primaryScreenHeight); + maxWidth = (int) (maxHeight * aspectRatio); + } + else + { + maxWidth = (int) (.9 * primaryScreenWidth); + maxHeight = (int) (maxWidth * aspectRatio); + } + } + + var maximumSize = new Size(maxWidth, maxHeight); + + form.Size = maximumSize; + form.FormBorderStyle = FormBorderStyle.Sizable; - form.MaximizeBox = false; + form.MaximizeBox = false; - form.Text = "ownChat"; + form.Text = currentContact.Name; form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); var pictureBox = new PictureBox { Dock = DockStyle.Fill, Image = bitmap, - SizeMode = PictureBoxSizeMode.CenterImage, - MaximumSize = new Size(500, 500) + SizeMode = PictureBoxSizeMode.Zoom, + Padding = new Padding(0), + Margin = new Padding(0) }; + form.MinimumSize = new Size(232, (int)(232 / aspectRatio)); + + form.Padding = new Padding(0); + form.Margin = new Padding(0); + form.Controls.Add(pictureBox); + form.ShowDialog(); } } - catch (Exception e) + catch (Exception exception) { - MessageBox.Show("Fehler: " + e.Message, "Fehler" , MessageBoxButton.OK); + ExceptionCallback?.Invoke(exception); } } - public void ShowPicture(ChatMessage curItem, Action downloadCompletedCallback) + public void ShowPicture(string originalImage, Action downloadCompletedCallback) { try { @@ -961,19 +989,18 @@ namespace ChatController.HauptKlassen { try { - using (var form = new Form()) + using(var form = new Form()) { - using (var ms = new MemoryStream(e.Result)) + using(var ms = new MemoryStream(e.Result)) { - var image = System.Drawing.Image.FromStream(ms); + var image = Image.FromStream(ms); - - using (var bitmap = new Bitmap(image)) + using(var bitmap = new Bitmap(image)) { short orient = 0; const int orientationId = 0x0112; - if (image.PropertyIdList.Contains(orientationId)) + if(image.PropertyIdList.Contains(orientationId)) { var item = image.GetPropertyItem(orientationId); @@ -990,8 +1017,8 @@ namespace ChatController.HauptKlassen form.ClientSize = bitmap.Size; form.FormBorderStyle = FormBorderStyle.Sizable; form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); - - using (var pictureBox = new PictureBox()) + + using(var pictureBox = new PictureBox()) { pictureBox.Dock = DockStyle.Fill; pictureBox.Image = bitmap; @@ -1008,226 +1035,54 @@ namespace ChatController.HauptKlassen } } } - catch (Exception edf) + catch(Exception exception) { - MessageBox.Show("Fehler: " + edf.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + ExceptionCallback?.Invoke(exception); } - }; - - webClient.DownloadDataAsync(new Uri(curItem.OriginalImage)); - } - catch (Exception e) - { - MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); - } - } - public bool DoSynchronisation(string pApiKey, string pCustomerId) - { - try - { - var endurl = ChatDaten.ServerUrl + "/api/ownchat/sync/schedule/"+pApiKey+"/" +pCustomerId; - - var request = WebRequest.Create(endurl); - - request.Credentials = CredentialCache.DefaultCredentials; - request.Proxy = null; - - var response = request.GetResponse(); - - var serverResponse = Utils.ReadStream(response); - - var definiti = new { result = "" }; - - var jsonDatentyp = JsonConvert.DeserializeAnonymousType(serverResponse, definiti); - - switch (jsonDatentyp.result) - { - case "0": - return true; - case "11": - MessageBox.Show("Kundennummer unbekannt.\nDer Chat wird jetzt geschlossen", "Fehler", MessageBoxButton.OK); - return false; - case "12": - MessageBox.Show("Der API-Key ist falsch -> Auth-Error.\nDer Chat wird jetzt geschlossen", "Fehler", MessageBoxButton.OK); - return false; - case "13": - MessageBox.Show("Es existiert kein API-Key für die angegebene Kundennummer.\nDer Chat wird jetzt geschlossen", "Fehler", MessageBoxButton.OK); - return false; - case "x": - MessageBox.Show("MySQL Error.\nDer Chat wird jetzt geschlossen", "Fehler",MessageBoxButton.OK); - return false; - default: - return false; - } + webClient.DownloadDataAsync(new Uri(originalImage)); } catch (Exception exception) { - MessageBox.Show("Die Verbindung konnte nicht aufgebaut werden.", "Fehler ", MessageBoxButton.OK); - return false; + ExceptionCallback?.Invoke(exception); } } - public long GetMaiximumAllowedFileUploadSize(string pToken, string pCustomerId) + public void ReloadGroupsAsync(Action callback) { - try + var url = ChatDaten.ServerUrl + Constants.GetChatGroupsUrl; + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + + var client = new RestClient(url); + var request = new RestRequest(); + + request.AddHeader(Constants.Token, ChatDaten.AuthToken); + request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer); + + client.ExecuteAsync(request, response => { - var endurl = ChatDaten.ServerUrl + "/api/ownchat/uploadmaxsize"; + var groups = JsonConvert.DeserializeObject(response.Content); - var request = WebRequest.Create(endurl); - request.Headers[Constants.Token] = pToken; - request.Headers[Constants.CustomerId] = pCustomerId; - - request.Credentials = CredentialCache.DefaultCredentials; - request.Proxy = null; - - var response = request.GetResponse(); - - var responseFromServer = Utils.ReadStream(response); - - var definiti = new { file_upload_max_size = "" }; - - var jsonDatentyp = JsonConvert.DeserializeAnonymousType(responseFromServer, definiti); - - return Convert.ToInt64(jsonDatentyp.file_upload_max_size); - } - catch (Exception e) - { - throw; - } + callback?.Invoke(groups); + }); } - public ChatGruppenDaten UpdateGroups() - { - try - { - var endurl = ChatDaten.ServerUrl + Constants.GetChatGroupsUrl; - - var request = WebRequest.Create(endurl); - - request.Credentials = CredentialCache.DefaultCredentials; - request.Headers[Constants.Token] = ChatDaten.AuthToken; - request.Headers[Constants.CustomerId] = ChatDaten.Kundennummer; - - var response = request.GetResponse(); - - var serverResponse = Utils.ReadStream(response); - - response.Close(); - - return !string.IsNullOrEmpty(serverResponse) ? JsonConvert.DeserializeObject(serverResponse) : null; - } - catch (Exception e) - { - MessageBox.Show("Beim Aktualisieren der Kontaktliste ist ein Fehler aufgetreten.\nFehler:\n"+e.Message, "Fehler", MessageBoxButton.OK); - return null; - } - } - - public IOrderedEnumerable GroupklassenAktuallisieren(ChatGruppenDaten chatDaten) + public List GroupklassenAktuallisieren(ChatGruppenDaten chatDaten) { try { _Contacts.Clear(); - foreach (var contact in chatDaten.Response) - { - _Contacts.AddRange(GenerateContactsFromServerResponse(contact.Value)); - } - return _Contacts.OrderByDescending(r => r.TimeStamp); - } - catch (Exception e) - { - MessageBox.Show("Beim Sortieren der aktualisierten Kontakte ist ein Fehler aufgetreten.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); - return null; - } - } + _Contacts.AddRange(GenerateContactsFromServerResponse(chatDaten.Response.Groups.ToArray())); - public Dictionary CheckTimeStampsAtStart(List pContacts) - { - try - { - if (File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName))) - { - var syncData = new Dictionary(); - - using (var streamReader = new StreamReader(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName), true)) - { - string line; - - while ((line = streamReader.ReadLine()) != null) - { - var encodedTextBytes = Convert.FromBase64String(line); - - var plainText = Encoding.UTF8.GetString(encodedTextBytes); - - var splitPlainText = plainText.Split(';'); - - syncData.Add(splitPlainText[0], splitPlainText[1]); - } - } - - var result = new Dictionary(); - - foreach (var contact in pContacts) - { - foreach (var data in syncData) - { - var groupoid = int.Parse(data.Key); - - if (contact.GroupId == groupoid) - { - var datetime = DateTime.Parse(data.Value); - - if (contact.TimeStamp.Equals(datetime)) - { - result.Add(groupoid, datetime); - } - } - } - } - - return result.Count > 0 ? result : null; - } - - return null; - } - catch (Exception e) - { - return null; - } - } - - public void SaveTimeStampsToFile(List pContacts) - { - try - { - if(File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName))) - { - File.SetAttributes(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName), FileAttributes.Normal); - File.Delete(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName)); - } - - using (var streamWriter = new StreamWriter(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName))) - { - Encoding enc = new UTF8Encoding(); - - foreach (var contact in pContacts) - { - var text = contact.GroupId + ";" + contact.TimeStamp+";"; - var bytes = enc.GetBytes(text); - var base64String = Convert.ToBase64String(bytes); - - streamWriter.WriteLine(base64String); - } - - File.SetAttributes(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName), FileAttributes.ReadOnly); - } + return _Contacts; } catch (Exception exception) { - + ExceptionCallback?.Invoke(exception); + return null; } } @@ -1263,8 +1118,10 @@ namespace ChatController.HauptKlassen } var avatar = Utils.AvatarToImageSourceConverter(groupInput.Avatar, groupInput.OnlyEmployees, groupInput.Users.Length > 2); - - contacts.Add(new Contact(groupInput.Name, avatar, groupInput.LastMessage, formattedTime, groupInput.Oid, userIdManage, groupInput.OnlyEmployees, groupInput.Users.Length)); + + var profilePicture = Utils.ConvertAvatarToBitmap(groupInput.Avatar, groupInput.OnlyEmployees, groupInput.Users.Length > 2); + + contacts.Add(new Contact(groupInput.Name, groupInput.LastMessage, formattedTime, groupInput.Oid, userIdManage, groupInput.OnlyEmployees, groupInput.Users.Length, groupInput.CanWrite, groupInput.AccentColor, profilePicture, avatar)); if(pShouldUpdateLastTimeStamp) { @@ -1287,11 +1144,11 @@ namespace ChatController.HauptKlassen { foreach (var message in pMessages) { - var time = DateTime.Parse(message.Timestamp.Date); - var clientZone = TimeZoneInfo.Local; - var formattedTime = TimeZoneInfo.ConvertTimeFromUtc(time, clientZone); + var time = DateTime.Parse(message.Timestamp.Date); + var clientZone = TimeZoneInfo.Local; + var formattedTime = TimeZoneInfo.ConvertTimeFromUtc(time, clientZone); var isLoggedInUsersMessage = ChatDaten.Userid != null && message.UserId == ChatDaten.Userid.Value; - var messageText = message.Text ?? (string.IsNullOrEmpty(message.File) ? string.Empty : message.Original_Filename); + var messageText = message.Text ?? (string.IsNullOrEmpty(message.File) ? string.Empty : message.Original_Filename); if (!string.IsNullOrEmpty(message.File)) { @@ -1304,6 +1161,35 @@ namespace ChatController.HauptKlassen Messages.Add(new ChatMessage(message.User_Name, message.Text, formattedTime, isLoggedInUsersMessage, message.GroupId, message.FileSize)); } } + + AddSeparators(); + } + + private void AddSeparators() + { + var messagesWithoutSeparators = Messages.Where(message => !message.IsSeparator).OrderBy(message => message.SendTime).ToList(); + + var separators = new List(); + + var previousMessage = messagesWithoutSeparators.OrderBy(message => message.SendTime).FirstOrDefault(); + foreach(var message in messagesWithoutSeparators.OrderBy(message => message.SendTime)) + { + if(!message.Equals(previousMessage) && previousMessage != null) + { + if(message.SendTime.Date != previousMessage.SendTime.Date) + { + var separatorMessage = new ChatMessage(null, null, message.SendTime.Date, false, 0, 0) { IsSeparator = true }; + + separators.Add(separatorMessage); + + previousMessage = message; + } + } + } + + messagesWithoutSeparators.AddRange(separators); + + Messages = messagesWithoutSeparators.OrderBy(message => message.SendTime).ToList(); } } } diff --git a/ChatController/HauptKlassen/Login.cs b/ChatController/HauptKlassen/Login.cs index 8109f7a..a13b0bd 100644 --- a/ChatController/HauptKlassen/Login.cs +++ b/ChatController/HauptKlassen/Login.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Net; using System.Web; using System.Windows; +using ChatController.Data; using ChatController.LoginKlassen; using ChatController.Utilities; @@ -14,11 +16,12 @@ namespace ChatController.HauptKlassen { public class Login { - private string _Url = string.Empty; + private string _BaseUrl = string.Empty; - private const string _NewUrl = "https://dict.ownchat.de/api/server/resolve/1/"; + private const string DictionaryServerUrl = "https://dict.ownchat.de/api/server/resolve/1/"; public string ServerUrl { get; set; } = string.Empty; + private string _AuthToken = string.Empty; private readonly string _UserName; @@ -29,10 +32,9 @@ namespace ChatController.HauptKlassen private long? _UserId; - private bool _ownchatVerbindungsaufbauOK; - private bool _gruppeholenverbindungsaufbauOK; + private bool _OwnchatVerbindungsaufbauOk; + private bool _GruppeholenverbindungsaufbauOk; - private AuthenticationData _serverconect; private UserDaten _LoggedInUser; private ChatGruppenDaten _AllGroups; @@ -44,61 +46,146 @@ namespace ChatController.HauptKlassen _ChatCode = pChatCode; _UserName = pUserName; _Password = pPassword; - _ApiKey = "0000";//default, damit nichts kaputt geht + _ApiKey = "0000"; } + // Wird im BeWoPlaner benutzt public Login(string pTenant, string pChatCode, string pUserName, string pPassword, string pApiKey) { - _Tenant = pTenant; + _Tenant = pTenant; _ChatCode = pChatCode; _UserName = pUserName; _Password = pPassword; - _ApiKey = pApiKey; + _ApiKey = pApiKey; } - - // - public Login(string pTenant) + + // Wird im BeWoPlaner benutzt + public Login(string tenant, Action callback) { - _Tenant = pTenant; + _Tenant = tenant; _ShouldShowMessageBox = false; - ServerErmittlung(); + + LookupServerUrlAsync(isSuccessful => { callback(ServerUrl); }); } public ChatDatenUebergabe AnmeldevorgangDurchFuehren() { - if(ServerErmittlung()){ - var dic = new Dictionary - { - {"username", _UserName}, + if(ServerErmittlung()) + { + var dic = new Dictionary + { + { "username", _UserName}, { "password", _Password}, { "chatcode", _ChatCode} - }; + }; - VerbindeMitChatServer(dic); - - if (_ownchatVerbindungsaufbauOK) - { - GetGroups(); - } - - if (_gruppeholenverbindungsaufbauOK) - { - var maxUploadSize = GetMaiximumAllowedFileUploadSize(_AuthToken,_Tenant); + VerbindeMitChatServer(dic); - return new ChatDatenUebergabe(_serverconect, _LoggedInUser, _AllGroups, ServerUrl, _AuthToken, _UserId, _Tenant, _ApiKey, maxUploadSize); - } - } + if(_OwnchatVerbindungsaufbauOk) + { + GetGroups(); + } - return null; + if(_GruppeholenverbindungsaufbauOk) + { + var maxUploadSize = GetMaiximumAllowedFileUploadSize(_AuthToken, _Tenant); + + return new ChatDatenUebergabe(_LoggedInUser, _AllGroups, ServerUrl, _AuthToken, _UserId, _Tenant, _ApiKey, maxUploadSize); + } + } + + return null; } - + + public void DoLoginAsync(Action callback, Action exceptionCallback) + { + try + { + LookupServerUrlAsync(isConnectedWithServer => + { + if(isConnectedWithServer) + { + ConnectWithChatServerAsync( + isSuccessfullyLoggedIn => + { + if (isSuccessfullyLoggedIn) + { + GetGroupsAsync(wasSuccessful => + { + if (wasSuccessful) + { + GetMaximumAllowedFileUploadSizeAsync(maxUploadFileSize => + { + callback?.Invoke(new ChatDatenUebergabe(_LoggedInUser, _AllGroups, ServerUrl, _AuthToken, _UserId, _Tenant, _ApiKey, maxUploadFileSize)); + }); + } + }); + } + }, + + errorMessage => { exceptionCallback?.Invoke(errorMessage); }); + } + }); + } + catch (Exception exception) + { + callback?.Invoke(null); + } + } + + public void LookupServerUrlAsync(Action callback) + { + try + { + if(!string.IsNullOrWhiteSpace(ServerUrl)) + { + callback?.Invoke(false); + return; + } + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + + var client = new RestClient(DictionaryServerUrl); + var request = new RestRequest(_Tenant); + + client.ExecuteAsync(request, response => + { + var lookupResult = JsonConvert.DeserializeObject(response.Content); + + _BaseUrl = lookupResult.Url; + ServerUrl = _BaseUrl; + + var result = false; + + switch (lookupResult.Status) + { + case 0: + result = true; + break; + case 1: + MessageBox.Show("Fehler: Kundennummer unbekannt.\nBitte überprüfen Sie die Anmeldeinformationen.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); + break; + case 2: + MessageBox.Show("Der Diensttyp ist für die angegebene Kundennummer nicht definiert.", "ownChat Info", MessageBoxButton.OK, MessageBoxImage.Asterisk); + break; + } + + callback?.Invoke(result); + }); + } + catch (Exception exception) + { + MessageBox.Show("Fehler: Es konnte keine Verbindung aufgebaut werden.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + } + } + public bool ServerErmittlung() { if (string.IsNullOrEmpty(ServerUrl)) { try { - var serverURl = _NewUrl + _Tenant; + var serverURl = DictionaryServerUrl + _Tenant; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var request = WebRequest.Create(serverURl); @@ -144,7 +231,7 @@ namespace ChatController.HauptKlassen return false; } - _Url = jsonDatentyp.Url; + _BaseUrl = jsonDatentyp.Url; } catch (Exception eds) { @@ -170,7 +257,7 @@ namespace ChatController.HauptKlassen return false; } - _Url = jsonDatentyp.Url; + _BaseUrl = jsonDatentyp.Url; } catch (Exception e) { @@ -183,7 +270,7 @@ namespace ChatController.HauptKlassen response.Close(); - ServerUrl = _Url; + ServerUrl = _BaseUrl; return true; } catch (Exception e) @@ -204,7 +291,7 @@ namespace ChatController.HauptKlassen { try { - var endurl = _Url + "/api/user/loginwithchatcode"; + var endurl = _BaseUrl + Constants.LoginWithChatCodeUrl; var requestBody = postparameter.Keys.Aggregate(string.Empty, (current, key) => current + HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(postparameter[key]) + "&"); @@ -219,6 +306,7 @@ namespace ChatController.HauptKlassen if (response.StatusCode == HttpStatusCode.OK) { + Debug.WriteLine(response.Content); var userDaten = JsonConvert.DeserializeObject(response.Content); if(userDaten.Success) @@ -226,28 +314,31 @@ namespace ChatController.HauptKlassen _AuthToken = userDaten.Response.User.Token; _UserId = userDaten.Response.User.Oid; + Utils.AuthToken = _AuthToken; + Utils.Tenant = _Tenant; + _LoggedInUser = userDaten; - _ownchatVerbindungsaufbauOK = true; + _OwnchatVerbindungsaufbauOk = true; } else { - if(userDaten.Errors.chatcode_failed != null) + if(userDaten.Error?.ChatCodeFailed != null) { if(_ShouldShowMessageBox) { - MessageBox.Show("Fehler: " + userDaten.Errors.chatcode_failed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error); + MessageBox.Show("Fehler: " + userDaten.Error.ChatCodeFailed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error); } } - else if(userDaten.Errors.login_failed != null) + else if(userDaten.Error?.LoginFailed != null) { if(_ShouldShowMessageBox) { - MessageBox.Show("Fehler: " + userDaten.Errors.login_failed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error); + MessageBox.Show("Fehler: " + userDaten.Error.LoginFailed[0] + "\nBitte überprüfen Sie die Anmeldeinformationen.", "Info", MessageBoxButton.OK, MessageBoxImage.Error); } } - _ownchatVerbindungsaufbauOK = false; + _OwnchatVerbindungsaufbauOk = false; } } else @@ -268,7 +359,7 @@ namespace ChatController.HauptKlassen { try { - var endurl = _Url + Constants.GetChatGroupsUrl; + var endurl = _BaseUrl + Constants.GetChatGroupsUrl; var request = WebRequest.Create(endurl); @@ -282,11 +373,13 @@ namespace ChatController.HauptKlassen if (!string.IsNullOrEmpty(serverResponse)) { + Debug.WriteLine($"'ChatGruppenDaten' (Gruppen): {serverResponse}"); + var jsonDaten = JsonConvert.DeserializeObject(serverResponse); _AllGroups = jsonDaten; - _gruppeholenverbindungsaufbauOK = true; + _GruppeholenverbindungsaufbauOk = true; } } } @@ -299,6 +392,79 @@ namespace ChatController.HauptKlassen } } + private void ConnectWithChatServerAsync(Action callback, Action exceptionCallback) + { + var url = _BaseUrl + Constants.LoginWithChatCodeUrl; + var requestBody = $"{HttpUtility.UrlEncode("username")}={HttpUtility.UrlEncode(_UserName)}&{HttpUtility.UrlEncode("password")}={HttpUtility.UrlEncode(_Password)}&{HttpUtility.UrlEncode("chatcode")}={HttpUtility.UrlEncode(_ChatCode)}"; + + var client = new RestClient(url); + var request = new RestRequest(Method.POST); + + request.AddHeader(Constants.ContentTypeKey, Constants.FormUrlEncodedContentTypeValue); + request.AddParameter(Constants.CustomerId, _Tenant, ParameterType.HttpHeader); + request.AddParameter(Constants.FormUrlEncodedContentTypeValue, requestBody, ParameterType.RequestBody); + + client.PostAsync(request, (response, handle) => + { + Debug.WriteLine(response.Content); + + var connectionData = JsonConvert.DeserializeObject(response.Content); + + if (connectionData.Success) + { + _AuthToken = connectionData.Response.User.Token; + _UserId = connectionData.Response.User.Oid; + + Utils.AuthToken = _AuthToken; + Utils.Tenant = _Tenant; + + _LoggedInUser = connectionData; + + callback?.Invoke(true); + } + else + { + var errorMessage = string.Empty; + + if (connectionData.Error?.ChatCodeFailed != null) + { + errorMessage = $"Fehler: {connectionData.Error.ChatCodeFailed[0]}"; + } + else if (connectionData.Error?.LoginFailed != null) + { + errorMessage = $"Fehler: {connectionData.Error.LoginFailed[0]}"; + } + + if (!string.IsNullOrWhiteSpace(errorMessage)) + { + exceptionCallback?.Invoke(errorMessage); + } + } + }); + } + + private void GetGroupsAsync(Action callback) + { + var url = _BaseUrl + Constants.GetChatGroupsUrl; + + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + + var client = new RestClient(url); + + var request = new RestRequest(); + request.AddHeader(Constants.Token, _AuthToken); + request.AddHeader(Constants.CustomerId, _Tenant); + + client.ExecuteAsync(request, response => + { + var groups = JsonConvert.DeserializeObject(response.Content); + + _AllGroups = groups; + + callback?.Invoke(true); + }); + } + #region Maximal erlaubte File Größe public long GetMaiximumAllowedFileUploadSize(string pToken, string pCustomerId) @@ -333,7 +499,27 @@ namespace ChatController.HauptKlassen return maximumFileSize; } - + + public void GetMaximumAllowedFileUploadSizeAsync(Action callback) + { + var url = ServerUrl + Constants.MaxUploadFileSizeUrl; + + var client = new RestClient(url); + var request = new RestRequest(); + + request.AddHeader(Constants.Token, _AuthToken); + request.AddHeader(Constants.CustomerId, _Tenant); + + client.ExecuteAsync(request, response => + { + var maxFileSizeAnonymous = JsonConvert.DeserializeAnonymousType(response.Content, new {file_upload_max_size = string.Empty}); + + var maxUploadFileSize = Convert.ToInt64(maxFileSizeAnonymous.file_upload_max_size); + + callback?.Invoke(maxUploadFileSize); + }); + } + #endregion } } diff --git a/ChatController/LoginControl.xaml b/ChatController/LoginControl.xaml index 9f0a4c9..3fda31a 100644 --- a/ChatController/LoginControl.xaml +++ b/ChatController/LoginControl.xaml @@ -3,68 +3,61 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" - mc:Ignorable="d" - d:DesignHeight="300" d:DesignWidth="300"> + mc:Ignorable="d"> - - - - - - - + + + + + + + - - - - - - - - - - + - - - - - - + - - + + + + + + + + + + + + + + + - - + + - - + + - - + + - - + + - - - - - - - - + + + + diff --git a/ChatController/LoginControl.xaml.cs b/ChatController/LoginControl.xaml.cs index d0811aa..18e5b72 100644 --- a/ChatController/LoginControl.xaml.cs +++ b/ChatController/LoginControl.xaml.cs @@ -1,52 +1,95 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.IO; -using System.Net; using System.Reflection; +using System.Runtime.CompilerServices; using System.Text; -using System.Web; using System.Windows; -using System.Windows.Input; - +using System.Windows.Controls; +using System.Windows.Threading; +using ChatController.Annotations; using ChatController.HauptKlassen; using ChatController.LoginKlassen; -using Newtonsoft.Json; - +using ChatController.Utilities; +using ChatController.Utilities.Extensions; using Cursors = System.Windows.Input.Cursors; -using KeyEventArgs = System.Windows.Input.KeyEventArgs; using MessageBox = System.Windows.MessageBox; using Path = System.IO.Path; namespace ChatController { - public partial class LoginControl + public partial class LoginControl : INotifyPropertyChanged { + private ChatControlWaitLayer _WaitLayer; + + public string UserName + { + get => _Benutzername; + + set + { + if (!Equals(_Benutzername, value)) + { + _Benutzername = value; + OnPropertyChanged(nameof(UserName)); + } + } + } + + public string Password + { + get => PasswordBox.Password; + + set => PasswordBox.Password = value; + } + + public string ChatCode + { + get => _ChatCode; + + set + { + if(!Equals(_ChatCode, value)) + { + _ChatCode = value; + OnPropertyChanged(nameof(ChatCode)); + } + } + } + + public string Tenant + { + get => _Kundennummer; + + set + { + if(!Equals(_Kundennummer, value)) + { + _Kundennummer = value; + OnPropertyChanged(nameof(Tenant)); + } + } + } + public delegate void LoginDelegate(ChatDatenUebergabe cdu); public event LoginDelegate OnLogin; - private string _newUrl = "https://dict.ownchat.de/api/server/resolve/1/"; - private string _benutzername = ""; - private string _passwort = ""; - private string _chatCode = ""; - private string _kundennummer = ""; - private string _authToken = ""; - private string _version = "1.3"; + private string _Benutzername = string.Empty; + private string _ChatCode = string.Empty; + private string _Kundennummer = string.Empty; + private readonly string _Version = "1.3"; + + public string Version => $"Version: {_Version}"; public LoginControl() { InitializeComponent(); - //encrypt verschlüsselte datei + DataContext = this; + LeseDateiFallsVorhanden(); - - //var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; - lblVersion.Content = $"Version: {_version}"; - -#if DEBUG - TextBoxBenutzerName.Text = "BaeurleC"; - TextBoxPasswort.Password = "asFdgAE5ERfdsew4!"; -#endif } private void AnmeldenButton_OnClick(object sender, RoutedEventArgs e) @@ -54,35 +97,67 @@ namespace ChatController Anmelden(); } - private void TextBoxPasswort_OnKeyUp(object sender, KeyEventArgs e) + private void StartWaiting() { - if (e.Key == Key.Return) + Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) StartWaitingImmediately); + } + + private void StartWaitingImmediately() + { + if (_WaitLayer == null) { - Anmelden(); + _WaitLayer = new ChatControlWaitLayer(); + Panel.SetZIndex(_WaitLayer, int.MaxValue); + RootGrid.Children.Add(_WaitLayer); + _WaitLayer.RefreshUI(); } } - + + private void EndWaiting() + { + Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) delegate + { + if (_WaitLayer != null) + { + RootGrid.Children.Remove(_WaitLayer); + _WaitLayer = null; + } + }); + } + private void Anmelden() { try { - //TODO Abfrage einführen, die prüft, ob eine Verbindung überhaupt hergestellt werden kann | Fehlermeldungen genauer definieren - if (!TextBoxKundennummer.Text.Equals("") && !TextBoxChatCode.Text.Equals("") && !TextBoxBenutzerName.Text.Equals("") && !TextBoxPasswort.Password.Equals("")) + if (!string.IsNullOrWhiteSpace(_Kundennummer) && !string.IsNullOrWhiteSpace(_ChatCode) && !string.IsNullOrWhiteSpace(_Benutzername) && Password.Length > 0) { - Cursor = Cursors.Wait; + StartWaiting(); - var _login = new Login(TextBoxKundennummer.Text, TextBoxChatCode.Text, TextBoxBenutzerName.Text, TextBoxPasswort.Password); + var login = new Login(_Kundennummer, _ChatCode, _Benutzername, PasswordBox.Password); - var x = _login.AnmeldevorgangDurchFuehren(); - - if (OnLogin != null && x != null) + login.DoLoginAsync(chatDatenUebergabe => { - AutosetDaten(); + this.Dispatch(() => + { + EndWaiting(); - OnLogin?.Invoke(x); - } + if(chatDatenUebergabe != null) + { + AutosetDaten(); - Cursor = Cursors.Arrow; + OnLogin?.Invoke(chatDatenUebergabe); + } + }); + }, + errorMessage => + { + this.Dispatch(() => + { + EndWaiting(); + + MessageBox.Show(errorMessage, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + }); + }); } else { @@ -92,183 +167,78 @@ namespace ChatController catch (Exception exception) { MessageBox.Show("Fehler: " + exception.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); + EndWaiting(); Cursor = Cursors.Arrow; } - } - - #region Speichern / Laden / Löschen der Datei - - #region wird vorerst nicht gebraucht - private void SpeichereDatenInDatei() - { - try - { - if (!File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"))) { - using (StreamWriter sw = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"))) - { - - Encoding enc = new UTF8Encoding(); - //var byt = enc.GetBytes(TextBoxKundennummer.Text); - //var bytes = Convert.ToBase64String(byt); - - //var byt2 = enc.GetBytes(TextBoxChatCode.Text); - //var bytes2 = Convert.ToBase64String(byt2); - - var byt3 = enc.GetBytes(TextBoxBenutzerName.Text); - var bytes3 = Convert.ToBase64String(byt3); - - - var byt4 = enc.GetBytes(TextBoxPasswort.Password); - var bytes4 = Convert.ToBase64String(byt4); - - //var byt5 = enc.GetBytes(Merken.IsChecked.ToString()); - //var bytes5 = Convert.ToBase64String(byt5); - - - //sw.WriteLine(bytes); - //sw.WriteLine(bytes2); - sw.WriteLine(bytes3); - sw.WriteLine(bytes4); - //sw.WriteLine(bytes5); - - File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"), FileAttributes.ReadOnly); - } - } - } - catch (Exception e) - { - MessageBox.Show("Ups, da ist was schief gelaufen: \n" + e.Message, "Fehler", MessageBoxButton.OK); - } } - private void LoescheGespeicherteDatei() + private void LoadTenantAndChatCodeFromFile() { try { - if (File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"))) + if(File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName))) { - File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"), FileAttributes.Normal); - File.Delete(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt")); - } - } - catch (Exception e) - { - MessageBox.Show("Ups, da ist was schief gelaufen: \n" + e.Message, "Fehler", MessageBoxButton.OK); - } - } - #endregion - - private void LeseDateiFallsVorhanden() - { - try - { - if (File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChat.txt"))) - { - List merkdaten = new List(); - using (StreamReader sr = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChat.txt"), true)) + var lines = new List(); + using(var streamReader = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), true)) { - string line = ""; + string line; - while ((line = sr.ReadLine()) != null) + while((line = streamReader.ReadLine()) != null) { var encodedTextBytes = Convert.FromBase64String(line); - string plainText = Encoding.UTF8.GetString(encodedTextBytes); + var plainText = Encoding.UTF8.GetString(encodedTextBytes); - merkdaten.Add(plainText); + lines.Add(plainText); } } - if (merkdaten.Count == 2) + if(lines.Count == 2) { - TextBoxKundennummer.Text = merkdaten[0]; - TextBoxChatCode.Text = merkdaten[1]; + _Kundennummer = lines[0]; + _ChatCode = lines[1]; } } - - - //if (File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"))) { - - // List daten = new List(); - // using (StreamReader sr = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), "OwnChatX1253781.txt"), true)) - // { - // string line = ""; - - // while ((line = sr.ReadLine()) != null) - // { - // var encodedTextBytes = Convert.FromBase64String(line); - - // string plainText = Encoding.UTF8.GetString(encodedTextBytes); - - // daten.Add(plainText); - // } - // } - - // if(daten.Count == 3) { - - // TextBoxBenutzerName.Text = daten[0]; - // TextBoxPasswort.Password = daten[1]; - // // Merken.IsChecked = Convert.ToBoolean(daten[2]); - // } - //} } - catch (Exception e) + catch(Exception e) { - MessageBox.Show("Ups, da ist was schief gelaufen: \n" + e.Message, "Fehler", MessageBoxButton.OK); + MessageBox.Show("Fehler: \n" + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); } } + private void LeseDateiFallsVorhanden() + { + LoadTenantAndChatCodeFromFile(); + } + private void AutosetDaten() { try { - if (!File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt"))) + if(File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName))) { - using ( - StreamWriter sw = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt"))) - { - - Encoding enc = new UTF8Encoding(); - var byt = enc.GetBytes(TextBoxKundennummer.Text); - var bytes = Convert.ToBase64String(byt); - - var byt2 = enc.GetBytes(TextBoxChatCode.Text); - var bytes2 = Convert.ToBase64String(byt2); - - sw.WriteLine(bytes); - sw.WriteLine(bytes2); - - File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt"), - FileAttributes.ReadOnly); - } + File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), FileAttributes.Normal); + File.Delete(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName)); } - else + + using(var streamWriter = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName))) { - File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt"), FileAttributes.Normal); - File.Delete(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt")); + Encoding utf8Encoding = new UTF8Encoding(); + var tenantBytes = utf8Encoding.GetBytes(_Kundennummer); + var encodedTenant = Convert.ToBase64String(tenantBytes); - using ( - StreamWriter sw = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt"))) - { + var chatCodeBytes = utf8Encoding.GetBytes(_ChatCode); + var encodedChatCode = Convert.ToBase64String(chatCodeBytes); - Encoding enc = new UTF8Encoding(); - var byt = enc.GetBytes(TextBoxKundennummer.Text); - var bytes = Convert.ToBase64String(byt); + streamWriter.WriteLine(encodedTenant); + streamWriter.WriteLine(encodedChatCode); - var byt2 = enc.GetBytes(TextBoxChatCode.Text); - var bytes2 = Convert.ToBase64String(byt2); - - sw.WriteLine(bytes); - sw.WriteLine(bytes2); - - File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChat.txt"), - FileAttributes.ReadOnly); - } + File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), Constants.TenantAndChatCodeFileName), FileAttributes.ReadOnly); } } catch (Exception e) { - MessageBox.Show("Ups, da ist was schief gelaufen: \n" + e.Message, "Fehler", MessageBoxButton.OK); + MessageBox.Show("Fehler: \n" + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); } } @@ -276,19 +246,20 @@ namespace ChatController { try { - string localAppData = Environment.GetFolderPath( - Environment.SpecialFolder.LocalApplicationData); - string companyFilePath - = Path.Combine(localAppData, "beyondSoft"); + var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + var companyFilePath = Path.Combine(localAppData, "beyondSoft"); if (!Directory.Exists(companyFilePath)) + { Directory.CreateDirectory(companyFilePath); + } - string bewoFilePath - = Path.Combine(companyFilePath, "OwnChat"); + var bewoFilePath = Path.Combine(companyFilePath, "OwnChat"); if (!Directory.Exists(bewoFilePath)) + { Directory.CreateDirectory(bewoFilePath); + } return bewoFilePath; } @@ -301,157 +272,17 @@ namespace ChatController return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } - #endregion - - //Neue Region zum VErschlüsseln und entschlüsseln der Daten - #region Verschlüsseln/Entschlüsseln via Link // wird ersmal nicht mehr gebraucht - - //TODO Kann erst nach erfolgreichem Login verschlüsselt werden - - private bool Verschluss() - { - try - { - string URl = _newUrl + "api/ownchat/user/encryptcredentials"; - - string postdaten = ""; - - Dictionary postparameter = new Dictionary(); - - postparameter.Add("username", _benutzername); - postparameter.Add("password", _passwort); - - //neu | hinzufügen laut document - postparameter.Add("chatcode", _chatCode); - - int i = 0; - foreach (var key in postparameter.Keys) - { - //hier noch chatcode übergeben - postdaten += HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(postparameter[key]) + "&"; - - } - - WebRequest requesten = WebRequest.Create(URl); - - requesten.Method = "POST"; - requesten.ContentType = "application/x-www-form-urlencoded"; - requesten.Headers["Token"] = _authToken; - requesten.Headers["CustomerID"] = _kundennummer; - - byte[] daten = Encoding.ASCII.GetBytes(postdaten); - - requesten.ContentLength = daten.Length; - - try - { - Stream requestStream = requesten.GetRequestStream(); - - requestStream.Write(daten, 0, daten.Length); - - requestStream.Close(); - - } - catch (Exception e) - { - MessageBox.Show("Es konnte keine Verbindung aufgebaut werden.", "Fehler", MessageBoxButton.OK); - return false; - } - - //response bereich | Verarbeiten - HttpWebResponse myHttpWebResponse = (HttpWebResponse)requesten.GetResponse(); - - Stream responseStream = myHttpWebResponse.GetResponseStream(); - - StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default); - - var pageContent = myStreamReader.ReadToEnd(); - - - //Bereich zum Verarbeiten der Erhaltenen Daten - var definiti = new { encryped = ""}; - - var jsonDatentyp = JsonConvert.DeserializeAnonymousType(pageContent, definiti); - - - - - - - return true; - } - catch (Exception e) - { - MessageBox.Show("Beim Verschlüsseln ist was schief gelaufen. \n" + e.Message,"Fehler",MessageBoxButton.OK); - return false; - } - } - - private byte[] mediaDatei; - - - //TODO Entschluss weiter ausprogrammieren - private bool Entschluss() - { - try - { - string URl = _newUrl + "api/ownchat/user/decryptcredentials"; - - - WebRequest requesten = WebRequest.Create(URl); - - requesten.Method = "POST"; - requesten.ContentType = "application/x-www-form-urlencoded"; - requesten.Headers["CustomerID"] = _kundennummer; - - byte[] daten = mediaDatei; - - requesten.ContentLength = daten.Length; - - try - { - Stream requestStream = requesten.GetRequestStream(); - - requestStream.Write(daten, 0, daten.Length); - - requestStream.Close(); - - } - catch (Exception e) - { - MessageBox.Show("Es konnte keine Verbindung aufgebaut werden.", "Fehler", MessageBoxButton.OK); - return false; - } - - //erhalte response - HttpWebResponse myHttpWebResponse = (HttpWebResponse)requesten.GetResponse(); - - Stream responseStream = myHttpWebResponse.GetResponseStream(); - - StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default); - - var pageContent = myStreamReader.ReadToEnd(); - - //Bereich zum Verarbeiten der Erhaltenen Daten - var definiti = new { encrypted = "" }; - - var jsonDatentyp = JsonConvert.DeserializeAnonymousType(pageContent, definiti); - - - return true; - } - catch (Exception e) - { - MessageBox.Show("Beim Entschlüsseln ist was schief gelaufen. \n" + e.Message, "Fehler", MessageBoxButton.OK); - return false; - } - } - #endregion - - public void Login() { Anmelden(); } + + public event PropertyChangedEventHandler PropertyChanged; + + [NotifyPropertyChangedInvocator] + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } } } diff --git a/ChatController/LoginKlassen/ChatDatenUebergabe.cs b/ChatController/LoginKlassen/ChatDatenUebergabe.cs index 3e64c0c..9e5e760 100644 --- a/ChatController/LoginKlassen/ChatDatenUebergabe.cs +++ b/ChatController/LoginKlassen/ChatDatenUebergabe.cs @@ -2,47 +2,33 @@ { public class ChatDatenUebergabe { - private AuthenticationData _serverconect { get; } - private UserDaten _angemeldeterUser { get; } - private ChatGruppenDaten _alleGruppen { get; } + public UserDaten LoggedInUser { get; } - private string _ServerUrl { get; } - private string _AuthToken { get; } - private long? _Userid { get; } - private string _Tenant { get; } - private string _ApiKey { get; } - private long _MaxUploadSize { get; } + public ChatGruppenDaten AlleGruppen { get; } - public ChatDatenUebergabe(AuthenticationData serverConect, UserDaten angemeldeterUser, ChatGruppenDaten alleGruppen, string serverUrl, string authToken, long? userid, string kundennummer, string apikey,long maxUploadSize) + public string ServerUrl { get; } + + public string AuthToken { get; } + + public long? Userid { get; } + + public string Kundennummer { get; } + + public string ApiKey { get; } + + public long MaxUploadSize { get; } + + public ChatDatenUebergabe(UserDaten loggedInUser, ChatGruppenDaten alleGruppen, string serverUrl, string authToken, long? userid, string kundennummer, string apikey,long maxUploadSize) { - _serverconect = serverConect; - _angemeldeterUser = angemeldeterUser; - _alleGruppen = alleGruppen; + LoggedInUser = loggedInUser; + AlleGruppen = alleGruppen; - _ServerUrl = serverUrl; - _AuthToken = authToken; - _Userid = userid; - _Tenant = kundennummer; - _ApiKey = apikey; - _MaxUploadSize = maxUploadSize; + ServerUrl = serverUrl; + AuthToken = authToken; + Userid = userid; + Kundennummer = kundennummer; + ApiKey = apikey; + MaxUploadSize = maxUploadSize; } - - public AuthenticationData Serverconect => _serverconect; - - public UserDaten AngemeldeterUser => _angemeldeterUser; - - public ChatGruppenDaten AlleGruppen => _alleGruppen; - - public string ServerUrl => _ServerUrl; - - public string AuthToken => _AuthToken; - - public long? Userid => _Userid; - - public string Kundennummer => _Tenant; - - public string ApiKey => _ApiKey; - - public long MaxUploadSize => _MaxUploadSize; } } diff --git a/ChatController/LoginKlassen/ChatGruppenDaten.cs b/ChatController/LoginKlassen/ChatGruppenDaten.cs index 1f9f934..ffc784d 100644 --- a/ChatController/LoginKlassen/ChatGruppenDaten.cs +++ b/ChatController/LoginKlassen/ChatGruppenDaten.cs @@ -1,14 +1,15 @@ using System.Collections.Generic; using System.IO; +using Newtonsoft.Json; namespace ChatController.LoginKlassen { + /// + /// Konvertiertes Objekt vom Server mit den Gruppen, Meldungen, Fehlern und ob die Abfragen an den Server erfolgreich war + /// public class ChatGruppenDaten { - public Dictionary Response { get; set; } - public string Message { get; set; } - public string Errors { get; set; } - public bool Success { get; set; } + public ChatGruppenDatenResponse Response { get; set; } } public class GroupInput @@ -20,13 +21,22 @@ namespace ChatController.LoginKlassen public GroupLatestMessage LastMessage { get; set; } public GroupUsers[] Users { get; set; } public bool OnlyEmployees { get; set; } + + [JsonProperty("accent_color")] + public string AccentColor { get; set; } + + [JsonProperty("i_can_write")] + public bool CanWrite { get; set; } + + [JsonProperty("i_can_see_participants")] + public bool CanSeeParticipants { get; set; } } public class GroupLatestMessage { public long Id { get; set; } - private string _Text; + private string _Text; public string Text { get @@ -78,4 +88,9 @@ namespace ChatController.LoginKlassen public int TimeZoneType { get; set; } public string TimeZone { get; set; } } + + public class ChatGruppenDatenResponse + { + public List Groups { get; set; } + } } diff --git a/ChatController/LoginKlassen/UserDaten.cs b/ChatController/LoginKlassen/UserDaten.cs index 4f6bcfa..5ac46ef 100644 --- a/ChatController/LoginKlassen/UserDaten.cs +++ b/ChatController/LoginKlassen/UserDaten.cs @@ -10,16 +10,12 @@ namespace ChatController.LoginKlassen public string Message { get; set; } - public Tetserror Errors { get; set; } + [JsonProperty("errors")] + public OwnChatLoginError Error { get; set; } public bool Success { get; set; } } - public class InputTest - { - public OwnChatLoginResponse User { get; set; } - } - public class OwnChatLoginResponse { [JsonProperty("file_upload_max_size")] @@ -30,10 +26,13 @@ namespace ChatController.LoginKlassen public OwnChatUser User { get; set; } } - public class Tetserror + public class OwnChatLoginError { - public string[] chatcode_failed{ get; set; } - public string[] login_failed { get; set; } + [JsonProperty("chatcode_failed")] + public string[] ChatCodeFailed { get; set; } + + [JsonProperty("login_failed")] + public string[] LoginFailed { get; set; } } public class OwnChatUser diff --git a/ChatController/Resource.Designer.cs b/ChatController/Resource.Designer.cs index 08f05a8..06739b1 100644 --- a/ChatController/Resource.Designer.cs +++ b/ChatController/Resource.Designer.cs @@ -106,6 +106,15 @@ namespace ChatController { } } + /// + /// Looks up a localized string similar to Office Dokumente und Bilder |*.doc;*.docx;*.xls;*.ppt;*.txt;*.pdf;*.jpg;*.png;*.jpeg;*.jpe;*.gif;*.bmp. + /// + public static string OpenFileDialogFilter_Test { + get { + return ResourceManager.GetString("OpenFileDialogFilter_Test", resourceCulture); + } + } + /// /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// diff --git a/ChatController/Resource.resx b/ChatController/Resource.resx index d61810c..887d38f 100644 --- a/ChatController/Resource.resx +++ b/ChatController/Resource.resx @@ -160,4 +160,7 @@ ownChatNewMessageSync.txt + + Office Dokumente und Bilder |*.doc;*.docx;*.xls;*.ppt;*.txt;*.pdf;*.jpg;*.png;*.jpeg;*.jpe;*.gif;*.bmp + \ No newline at end of file diff --git a/ChatController/Utilities/Constants.cs b/ChatController/Utilities/Constants.cs index 1ef15ea..3295501 100644 --- a/ChatController/Utilities/Constants.cs +++ b/ChatController/Utilities/Constants.cs @@ -20,9 +20,16 @@ namespace ChatController.Utilities public static readonly string GetChatGroupsUrl = "/api/chat/groups"; public static readonly string LoadMessagesForGroupUrl = "/api/chat/messages?groupid="; public static readonly string LoadOwnChatNewsUrl = "/api/ownchat/news/"; + public static readonly string SendMessageUrl = "/api/chat/messages/send"; public static readonly string UrlPageParameter = "&page="; public static readonly int NotificationTimeout = 1500; + + public static readonly string ContentTypeKey = "content-type"; + public static readonly string FormUrlEncodedContentTypeValue = "application/x-www-form-urlencoded"; + public static readonly string MultipartContentTypeValue = "multipart/form-data"; + + public static readonly string TenantAndChatCodeFileName = "ownChat.txt"; } } diff --git a/ChatController/Utilities/Extensions/ControlExtensions.cs b/ChatController/Utilities/Extensions/ControlExtensions.cs new file mode 100644 index 0000000..280f963 --- /dev/null +++ b/ChatController/Utilities/Extensions/ControlExtensions.cs @@ -0,0 +1,21 @@ +using System; +using System.Windows; +using System.Windows.Threading; + +namespace ChatController.Utilities.Extensions +{ + public static class ControlExtensions + { + private static readonly Action _EmptyDelegate = delegate { }; + + public static void Dispatch(this DispatcherObject p, Action action) + { + p.Dispatcher.BeginInvoke(DispatcherPriority.Normal, action); + } + + public static void RefreshUI(this UIElement uiElement) + { + uiElement.Dispatcher.Invoke(DispatcherPriority.Render, _EmptyDelegate); + } + } +} diff --git a/ChatController/Utilities/FileUtils.cs b/ChatController/Utilities/FileUtils.cs new file mode 100644 index 0000000..598d0cd --- /dev/null +++ b/ChatController/Utilities/FileUtils.cs @@ -0,0 +1,131 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; + +namespace ChatController.Utilities +{ + public class FileUtils + { + public static string ScaleImage(string pFile, string pFormat, long maxUploadSize) + { + try + { + byte[] mediaFile; + using(Stream reader = File.OpenRead(pFile)) + { + mediaFile = Utils.ReadFully(reader); + } + + var memoryStream = new MemoryStream(mediaFile); + var image = Image.FromStream(memoryStream); + + float width, height; + + if(image.Height < image.Width) + { + if(image.Height > 1080) + { + var factor = (float)image.Height / 1080; + + height = 1080; + + width = image.Width / factor; + } + else + { + return pFile; + } + } + else if(image.Height < 1080 && image.Width < 1080) + { + return pFile; + } + else + { + if(image.Width > 1080) + { + var factor = (float)image.Width / 1080; + + width = 1080; + + height = image.Height / factor; + } + else + { + return pFile; + } + } + + var scaledBitmap = new Bitmap(image, new Size((int)width, (int)height)); + + const int orientationId = 0x0112; + + if(image.PropertyIdList.Contains(orientationId)) + { + var item = image.GetPropertyItem(orientationId); + + scaledBitmap.SetPropertyItem(item); + } + + using(var graphics = Graphics.FromImage(image)) + { + graphics.Clear(Color.Transparent); + + graphics.InterpolationMode = InterpolationMode.Low; + + graphics.DrawImage(scaledBitmap, (int)width, (int)height); + } + + var filePath = Path.GetTempPath() + Guid.NewGuid() + pFormat; + + if(pFormat.Equals(".JPG") || pFormat.Equals(".JPE") || pFormat.Equals(".JPEG") || pFormat.Equals(".BMP")) + { + scaledBitmap.Save(filePath, ImageFormat.Jpeg); + } + else if(pFormat.Equals(".PNG")) + { + scaledBitmap.Save(filePath, ImageFormat.Png); + } + else if(pFormat.Equals(".GIF")) + { + scaledBitmap.Save(filePath, ImageFormat.Gif); + } + + if(File.Exists(filePath)) + { + var fileInfo = new FileInfo(filePath); + var fileInfoLength = fileInfo.Length; + + if(maxUploadSize < fileInfoLength) + { + File.Delete(filePath); + return string.Empty; + } + } + else + { + return string.Empty; + } + + memoryStream.Dispose(); + memoryStream.Close(); + + return filePath; + } + catch(Exception exception) + { + return pFile; + } + } + + public static bool CheckFileSize(string pathToFile, long maxFileSize) + { + var fileInfo = new FileInfo(pathToFile); + + return fileInfo.Length > maxFileSize; + } + } +} diff --git a/ChatController/Utilities/OwnChatEnums.cs b/ChatController/Utilities/OwnChatEnums.cs new file mode 100644 index 0000000..a85e9f6 --- /dev/null +++ b/ChatController/Utilities/OwnChatEnums.cs @@ -0,0 +1,12 @@ +namespace ChatController.Utilities +{ + public enum ChatMessageType + { + Message, + Image, + DefaultImage, + Document, + Hyperlink, + Separator + } +} diff --git a/ChatController/Utilities/Utils.cs b/ChatController/Utilities/Utils.cs index 41b6484..21a8ddc 100644 --- a/ChatController/Utilities/Utils.cs +++ b/ChatController/Utilities/Utils.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; @@ -6,7 +7,6 @@ using System.Linq; using System.Net; using System.Reflection; using System.Runtime.InteropServices; -using System.Text; using System.Windows; using System.Windows.Interop; using System.Windows.Media; @@ -19,16 +19,91 @@ namespace ChatController.Utilities { public class Utils { - public static DateTime DefaultDate = new DateTime(1,1,1); + public static string AuthToken { get; set; } + + public static string Tenant { get; set; } + + public static DateTime DefaultDate = new DateTime(1, 1, 1); public static ImageSource AvatarToImageSourceConverter(string pAvatarPath, bool pIsEmployee, bool pIsGroup) { return CreateImageSourceFromPath(pAvatarPath, pIsGroup, pIsEmployee); } - public static ImageSource CreateChatGroupPictureImageSource(string pPicturePath, bool pIsGroup, bool pIsEmployee) + public static Bitmap ConvertAvatarToBitmap(string linkToPicture, bool isEmployee, bool isGroup) { - return CreateImageSourceFromPath(pPicturePath, pIsGroup, pIsEmployee); + Bitmap bitmap = null; + + if(!string.IsNullOrWhiteSpace(linkToPicture)) + { + var client = new RestClient(linkToPicture); + + var request = new RestRequest(Method.GET) + { + ResponseWriter = responseStream => + { + try + { + bitmap = new Bitmap(responseStream); + } + catch(Exception exception) + { + + } + } + }; + + request.AddHeader(Constants.Token, AuthToken); + request.AddHeader(Constants.CustomerId, Tenant); + + client.DownloadData(request); + } + + if(bitmap != null) + { + return bitmap; + } + + var defaultBitmap = (BitmapImage) GetDefaultImageSource(isGroup, isEmployee); + + using(var outStream = new MemoryStream()) + { + BitmapEncoder enc = new BmpBitmapEncoder(); + enc.Frames.Add(BitmapFrame.Create(defaultBitmap)); + enc.Save(outStream); + + return new Bitmap(outStream); + } + } + + public static void DownloadProfilePictureAsync(string avatarPath, bool isEmployee, bool isGroup, Action callback) + { + var url = avatarPath; + + var client = new RestClient(url); + var request = new RestRequest + { + ResponseWriter = stream => + { + var bitmap = new BitmapImage(); + + var localStream = new MemoryStream(); + + stream.CopyTo(localStream); + + localStream.Position = 0; + + bitmap.BeginInit(); + + bitmap.StreamSource = localStream; + + bitmap.EndInit(); + + bitmap.Freeze(); + + callback?.Invoke(bitmap); + } + }; } private static ImageSource GetDefaultImageSource(bool pIsGroup, bool pIsEmployee) @@ -43,7 +118,7 @@ namespace ChatController.Utilities { defaultImage = Constants.CustomerDefaultImagePath; } - + var resultBitmapImage = new BitmapImage(); resultBitmapImage.BeginInit(); @@ -60,6 +135,7 @@ namespace ChatController.Utilities Bitmap bitmap = null; var client = new RestClient(pPathToImageFile); + var request = new RestRequest(Method.GET) { ResponseWriter = stream => @@ -75,6 +151,9 @@ namespace ChatController.Utilities } }; + request.AddHeader(Constants.Token, AuthToken); + request.AddHeader(Constants.CustomerId, Tenant); + client.DownloadData(request); if (bitmap != null) @@ -92,9 +171,6 @@ namespace ChatController.Utilities bitmapImage.StreamSource = memoryStream; bitmapImage.EndInit(); - memoryStream.Dispose(); - memoryStream.Close(); - return bitmapImage; } } @@ -102,42 +178,6 @@ namespace ChatController.Utilities return GetDefaultImageSource(pIsGroup, pIsEmployee); } - - public static ImageSource CreateImageSourceFromSmallerImage(string pUri) - { - Bitmap bitmap; - var request = WebRequest.Create(pUri); - using(var response = request.GetResponse()) - { - using(var stream = response.GetResponseStream()) - { - if(stream == null) - { - return null; - } - - bitmap = new Bitmap(stream); - } - } - - using(var memoryStream = new MemoryStream()) - { - bitmap.Save(memoryStream, ImageFormat.Png); - memoryStream.Position = 0; - - var bitmapImage = new BitmapImage(); - - bitmapImage.BeginInit(); - bitmapImage.CacheOption = BitmapCacheOption.OnLoad; - bitmapImage.StreamSource = memoryStream; - bitmapImage.EndInit(); - - memoryStream.Dispose(); - memoryStream.Close(); - - return bitmapImage; - } - } public static string ReadStream(WebResponse response) { @@ -226,7 +266,6 @@ namespace ChatController.Utilities graphics.DrawIcon(pIcon, 0, 0); graphics.Dispose(); - bitmap.Save("icon.ico", ImageFormat.Icon); @@ -289,10 +328,6 @@ namespace ChatController.Utilities return Icon.FromHandle(bitmap.GetHicon()); } - public static DateTime FromUnixTimeStamp(long pUnixTimeStamp) - { - return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(pUnixTimeStamp); - } public static byte[] ReadFully(Stream pStream) { using (var memStream = new MemoryStream()) @@ -326,5 +361,97 @@ namespace ChatController.Utilities return RotateFlipType.RotateNoneFlipNone; } } + + public static List GetVisualChildCollection(object parent) where T : Visual + { + var visualCollection = new List(); + GetVisualChildCollection(parent as DependencyObject, visualCollection); + + return visualCollection; + } + + public 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); + } + } + } + + /* + * try + { + using (var form = new Form()) + { + using (var ms = new MemoryStream(e.Result)) + { + var image = System.Drawing.Image.FromStream(ms); + + using (var bitmap = new Bitmap(image)) + { + short orient = 0; + const int orientationId = 0x0112; + + if (image.PropertyIdList.Contains(orientationId)) + { + var item = image.GetPropertyItem(orientationId); + + orient = BitConverter.ToInt16(item.Value, 0); + + bitmap.SetPropertyItem(item); + } + + var flipType = Utils.OrientationToFlipType(orient.ToString()); + + bitmap.RotateFlip(flipType); + + form.StartPosition = FormStartPosition.CenterScreen; + form.ClientSize = bitmap.Size; + form.FormBorderStyle = FormBorderStyle.Sizable; + form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); + + using (var pictureBox = new PictureBox()) + { + pictureBox.Dock = DockStyle.Fill; + pictureBox.Image = bitmap; + + pictureBox.SizeMode = PictureBoxSizeMode.Zoom; + + form.Controls.Add(pictureBox); + + downloadCompletedCallback?.Invoke(); + + form.ShowDialog(); + } + } + } + } + */ + + public Bitmap ConvertStreamToBitmap(Stream imageStream) + { + try + { + var image = Image.FromStream(imageStream); + + + + return null; + } + catch(Exception exception) + { + throw exception; + } + } } } diff --git a/PrototypChat/LoginMaske.xaml.cs b/PrototypChat/LoginMaske.xaml.cs index 0052b2b..a61a2be 100644 --- a/PrototypChat/LoginMaske.xaml.cs +++ b/PrototypChat/LoginMaske.xaml.cs @@ -1,5 +1,4 @@ using System.Windows.Input; -using ChatController; using ChatController.LoginKlassen; namespace ownChat diff --git a/PrototypChat/MainWindow.xaml.cs b/PrototypChat/MainWindow.xaml.cs index 6339f11..504010d 100644 --- a/PrototypChat/MainWindow.xaml.cs +++ b/PrototypChat/MainWindow.xaml.cs @@ -40,6 +40,7 @@ namespace ownChat private void MainWindow_OnClosed(object sender, EventArgs e) { + ChatMainControl.DeleteTempFiles(); ChatMainControl.WriteToNewSyncFile(); ChatMainControl.ClearNotifications(); Environment.Exit(0); diff --git a/PrototypChat/PrototypChat.csproj b/PrototypChat/PrototypChat.csproj index 996a09c..fdaceb9 100644 --- a/PrototypChat/PrototypChat.csproj +++ b/PrototypChat/PrototypChat.csproj @@ -72,6 +72,9 @@ ownchat_favicon.ico + + False + ..\libs\Newtonsoft.Json.dll