From 3fbf8afe0d01af17bd3c373f7dfbec5dcafdb055 Mon Sep 17 00:00:00 2001 From: Lyndon Date: Tue, 14 May 2019 13:37:20 +0200 Subject: [PATCH] Anzeige von neuen Nachrichten und die Ladegeschwindigkeit von Konversationen verbessert MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Aufgrund der Benutzung von Threads anstelle von Timern hat das Aufrufen der einzelnen Konversationen ca. 2 Sekunden gedauert. Die Synchronisationsdatei enthält, ob die letzte Nachrichte bereits gelesen wurde, sodass man, wenn man den Chat beendet bevor man eine neue Nachricht gelesen hat, diese nach dem erneuten Öffnen immer noch als neu angezeigt wird. - Dateinamen verbessert - Diverse Verbesserungen des Codes --- .../bewoplaner-chat-android/build.gradle | 2 +- .../gradle/wrapper/gradle-wrapper.properties | 4 +- ChatController/ChatController.csproj | 12 +- ChatController/ChatKlassen/ChatMessage.cs | 66 +- ChatController/ChatKlassen/Contact.cs | 30 +- ...{AktuellerKontakt.cs => CurrentContact.cs} | 8 +- ChatController/ChatKlassen/MessageCounter.cs | 8 +- ChatController/ChatMainControl.xaml | 109 +-- ChatController/ChatMainControl.xaml.cs | 792 +++++++++--------- ChatController/Data/OwnChatApi.cs | 2 +- ChatController/HauptKlassen/Chat.cs | 767 ++++++----------- ChatController/HauptKlassen/Login.cs | 50 +- ChatController/LoginControl.xaml | 3 - ChatController/LoginControl.xaml.cs | 10 +- .../LoginKlassen/AuthenticationData.cs | 6 +- .../LoginKlassen/ChatDatenUebergabe.cs | 6 +- .../LoginKlassen/ChatGruppenDaten.cs | 2 +- ChatController/LoginKlassen/UserMessages.cs | 2 +- ChatController/Utilities/Constants.cs | 4 - ChatController/Utilities/Utils.cs | 181 +++- PrototypChat/LoginMaske.xaml | 4 +- PrototypChat/LoginMaske.xaml.cs | 9 +- PrototypChat/MainWindow.xaml | 2 +- PrototypChat/MainWindow.xaml.cs | 13 +- PrototypChat/PrototypChat.csproj | 1 + 25 files changed, 962 insertions(+), 1131 deletions(-) rename ChatController/ChatKlassen/{AktuellerKontakt.cs => CurrentContact.cs} (76%) diff --git a/BeWoPlanerChat/bewoplaner-chat-android/build.gradle b/BeWoPlanerChat/bewoplaner-chat-android/build.gradle index 39820de..ab37d20 100644 --- a/BeWoPlanerChat/bewoplaner-chat-android/build.gradle +++ b/BeWoPlanerChat/bewoplaner-chat-android/build.gradle @@ -6,7 +6,7 @@ buildscript { google() } dependencies { - classpath 'com.android.tools.build:gradle:3.2.0' + classpath 'com.android.tools.build:gradle:3.3.2' classpath 'io.realm:realm-gradle-plugin:5.3.0' // NOTE: Do not place your application dependencies here; they belong diff --git a/BeWoPlanerChat/bewoplaner-chat-android/gradle/wrapper/gradle-wrapper.properties b/BeWoPlanerChat/bewoplaner-chat-android/gradle/wrapper/gradle-wrapper.properties index 2863f34..f922e7f 100644 --- a/BeWoPlanerChat/bewoplaner-chat-android/gradle/wrapper/gradle-wrapper.properties +++ b/BeWoPlanerChat/bewoplaner-chat-android/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Tue Sep 25 13:06:52 CEST 2018 +#Mon Apr 08 14:14:05 CEST 2019 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip diff --git a/ChatController/ChatController.csproj b/ChatController/ChatController.csproj index 91cc4b1..6af1c1a 100644 --- a/ChatController/ChatController.csproj +++ b/ChatController/ChatController.csproj @@ -33,6 +33,9 @@ ownchat_favicon.ico + + + False @@ -60,10 +63,10 @@ ChatEmojiiControl.xaml - + ChatMainControl.xaml @@ -74,12 +77,13 @@ LoginControl.xaml - + + ChatControlWaitLayer.xaml @@ -90,6 +94,8 @@ Resource.resx + + @@ -132,6 +138,8 @@ + + diff --git a/ChatController/ChatKlassen/ChatMessage.cs b/ChatController/ChatKlassen/ChatMessage.cs index 0207a30..73edc01 100644 --- a/ChatController/ChatKlassen/ChatMessage.cs +++ b/ChatController/ChatKlassen/ChatMessage.cs @@ -9,7 +9,7 @@ namespace ChatController.ChatKlassen public class ChatMessage { //Chat-Ansicht - public ChatMessage(string username, string message, DateTime sendtime, bool isme) + public ChatMessage(string username, string message, DateTime sendtime, bool isme, long pGroupId) { Username = username; UserMessage = message; @@ -19,10 +19,12 @@ namespace ChatController.ChatKlassen Farbgebung(isme); VisibilityRegelung(IsHyperlink(message) ? "HyperlinkMessage" : "Message"); + + GroupId = pGroupId; } // Image-Ansicht - public ChatMessage(string username, string message, DateTime sendtime, bool isme, ImageSource image, string originalImage, string imageName) + public ChatMessage(string username, string message, DateTime sendtime, bool isme, ImageSource image, string originalImage, string imageName, long pGroupId) { Username = username; UserMessage = message; @@ -35,64 +37,49 @@ namespace ChatController.ChatKlassen Farbgebung(isme); - VisibilityRegelung("Image"); - } - - //Image-PlaceHolder | wird nicht benutzt und wird nicht gebraucht ? - public ChatMessage(string username, string message, DateTime sendtime, bool isme, string originalImage, string imageName) - { - Username = username; - UserMessage = message; - SendTime = sendtime; - IsMyMessage = isme; - OriginalImage = originalImage; - OriginalImageName = imageName; + VisibilityRegelung("Image"); - Farbgebung(isme); - - VisibilityRegelung("Default_Image"); + GroupId = pGroupId; } //Dokumenten-Ansicht - public ChatMessage(string username, string message, DateTime sendtime, string pSmallerImagePath, bool isme, string url) + public ChatMessage(string pUsername, string pMessageText, DateTime pSendTime, string pSmallerImagePath, bool pIsLoggedInUsersMessage, string pUrl, long pGroupId) { - Username = username; - UserMessage = message; - SendTime = sendtime; - IsMyMessage = isme; + Username = pUsername; + UserMessage = pMessageText; + SendTime = pSendTime; + IsMyMessage = pIsLoggedInUsersMessage; - Dokpfad = url; + FilePath = pUrl; - Farbgebung(isme); + Farbgebung(pIsLoggedInUsersMessage); Thumbnail = Utilities.Utils.CreateImageSourceFromPath(pSmallerImagePath); VisibilityRegelung("Dokumente"); + + GroupId = pGroupId; } public ImageSource Thumbnail { get; } - #region Farbgebung private void Farbgebung(bool isme) { if (isme) { ChatColor = new BrushConverter().ConvertFromString("#ff5e00") as SolidColorBrush; Posi = "Right"; - _farbeRechtsColor = new BrushConverter().ConvertFromString("#505050") as SolidColorBrush; - _farbeLinksColor = new BrushConverter().ConvertFromString("#505050") as SolidColorBrush; } else { ChatColor = new BrushConverter().ConvertFromString("#FFFFFF") as SolidColorBrush; //"#cccccc" Posi = "Left"; - _farbeRechtsColor = new BrushConverter().ConvertFromString("#505050") as SolidColorBrush; - _farbeLinksColor = new BrushConverter().ConvertFromString("#505050") as SolidColorBrush; } - } - #endregion - #region Visibility Regelung + _farbeRechtsColor = new BrushConverter().ConvertFromString("#505050") as SolidColorBrush; + _farbeLinksColor = new BrushConverter().ConvertFromString("#505050") as SolidColorBrush; + } + private void VisibilityRegelung(string Ansicht) { switch (Ansicht) @@ -141,9 +128,6 @@ namespace ChatController.ChatKlassen break; } } - #endregion - - #region Hyperlink Detection private static readonly Regex UrlRegex = new Regex(@"(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~/|/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?"); @@ -186,10 +170,6 @@ namespace ChatController.ChatKlassen return false; } - #endregion - - #region Variablen - public bool IsMyMessage { get; set; } public string Username { get; } public string UserMessage { get; } @@ -210,7 +190,6 @@ namespace ChatController.ChatKlassen public Visibility ChatVisibility { get; set; } public Visibility HyperlinkVisibility { get; set; } - private Visibility _pictureVisibility; public Visibility PictureVisibility @@ -247,11 +226,10 @@ namespace ChatController.ChatKlassen public Visibility DokumentVisibility { get; set; } public ImageSource ImageSources { get; } - public object Dokpfad { get; } + public object FilePath { get; } public long? ChatMessageOid { get; private set; } - //Farbe Links MEssageHeader private Brush _farbeLinksColor; public Brush FarbeLinksColor { @@ -264,7 +242,6 @@ namespace ChatController.ChatKlassen } } - //Farbe Rechts MessageHeader private Brush _farbeRechtsColor; public Brush FarbeRechtsColor { @@ -277,6 +254,8 @@ namespace ChatController.ChatKlassen } } + public long GroupId { get; } + public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) @@ -284,6 +263,5 @@ namespace ChatController.ChatKlassen var handler = PropertyChanged; handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } - #endregion } } diff --git a/ChatController/ChatKlassen/Contact.cs b/ChatController/ChatKlassen/Contact.cs index 0b46d0b..d28734f 100644 --- a/ChatController/ChatKlassen/Contact.cs +++ b/ChatController/ChatKlassen/Contact.cs @@ -29,6 +29,8 @@ namespace ChatController.ChatKlassen } } + public bool IsNewMessage { get; set; } + private Brush _color; public Brush Color { @@ -41,25 +43,25 @@ namespace ChatController.ChatKlassen } } - private int _NumberOfReadMessages; - public int NumberOfReadMessages + private bool _HasUnreadMessages; + public bool HasUnreadMessages { - get => _NumberOfReadMessages; + get => _HasUnreadMessages; set { - _NumberOfReadMessages = value; + _HasUnreadMessages = value; - if (_NumberOfReadMessages == 1) + if (_HasUnreadMessages) { _color = new BrushConverter().ConvertFromString("#ff5e00") as SolidColorBrush; } - else + else { _color = new SolidColorBrush(Colors.Gray); } - OnPropertyChanged(nameof(NumberOfReadMessages)); + OnPropertyChanged(nameof(HasUnreadMessages)); OnPropertyChanged(nameof(Color)); } } @@ -78,21 +80,21 @@ namespace ChatController.ChatKlassen public ImageSource Image { get; } public DateTime TimeStamp { get; set; } - public long GroupId { get; set; } - public long UserId { get; set; } - public long? CustomerOid { get; set; } + public int GroupId { get; set; } + public int UserOid { get; set; } + public string UserIdManage { get; set; } - public Contact(string pName, ImageSource pImage, string pLastMessageText, DateTime pTimeStamp, long pGroupId,long? pCustomerOid, bool pOnlyEmployees, int pUserCount) + public Contact(string pName, ImageSource pImage, string pLastMessageText, DateTime pTimeStamp, int pGroupId, string pUserIdManage, bool pOnlyEmployees, int pUserCount) { Name = pName; ReceivedMessage = pLastMessageText; Image = pImage; TimeStamp = pTimeStamp; GroupId = pGroupId; - CustomerOid = pCustomerOid; - NumberOfReadMessages = 1; + UserIdManage = pUserIdManage; + HasUnreadMessages = false; - if (CustomerOid != null) + if (UserIdManage != null) { _ContactChatColor = new BrushConverter().ConvertFromString("#3B7799") as SolidColorBrush; } diff --git a/ChatController/ChatKlassen/AktuellerKontakt.cs b/ChatController/ChatKlassen/CurrentContact.cs similarity index 76% rename from ChatController/ChatKlassen/AktuellerKontakt.cs rename to ChatController/ChatKlassen/CurrentContact.cs index 9e169c7..e892f92 100644 --- a/ChatController/ChatKlassen/AktuellerKontakt.cs +++ b/ChatController/ChatKlassen/CurrentContact.cs @@ -3,7 +3,7 @@ using System.Windows.Media; namespace ChatController.ChatKlassen { - public class AktuellerKontakt + public class CurrentContact { public Contact Contact { get; set; } @@ -11,17 +11,17 @@ namespace ChatController.ChatKlassen public ImageSource Image { get; } public DateTime TimeStamp { get; set; } public long GroupId { get; set; } - public long? CustomerOid { get; set; } + public string UserIdManage { get; set; } - public AktuellerKontakt(Contact pContact) + public CurrentContact(Contact pContact) { if(pContact != null) { Contact = pContact; Image = pContact.Image; TimeStamp = pContact.TimeStamp; Name = pContact.Name; - CustomerOid = pContact.CustomerOid; + UserIdManage = pContact.UserIdManage; GroupId = pContact.GroupId; } } diff --git a/ChatController/ChatKlassen/MessageCounter.cs b/ChatController/ChatKlassen/MessageCounter.cs index 6079360..f80e881 100644 --- a/ChatController/ChatKlassen/MessageCounter.cs +++ b/ChatController/ChatKlassen/MessageCounter.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ChatController.ChatKlassen +namespace ChatController.ChatKlassen { public class MessageCounter { diff --git a/ChatController/ChatMainControl.xaml b/ChatController/ChatMainControl.xaml index d949ead..e864040 100644 --- a/ChatController/ChatMainControl.xaml +++ b/ChatController/ChatMainControl.xaml @@ -35,7 +35,7 @@ Maximum="{TemplateBinding ScrollableHeight}" ViewportSize="{TemplateBinding ViewportHeight}" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" - Grid.Column="1"/> + Grid.Row="0" Grid.Column="1"/> - @@ -82,39 +81,30 @@ - - - - - - - - + + - - - @@ -122,11 +112,9 @@ - - @@ -141,12 +129,8 @@ - - - - @@ -159,9 +143,7 @@ - - @@ -170,8 +152,6 @@ - - @@ -190,19 +170,15 @@ - - - - + - @@ -210,18 +186,12 @@ - - - - - - @@ -232,8 +202,7 @@ - - + @@ -257,12 +226,9 @@ - - - - - --> - - - - - - - - + @@ -386,27 +301,22 @@ - - - - - - - - diff --git a/ChatController/ChatMainControl.xaml.cs b/ChatController/ChatMainControl.xaml.cs index e16c958..442e72a 100644 --- a/ChatController/ChatMainControl.xaml.cs +++ b/ChatController/ChatMainControl.xaml.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.IO; using System.Linq; using System.Net; +using System.Text; using System.Threading; using System.Windows; using System.Windows.Controls; @@ -16,9 +17,9 @@ using System.Windows.Threading; using ChatController.ChatKlassen; using ChatController.HauptKlassen; -using ChatController.Klassen; 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; @@ -29,43 +30,39 @@ using Orientation = System.Windows.Controls.Orientation; using Panel = System.Windows.Controls.Panel; using Path = System.IO.Path; using ScrollBar = System.Windows.Controls.Primitives.ScrollBar; +using Timer = System.Windows.Forms.Timer; namespace ChatController { public partial class ChatMainControl { - #region Vokabeln + private readonly Dictionary _Group2NotifyIcons = new Dictionary(); + + private readonly Dictionary _GroupId2DateTime = new Dictionary(); + + public Window ContainingWindow { get; set; } + private Chat _Chat; - private AktuellerKontakt _AktuellerKontakt; + private CurrentContact _CurrentContact; private bool _IsChatBoxOnFocus; - private ChatEmojiiControl _EmojiView; - - private IOrderedEnumerable _OrderedMessages; private IOrderedEnumerable _ContactList; private bool _ScrollPrueferAktivieren; - private Thread _NewThread; - public bool disableKontaktNachrichtenThread = true; + public bool _ShouldInterruptContactsThread = true; - private Thread _AlleKontakteThread; - public bool _AlleNachrichtenThreadBool = true; private readonly List _CreatedTempFiles = new List(); - private Dictionary> _MenuItemName2Callback = new Dictionary>(); - - public delegate void CloseDelegate(); - - public event CloseDelegate OnClose; + private readonly Dictionary> _MenuItemName2Callback = new Dictionary>(); private bool _IsDesktopVersion = true; - #endregion public ChatMainControl() { InitializeComponent(); + ReloadGruppen.Visibility = Visibility.Collapsed; } @@ -73,41 +70,85 @@ namespace ChatController { _Chat = new Chat(cdu); - _ContactList = _Chat.GroupklassenInChatKontakteUmwandler(); + _ContactList = _Chat.AddContacts(); Clientlist.ItemsSource = _ContactList; - - var view = (CollectionView) CollectionViewSource.GetDefaultView(Clientlist.ItemsSource); - view.Filter = UserFilter; - HorcheAlleGruppenNachrichten(); - LeseMessageInfoAusDatei(); + ReadNewSyncFile(); + + foreach (var contact in _ContactList) + { + if (_GroupId2DateTime.ContainsKey(contact.GroupId)) + { + var dateTimeFromFile = _GroupId2DateTime[contact.GroupId].TimeStamp; + var isUnread = _GroupId2DateTime[contact.GroupId].IsUnread; + + var isYounger = contact.TimeStamp > dateTimeFromFile; + + contact.IsNewMessage = isYounger || isUnread; + contact.HasUnreadMessages = contact.IsNewMessage; + } + } + + var view = (CollectionView) CollectionViewSource.GetDefaultView(Clientlist.ItemsSource); + view.Filter = UserFilter; + + _GlobalListeningThreadtimer?.Stop(); + _GlobalListeningThreadtimer = null; + InitGlobalListeningThread(); Clientlist.Items.Refresh(); } - - public AktuellerKontakt GetCurrentContact() + + public void ShowNotification(string pTitle, string pMessage, long pGroupId) { - var kontakt = (AktuellerKontakt) AktChatUserList?.Items[0]; - - return kontakt?.CustomerOid == null ? null : kontakt; - } - - public List GetSelectedMessages() - { - var itemListe = new List(); - - foreach (var selectedItem in ChatListBox.SelectedItems) + if (!_Group2NotifyIcons.ContainsKey(pGroupId)) { - var Item = selectedItem as ChatMessage; + var notificationIcon = Resource.ownchat_favicon; - itemListe.Add(Item); + var contact = _ContactList.FirstOrDefault(a => a.GroupId == pGroupId); + + if(contact != null) + { + notificationIcon = Utils.ImageSourceToIcon(contact.Image); + } + + var notifyIcon = new NotifyIcon { Icon = notificationIcon, Visible = true }; + + notifyIcon.BalloonTipClicked += (sender, args) => + { + DisposeAndRemoveNotification((NotifyIcon)sender, pGroupId); + + SelectContact(_ContactList.FirstOrDefault(f => f.GroupId.Equals(pGroupId))); + }; + + notifyIcon.BalloonTipClosed += (sender, args) => + { + DisposeAndRemoveNotification((NotifyIcon)sender, pGroupId); + }; + + _Group2NotifyIcons.Add(pGroupId, notifyIcon); } - return itemListe.Count > 0 ? itemListe : null; + _Group2NotifyIcons[pGroupId].ShowBalloonTip(Constants.NotificationTimeout, pTitle, pMessage, ToolTipIcon.None); + } + + public void ClearNotifications() + { + foreach(var group2NotifyIcon in _Group2NotifyIcons) + { + group2NotifyIcon.Value.Dispose(); + } + + _Group2NotifyIcons.Clear(); + } + + private void DisposeAndRemoveNotification(IDisposable pNotification, long pGroupId) + { + pNotification.Dispose(); + _Group2NotifyIcons.Remove(pGroupId); } - #region Style setter für ownChatDesktop Version public void ResetStyle() { EmojiButton.Style = null; @@ -115,81 +156,88 @@ namespace ChatController ReloadGruppen.Visibility = Visibility.Visible; _IsDesktopVersion = false; } - #endregion - #region Lade KontaktDaten und Lade sie in den Chat private void AktChatUser_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) { - _Chat.ShowProfilePicture(_AktuellerKontakt); + _Chat.ShowProfilePicture(_CurrentContact); } private void Clientlist_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if(Clientlist.SelectedItem != null) { - disableKontaktNachrichtenThread = true; - Cursor = Cursors.Wait; - _ScrollPrueferAktivieren = false; - ChatListBox.ItemsSource = null; - - AktChatUserList.Items.Clear(); - - var kontakt = (Contact)Clientlist.SelectedItem; - - if(kontakt.NumberOfReadMessages == 1) { - kontakt.NumberOfReadMessages = 0; - - Clientlist.Items.Refresh(); - } - - var aktuellerKontakt = new AktuellerKontakt(kontakt); - - AktChatUserList.Items.Add(aktuellerKontakt); - _AktuellerKontakt = aktuellerKontakt; - - var chatMessages = _Chat.LadeChatNachrichtenVomKontakt(aktuellerKontakt); - - ChatListBox.ItemsSource = chatMessages; - - if (VisualTreeHelper.GetChildrenCount(ChatListBox) > 0) - { - var border = (Border) VisualTreeHelper.GetChild(ChatListBox, 0); - var scrollViewer = (ScrollViewer) VisualTreeHelper.GetChild(border, 0); - scrollViewer.ScrollToBottom(); - } - - ChatListBox.ContextMenu = _Chat.ErstelleKontextMenue(); - SetContextHandler(); - _ScrollPrueferAktivieren = true; - - HorcheAktivNachNachrichten(); - Cursor = Cursors.Arrow; - - - disableKontaktNachrichtenThread = false; + SelectContact((Contact) Clientlist.SelectedItem); } } - #endregion - #region Context Menue - //ab Hier Kontext Menü + private void SelectContact(Contact pContact) + { + _ShouldInterruptContactsThread = true; + + Cursor = Cursors.Wait; + _ScrollPrueferAktivieren = false; + + AktChatUserList.Items.Clear(); + + if (pContact.HasUnreadMessages) + { + pContact.HasUnreadMessages = false; + + Clientlist.Items.Refresh(); + } + + var currentContact = new CurrentContact(pContact); + pContact.IsNewMessage = false; + + var shouldChangeIcon = _ContactList.Any(contact => contact.IsNewMessage); + if(shouldChangeIcon) + { + ContainingWindow.Icon = Utils.GetImageSourceFromIcon(Resource.ownchat_favicon); + } + + AktChatUserList.Items.Add(currentContact); + _CurrentContact = currentContact; + + var chatMessages = _Chat.LoadChatMessagesForContact(currentContact); + + ChatListBox.ItemsSource = chatMessages; + + if (VisualTreeHelper.GetChildrenCount(ChatListBox) > 0) + { + var border = (Border) VisualTreeHelper.GetChild(ChatListBox, 0); + var scrollViewer = (ScrollViewer) VisualTreeHelper.GetChild(border, 0); + scrollViewer.ScrollToBottom(); + } + + ChatListBox.ContextMenu = _Chat.ErstelleKontextMenue(); + SetContextHandler(); + _ScrollPrueferAktivieren = true; + + ListenForMessages(); + Cursor = Cursors.Arrow; + + WriteToNewSyncFile(); + + _ShouldInterruptContactsThread = false; + } + private void SetContextHandler() { - var contextItems = ChatListBox.ContextMenu.Items; + var contextItems = ChatListBox?.ContextMenu?.Items; foreach (var menuItemText in _MenuItemName2Callback.Keys) { var cb = _MenuItemName2Callback[menuItemText]; - MenuItem item = new MenuItem(); + var menuItem = new MenuItem(); - item.Click += (s, e2) => + menuItem.Click += (s, e2) => { cb(menuItemText); }; - item.Header = menuItemText; + menuItem.Header = menuItemText; - contextItems.Add(item); + contextItems.Add(menuItem); } var item2 = (MenuItem)contextItems[0]; @@ -203,24 +251,20 @@ namespace ChatController } - public delegate void ContextDelegate(); - - public event ContextDelegate CreateNewContextItems; - private void Item2OnClick(object sender, RoutedEventArgs routedEventArgs) { foreach (var items in ChatListBox.SelectedItems) { var item = (ChatMessage)items; - _Chat.SpeichernUnterFunkion(item); + _Chat.SaveFileAs(item); } } private void Item3OnClick(object sender, RoutedEventArgs routedEventArgs) { - var kontakt = (AktuellerKontakt)AktChatUserList.Items[0]; - _Chat.Einfuegen(kontakt.GroupId,this); + var kontakt = (CurrentContact)AktChatUserList.Items[0]; + _Chat.Paste(kontakt.GroupId,this); } private void Item4OnClick(object sender, RoutedEventArgs routedEventArgs) @@ -234,7 +278,7 @@ namespace ChatController } if(!chatmessages.Equals("")) - _Chat.Kopieren(chatmessages, 1); + _Chat.Copy(chatmessages, 1); } private void Chat_OnContextMenuOpening(object sender, ContextMenuEventArgs e) @@ -259,7 +303,7 @@ namespace ChatController ContextItemSpeichernUnter.Visibility = Visibility.Collapsed; } - if (item.ImageSources == null && item.Dokpfad == null) + if (item.ImageSources == null && item.FilePath == null) { var contextItems = ChatListBox.ContextMenu.Items; var ContextItemSpeichernUnter = (MenuItem) contextItems[2]; @@ -313,8 +357,8 @@ namespace ChatController } //prüfe ob dokumentation erlaubt - var kontakt = (AktuellerKontakt)AktChatUserList.Items[0]; - if (kontakt.CustomerOid == null && ChatListBox.ContextMenu.Items.Count > 3) + 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]; @@ -336,23 +380,13 @@ namespace ChatController } - public void AddContextMenu(string menuItemText, Action callBackAction) - { - if (!_MenuItemName2Callback.ContainsKey(menuItemText)) - { - _MenuItemName2Callback.Add(menuItemText, callBackAction); - } - } - #endregion - - #region Sende Media Nachrichten private void MediaButton_OnClick(object sender, RoutedEventArgs e) { if (AktChatUserList.Items.Count > 0) { - var kontakt = (AktuellerKontakt)AktChatUserList.Items[0]; + var kontakt = (CurrentContact)AktChatUserList.Items[0]; - var medium = _Chat.HoleMedium(); + var medium = _Chat.OpenFile(); if(medium != null) { @@ -360,13 +394,13 @@ namespace ChatController if (!convertetMedia.Equals("")) { - _Chat.AddeMediumDerNachrichtView(convertetMedia,medium); + _Chat.AddNewFile(convertetMedia,medium,kontakt.GroupId); CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); ChatListBox.Items.MoveCurrentToLast(); ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); - _Chat.SendeMediumAnKontakt(kontakt, convertetMedia,medium); + _Chat.SendFileToContact(kontakt, convertetMedia,medium); if (!convertetMedia.Equals("") && !convertetMedia.Equals(medium) && File.Exists(convertetMedia)) { @@ -384,18 +418,16 @@ namespace ChatController MessageBox.Show("Bitte wählen Sie einen Kontakt aus.","ownChat",MessageBoxButton.OK, MessageBoxImage.Information); } } - #endregion - #region Sende Normale Nachrichten private void SendButton_OnClick(object sender, RoutedEventArgs e) { if (!AktChatUserList.Items.IsEmpty && !Chatbox.Text.Equals("") && _IsChatBoxOnFocus) { if (!Chatbox.Text.Equals("")) { - var kontakt = (AktuellerKontakt)AktChatUserList.Items[0]; + var kontakt = (CurrentContact)AktChatUserList.Items[0]; - _Chat.AddeNachrichtDerView(Chatbox.Text); + _Chat.AddNewMessage(Chatbox.Text, kontakt.GroupId); CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); @@ -419,22 +451,20 @@ namespace ChatController if (AktChatUserList.Items.IsEmpty) { MessageBox.Show("Bitte wählen Sie einen Chatpartner aus.", "Fehler", MessageBoxButton.OK); - if (Chatbox.Text.Equals("")) + if (string.IsNullOrEmpty(Chatbox.Text)) { Chatbox.Text = "Nachricht schreiben"; Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray); _IsChatBoxOnFocus = false; } } - else if (Chatbox.Text.Equals("")) + else if (string.IsNullOrEmpty(Chatbox.Text)) { - MessageBox.Show("Sie können keine lehre Nachricht verschicken.", "Fehler", MessageBoxButton.OK); - if (Chatbox.Text.Equals("")) - { - Chatbox.Text = "Nachricht schreiben"; - Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray); - _IsChatBoxOnFocus = false; - } + MessageBox.Show("Sie können keine leere Nachricht verschicken.", "Fehler", MessageBoxButton.OK); + + Chatbox.Text = "Nachricht schreiben"; + Chatbox.Foreground = new SolidColorBrush(Colors.DarkGray); + _IsChatBoxOnFocus = false; } } } @@ -447,8 +477,6 @@ namespace ChatController Chatbox.Foreground = new SolidColorBrush(Colors.Black); _IsChatBoxOnFocus = true; } - - //hier bereich wie Dokumentieren } private void Chatbox_OnKeyDownHandler(object sender, KeyEventArgs e) @@ -459,9 +487,9 @@ namespace ChatController { if (!AktChatUserList.Items.IsEmpty && !Chatbox.Text.Equals("")) { - var kontakt = (AktuellerKontakt)AktChatUserList.Items[0]; + var kontakt = (CurrentContact)AktChatUserList.Items[0]; - _Chat.AddeNachrichtDerView(Chatbox.Text); + _Chat.AddNewMessage(Chatbox.Text, kontakt.GroupId); CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); ChatListBox.Items.MoveCurrentToLast(); @@ -492,10 +520,7 @@ namespace ChatController } } - #endregion - - #region Add Emoji To ChatBox - public delegate void EmojiiDelegate(Button x); + public delegate void EmojiiDelegate(Button button); public event EmojiiDelegate OnEmojii; @@ -507,17 +532,14 @@ namespace ChatController OnEmojii(EmojiButton); } } - #endregion - - #region Nachladen weiterer Chat Nachrichten + private void Chat_OnScrollChanged(object sender, ScrollChangedEventArgs e) { - List scrollBarList = GetVisualChildCollection(ChatListBox); - foreach (ScrollBar scrollBar in scrollBarList) + var scrollBarList = GetVisualChildCollection(ChatListBox); + foreach (var scrollBar in scrollBarList) { if (scrollBar.Orientation == Orientation.Horizontal) { - scrollBar.ValueChanged += HorizontalScrollbarChanged; _ScrollPrueferAktivieren = true; } else @@ -550,7 +572,7 @@ namespace ChatController var kontakt = (Contact)Clientlist.SelectedItem; - var xy = _Chat.LadeWeiterNachrichten(kontakt); + var xy = _Chat.LoadMoreMessages(kontakt); ChatListBox.ItemsSource = xy; @@ -561,181 +583,156 @@ namespace ChatController } } - private void HorizontalScrollbarChanged(object sender, RoutedPropertyChangedEventArgs routedPropertyChangedEventArgs) - { - //nix - - } - - #region Get Scollbar von listbox private static List GetVisualChildCollection(object parent) where T : Visual { - List visualCollection = new List(); + var visualCollection = new List(); GetVisualChildCollection(parent as DependencyObject, visualCollection); + return visualCollection; } - private static void GetVisualChildCollection(DependencyObject parent, List visualCollection) where T : Visual + private static void GetVisualChildCollection(DependencyObject parent, ICollection visualCollection) where T : Visual { - int count = VisualTreeHelper.GetChildrenCount(parent); - for (int i = 0; i < count; i++) + var count = VisualTreeHelper.GetChildrenCount(parent); + for (var i = 0; i < count; i++) { - DependencyObject child = VisualTreeHelper.GetChild(parent, i); - if (child is T) + var child = VisualTreeHelper.GetChild(parent, i); + + if (child is T item) { - visualCollection.Add(child as T); + visualCollection.Add(item); } - else if (child != null) + else { GetVisualChildCollection(child, visualCollection); } } } - #endregion - - #endregion - - #region Funktion Nachrichten Listener - - private void HorcheAktivNachNachrichten() + private void ListenForMessages() { - if (_NewThread != null) - { - _NewThread.Join(); - _NewThread = null; - } - - var kontakt = (AktuellerKontakt) AktChatUserList.Items[0]; - - _NewThread = new Thread(DoWork) {IsBackground = true}; - _NewThread.Start(kontakt); + _ListeningThreadTimer?.Stop(); + _ListeningThreadTimer = null; + InitListeningThread((CurrentContact)AktChatUserList.Items[0]); } - private void DoWork(object o) + private Timer _ListeningThreadTimer; + private Timer _GlobalListeningThreadtimer; + + private void InitGlobalListeningThread() { - var currentContact = (AktuellerKontakt) o; - - while (true) + _GlobalListeningThreadtimer = new Timer(); + _GlobalListeningThreadtimer.Tick += GlobalListeningThreadTimerTickEvent; + _GlobalListeningThreadtimer.Interval = 2000; + _GlobalListeningThreadtimer.Start(); + } + + private void GlobalListeningThreadTimerTickEvent(object sender, EventArgs e) + { + ListenGloballyForMessages(); + } + + private void ListenGloballyForMessages() + { + var numberOfNewMessages = _Chat.GetNumberOfAllNewMessages(); + + if (numberOfNewMessages > 0) { - Thread.Sleep(2000); - - if (!disableKontaktNachrichtenThread) + Dispatcher.BeginInvoke( + DispatcherPriority.Normal, + (Action)delegate { - var hasNewMessages = _Chat.CheckIfNewMessagesExist(currentContact); + var contacts = _Chat.NeueGroupklassenKontakte().ToList(); - if (hasNewMessages) + CurrentContact currentContact = null; + + if (AktChatUserList.HasItems) { - Utils.NotifyIcon.ShowBalloonTip(Constants.NotificationTimeout, "ownChat", $"Hat neue Nachrichten: {currentContact.Name}({currentContact.Contact.Name})", ToolTipIcon.None); - - Dispatcher.BeginInvoke(DispatcherPriority.Background, - (Action) delegate - { - - - _Chat.LadeChatNachrichtenVomKontakt(currentContact); - - CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); - - ChatListBox.Items.MoveCurrentToLast(); - ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); - }); + currentContact = (CurrentContact)AktChatUserList.Items[0]; } - } - else - { - break; - } - } - } - #endregion - - #region Für alle Nachrichten Count Listener - private void HorcheAlleGruppenNachrichten() - { - _AlleKontakteThread = new Thread(DoWorkAlleNachrichten); - _AlleKontakteThread.IsBackground = true; - _AlleKontakteThread.Start(); - } - - private void DoWorkAlleNachrichten() - { - while (true) - { - var x = _Chat.SchaueNachAllenMessageCounts(); - - if (x > 0) - { - this.Dispatcher.BeginInvoke( - DispatcherPriority.Background, - (Action)delegate - { - var alist = _Chat.NeueGroupklassenKontakte(); - - AktuellerKontakt aktuellerKontakt = null; - - if (AktChatUserList.HasItems) + foreach (var contact in _ContactList) + { + foreach (var newContact in contacts) { - aktuellerKontakt = (AktuellerKontakt)AktChatUserList.Items[0]; - } - - foreach (var liste in _ContactList) + if (contact.GroupId == newContact.GroupId) { - foreach (var neu in alist) + if (!contact.ReceivedMessage.Equals(newContact.ReceivedMessage)) { - if (liste.GroupId == neu.GroupId) + contact.ReceivedMessage = newContact.ReceivedMessage; + contact.TimeStamp = newContact.TimeStamp; + + if (Clientlist.SelectedItem != null && !((Contact)Clientlist.SelectedItem).GroupId.Equals(newContact.GroupId) || Clientlist.SelectedItem == null) { - if (!liste.ReceivedMessage.Equals(neu.ReceivedMessage)) { - - liste.ReceivedMessage = neu.ReceivedMessage; - liste.TimeStamp = neu.TimeStamp; - - if (aktuellerKontakt != null && neu.GroupId == aktuellerKontakt.GroupId) - { - liste.NumberOfReadMessages = 0; - } - else - { - liste.NumberOfReadMessages = 1; - } - } + ContainingWindow.Icon = Utils.GetImageSourceFromIcon(Resource.oC_favico_NewMessage); + ShowNotification(newContact.Name, "Sie haben eine neue Nachricht", newContact.GroupId); } - - //abchecken ob neue Groupid in liste vorhanden , wenn nicht dann adde neuen kontakt der liste hinzu - if (!_ContactList.Contains(neu)) + + // Wenn der momentan ausgewählte Kontakt der aktuelle Kontakt in der Schleife ist, werden die Nachrichten nicht als ungelesen angezeigt, sonst schon. + if (currentContact != null && newContact.GroupId == currentContact.GroupId) { - _ContactList.ToList().Add(neu); + contact.HasUnreadMessages = false; + } + else + { + contact.HasUnreadMessages = true; + contact.IsNewMessage = true; } - } - - //umgekert ist eine kontakt aus der liste nicht mehr in neu muss diese raus - if (!alist.Contains(liste)) - { - _ContactList.ToList().Remove(liste); } } - - Clientlist.Items.Refresh(); - - }); - - } - - if (_AlleNachrichtenThreadBool == false) - { - break; - } - - Thread.Sleep(5000); + if (!_ContactList.Contains(newContact)) + { + _ContactList.ToList().Add(newContact); + } + } + + if (!contacts.Contains(contact)) + { + _ContactList.ToList().Remove(contact); + } + } + + Clientlist.Items.Refresh(); + }); } } - #endregion + private void InitListeningThread(CurrentContact pCurrentContacObject) + { + _ListeningThreadTimer = new Timer {Tag = pCurrentContacObject}; + _ListeningThreadTimer.Tick += ListeningThreadTimerTickEvent; + _ListeningThreadTimer.Interval = 2000; + _ListeningThreadTimer.Start(); + } + + private void ListeningThreadTimerTickEvent(object sender, EventArgs e) + { + ListenForMessagesForCurrentContact((CurrentContact) ((Timer) sender).Tag); + } + + private void ListenForMessagesForCurrentContact(CurrentContact pCurrentContact) + { + if (!_ShouldInterruptContactsThread) + { + var hasNewMessages = _Chat.CheckIfNewMessagesExist(pCurrentContact); + + if (hasNewMessages) + { + Dispatcher.BeginInvoke(DispatcherPriority.Background, + (Action)delegate + { + _Chat.LoadChatMessagesForContact(pCurrentContact); + + CollectionViewSource.GetDefaultView(ChatListBox.ItemsSource).Refresh(); + + ChatListBox.Items.MoveCurrentToLast(); + ChatListBox.ScrollIntoView(ChatListBox.Items.CurrentItem); + }); + } + } + } - #region Suche Nach Person - private void Suche_OnTextChanged(object sender, TextChangedEventArgs e) { CollectionViewSource.GetDefaultView(Clientlist.ItemsSource).Refresh(); @@ -749,10 +746,6 @@ namespace ChatController return ((item as Contact).Name.IndexOf(Suche.Text, StringComparison.OrdinalIgnoreCase) >= 0); } - #endregion - - #region Zeige Erhaltene Daten per doppelclick An - private void Chat_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) { Cursor = Cursors.Wait; @@ -770,10 +763,10 @@ namespace ChatController StartWaiting(); _Chat.ShowPicture(item, EndWaiting); } - else if(item != null && item.Dokpfad != null) + else if(item != null && item.FilePath != null) { - var filename = Path.GetFileName(item.Dokpfad.ToString()); - LoadDokument(item.Dokpfad.ToString(), filename); + var filename = Path.GetFileName(item.FilePath.ToString()); + LoadDocument(item.FilePath.ToString(), filename); } } @@ -785,43 +778,17 @@ namespace ChatController } } - #endregion - - #region Lade Dokument Herunter und Zeige es an - private void OpenDokument_OnClick(object sender, RoutedEventArgs e) - { - OpenDocument(sender); - } - - private void OpenDocument(object sender) - { - Cursor = Cursors.Wait; - - var btn = sender as System.Windows.Controls.Button; - - if (btn.Tag != null) - { - var link = btn.Tag; - - var filename = Path.GetFileName(link.ToString()); - - LoadDokument(link.ToString(), filename); - } - - Cursor = Cursors.Arrow; - } - - private void LoadDokument(string link, String filename) + private void LoadDocument(string link, string filename) { try { StartWaiting(); - string path = Path.Combine(Path.GetTempPath(), filename); + var path = Path.Combine(Path.GetTempPath(), filename); _CreatedTempFiles.Add(path); if (!File.Exists(path)) { - using (WebClient webClient = new WebClient()) + using (var webClient = new WebClient()) { webClient.DownloadFile(link, path); } @@ -844,16 +811,9 @@ namespace ChatController { EndWaiting(); } - - - } - #endregion - - #region Wait Layer - - private ChatControlWaitLayer _waitLayer = null; + private ChatControlWaitLayer _waitLayer; public void StartWaiting() { @@ -887,16 +847,11 @@ namespace ChatController }); } - #endregion - - #region link request private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e) { Process.Start(e.Uri.ToString()); } - #endregion - #region ReloadGruppen (For Stand Alone version) private void ButtonReloadGruppen_OnClick(object sender, RoutedEventArgs e) { DoSynchro(); @@ -908,15 +863,13 @@ namespace ChatController { Cursor = Cursors.Wait; - SpeichereMessageInfoInDatei(); + WriteToNewSyncFile(); - var aktuelleGruppen = _Chat.GruppenAktuallisieren(); + var aktuelleGruppen = _Chat.UpdateGroups(); - var x = _Chat.GroupklassenAktuallisieren(aktuelleGruppen); + _ContactList = _Chat.GroupklassenAktuallisieren(aktuelleGruppen); - _ContactList = x; - - LeseMessageInfoAusDatei(); + ReadNewSyncFile(); Clientlist.Items.Refresh(); @@ -927,88 +880,149 @@ namespace ChatController MessageBox.Show("Ein Fehler bei der Synchronisation ist aufgetreten.\nFehler:\n" + e.Message, "Fehler", MessageBoxButton.OK); } } - - #endregion - #region speichern sowie lesen der MessageSyncDatei / stylezwecke (OwnChat only) - public void SpeichereMessageInfoInDatei() + // Speichert die TimeStamps der zuletzt empfangenen Nachrichten + public void WriteToNewSyncFile() { - List aa = new List(); - foreach (var kontakt in _ContactList) + try { - if(kontakt.NumberOfReadMessages == 0 && !kontakt.ReceivedMessage.Equals("")) { - aa.Add(kontakt); - } - } - - if(aa.Count>0) - _Chat.SpeichereTimeStampsInDatei(aa); - } - - public void LeseMessageInfoAusDatei() - { - List aa = new List(); - foreach (var kontakt in _ContactList) - { - aa.Add(kontakt); - } - - var liste = _Chat.PruefeTimeStampsBeiStart(aa); - - if(liste != null) { - foreach (var kon in _ContactList) + if (File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name))) { - foreach (var item in liste) - { - if (kon.GroupId == item.Key) - { - kon.NumberOfReadMessages = 0; - } - } + File.SetAttributes(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name), FileAttributes.Normal); + File.Delete(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name)); } - } - } - #endregion - - #region Speichern Und LEsen Der MesageSyncDatei (Bewoplaner only) - public List UebergebeMessageInfoDatenFuerDb() + using (var streamWriter = new StreamWriter(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name))) + { + Encoding enc = new UTF8Encoding(); + + foreach (var contact in _ContactList.ToList().Where(contact => contact.ReceivedMessage != null)) + { + var text = contact.GroupId + ";" + contact.TimeStamp + ";" + contact.IsNewMessage + ";"; + var bytes = enc.GetBytes(text); + var base64String = Convert.ToBase64String(bytes); + + streamWriter.WriteLine(base64String); + } + + File.SetAttributes(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name), FileAttributes.ReadOnly); + } + } + catch (Exception exception) + { + + } + } + + public void ReadNewSyncFile() { - List < Contact > aa = new List(); + try + { + if(File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name))) + { + using (var streamReader = new StreamReader(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFile2Name), true)) + { + string line; + + _GroupId2DateTime.Clear(); + + while ((line = streamReader.ReadLine()) != null) + { + var encodedTextBytes = Convert.FromBase64String(line); + var plainText = Encoding.UTF8.GetString(encodedTextBytes); + var splitPlainText = plainText.Split(';'); + + // Ist kein Datum vorhanden -> 01.01.0001 00:00:00 + + var groupId = int.Parse(splitPlainText[0]); + var dateTime = DateTime.Parse(splitPlainText[1]); + var isUnread = splitPlainText.Length <= 2 || string.IsNullOrEmpty(splitPlainText[2]) || bool.Parse(splitPlainText[2]); + + Debug.WriteLine($"{groupId}: {dateTime:dd.MM.yyyy HH:mm:ss}; Is unread: {isUnread}"); + + _GroupId2DateTime.Add(groupId, new SyncFileInfoStruct(isUnread, dateTime)); + } + } + + var latestDateTime = Utils.DefaultDate; + + foreach(var id2dateTime in _GroupId2DateTime) + { + if(id2dateTime.Value.TimeStamp > latestDateTime) + { + latestDateTime = id2dateTime.Value.TimeStamp; + } + } + + //_Chat.LastTimeStamp = !latestDateTime.Equals(Utils.DefaultDate) ? latestDateTime.GetUnixTimeStamp() : DateTime.UtcNow.GetUnixTimeStamp(); + } + } + catch (Exception e) + { + + } + } + + public List GetContactsWithoutUnreadMessages() + { + var contacts = new List(); Clientlist.Items.Refresh(); - foreach (var item in Clientlist.Items) + foreach(var contactItem in Clientlist.Items) { - var kontakt = item as Contact; - - if (kontakt != null && kontakt.NumberOfReadMessages == 0 && !kontakt.ReceivedMessage.Equals("")) + if(contactItem is Contact contact && contact.HasUnreadMessages && !string.IsNullOrEmpty(contact.ReceivedMessage)) { - aa.Add(kontakt); + contacts.Add(contact); } } - - return aa; + + return contacts; } - public void ErhalteMessageInfoVonDb(Dictionary liste) + public void ResetNumberOfUnreadMessages(Dictionary pGroupId2DateTime) { - if (liste != null) + if(pGroupId2DateTime != null) { - foreach (var kon in _ContactList) + foreach(var contact in _ContactList) { - foreach (var item in liste) + foreach(var groupId2DateTime in pGroupId2DateTime) { - if (kon.GroupId == item.Key) + if(contact.GroupId == groupId2DateTime.Key) { - kon.NumberOfReadMessages = 0; + contact.HasUnreadMessages = false; } } } - } + } + } + + public List GetSelectedMessages() + { + var messages = (from object selectedItem in ChatListBox.SelectedItems select selectedItem as ChatMessage).ToList(); + + return messages.Count > 0 ? messages : null; + } + + public CurrentContact GetCurrentContact() + { + if(AktChatUserList != null && AktChatUserList.Items.Count > 0) + { + var contact = (CurrentContact) AktChatUserList.Items[0]; + + return contact.UserIdManage == null ? null : contact; + } + + return null; + } + + public void AddContextMenu(string menuItemText, Action callBackAction) + { + if (!_MenuItemName2Callback.ContainsKey(menuItemText)) + { + _MenuItemName2Callback.Add(menuItemText, callBackAction); + } } - - #endregion public void DeleteTempFiles() { diff --git a/ChatController/Data/OwnChatApi.cs b/ChatController/Data/OwnChatApi.cs index 349c00a..0c7f402 100644 --- a/ChatController/Data/OwnChatApi.cs +++ b/ChatController/Data/OwnChatApi.cs @@ -81,7 +81,7 @@ namespace ChatController.Data { try { - var serverResponse = Empty; + var serverResponse = string.Empty; using (var dataStream = response.GetResponseStream()) { diff --git a/ChatController/HauptKlassen/Chat.cs b/ChatController/HauptKlassen/Chat.cs index df51cdf..d84a2a5 100644 --- a/ChatController/HauptKlassen/Chat.cs +++ b/ChatController/HauptKlassen/Chat.cs @@ -1,10 +1,9 @@ using ChatController.ChatKlassen; -using ChatController.Klassen; - using Newtonsoft.Json; using System; using System.Collections.Generic; +using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; @@ -12,7 +11,6 @@ using System.IO; using System.Linq; using System.Net; using System.Net.Http; -using System.Reflection; using System.Text; using System.Threading; using System.Windows; @@ -23,7 +21,7 @@ using System.Windows.Media.Imaging; using ChatController.LoginKlassen; using ChatController.Utilities; - +using ChatController.Utilities.Extensions; using Application = System.Windows.Forms.Application; using Clipboard = System.Windows.Forms.Clipboard; using Color = System.Drawing.Color; @@ -38,7 +36,7 @@ namespace ChatController.HauptKlassen public class Chat { private readonly List _Contacts = new List(); - private readonly List _Messages = new List(); + public List Messages { get; } = new List(); public ChatDatenUebergabe ChatDaten { get; set; } @@ -48,114 +46,51 @@ namespace ChatController.HauptKlassen private string _NextPage; private bool _HasNextPage; - private long _LastTimeStamp; - + public long LastTimeStamp { get; set; } + public Chat(ChatDatenUebergabe chatDaten) { ChatDaten = chatDaten; } - public IOrderedEnumerable GroupklassenInChatKontakteUmwandler() + public ChatMessage PrevisouslyLatestMessage { get; set; } + public ChatMessage GetLatestMessage() { - foreach (var kontakt in ChatDaten.AlleGruppen.Response) + ChatMessage latestMessage = null; + foreach (var message in Messages) { - foreach (var value in kontakt.Value) + if (latestMessage == null || latestMessage.SendTime < message.SendTime) { - var message = ""; - - var lastMessage = value.LastMessage; - - var timeformated = new DateTime(); - - if(lastMessage?.Text != null) - { - message = lastMessage.Text; - } - - if(value.LastMessage != null) { - var timestamp = DateTime.Parse(lastMessage.Timestamp.Date); - - var clientZone = TimeZoneInfo.Local; - timeformated = TimeZoneInfo.ConvertTimeFromUtc(timestamp, clientZone); - } - - if(string.IsNullOrEmpty(message) && !string.IsNullOrEmpty(value.LastMessage?.File)) - { - message = Path.GetFileName(value.LastMessage.File); - } - - long? customerOid = null; - var isEmployee = false; - - foreach(var user in value.Users) - { - if(user.Oid != ChatDaten.Userid) - { - if(!user.Is_Employee && !string.IsNullOrEmpty(user.Userid_Manage)) - { - customerOid = long.Parse(user.Userid_Manage.Substring(1)); - } - } - } - - if(value.OnlyEmployees && value.Users.Length == 2) - { - isEmployee = true; - } - - _Contacts.Add(new Contact(value.Name, Utils.AvatarToImageSourceConverter(value.Avatar, isEmployee), message, timeformated, value.Oid, customerOid, value.OnlyEmployees, value.Users.Length)); - - if(lastMessage?.Timestamp?.Date != null) { - var span = DateTime.Parse(lastMessage.Timestamp.Date) - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); - var unixTime = Convert.ToInt64(span.TotalSeconds); - - if (_LastTimeStamp < unixTime) - { - _LastTimeStamp = unixTime; - } - } + latestMessage = message; } } + return latestMessage; + } + + public IOrderedEnumerable AddContacts() + { + foreach (var contact in ChatDaten.AlleGruppen.Response) + { + _Contacts.AddRange(GenerateContactsFromServerResponse(contact.Value, true)); + } + var sortedKontaktliste = _Contacts.OrderByDescending(r => r.TimeStamp); return sortedKontaktliste; } - public IOrderedEnumerable LadeChatNachrichtenVomKontakt(AktuellerKontakt pContact) + public IOrderedEnumerable LoadChatMessagesForContact(CurrentContact pContact) { if (pContact != null) { - HoleNachrichtenVomServer(pContact.GroupId); - _Messages.Clear(); + LoadMessagesFromServer(pContact.GroupId); + Messages.Clear(); - foreach (var message in _UserMessages.Response.Messages) - { - var time = DateTime.Parse(message.Timestamp.Date); - var clientTimeZone = TimeZoneInfo.Local; - var formattedTime = TimeZoneInfo.ConvertTimeFromUtc(time, clientTimeZone); - var isMyOwnMessage = message.UserId == ChatDaten.Userid.Value; - var textMessage = message.Text ?? string.Empty; - - if(string.IsNullOrEmpty(textMessage)) - { - textMessage = message.Original_Filename; - } - - if (!string.IsNullOrEmpty(message.File)) - { - _Messages.Add(Constants.ImageFileExtensions.Contains(Path.GetExtension(message.File).ToUpperInvariant()) ? - new ChatMessage(message.User_Name, textMessage, formattedTime, isMyOwnMessage, DownloadImage(message.Smaller_Image), message.File, message.Original_Filename) : - new ChatMessage(message.User_Name, textMessage, formattedTime, message.Smaller_Image, isMyOwnMessage, message.File)); - } - else - { - _Messages.Add(new ChatMessage(message.User_Name, message.Text, formattedTime, isMyOwnMessage)); - } - } + AddMessagesFromServerResponse(_UserMessages.Response.Messages); } - return _Messages.OrderBy(r => r.SendTime); + return Messages.OrderBy(r => r.SendTime); } private static ImageSource DownloadImage(string pUri) @@ -177,11 +112,11 @@ namespace ChatController.HauptKlassen } } - private void HoleNachrichtenVomServer(long groupId) + private void LoadMessagesFromServer(long pGroupId) { try { - var endurl = ChatDaten.ServerUrl + "/api/chat/messages?groupid=" + groupId; + var endurl = ChatDaten.ServerUrl + Constants.LoadMessagesForGroupUrl + pGroupId; var webRequest = WebRequest.Create(endurl); @@ -191,15 +126,11 @@ namespace ChatController.HauptKlassen using (var response = webRequest.GetResponse()) { - var responseFromServer = Utils.ReadStream(response); + var serverResponse = Utils.ReadStream(response); - if (!responseFromServer.Equals("")) + if (!string.IsNullOrEmpty(serverResponse)) { - _UserMessages = null; - - var jsonDaten = JsonConvert.DeserializeObject(responseFromServer); - - _UserMessages = jsonDaten; + _UserMessages = JsonConvert.DeserializeObject(serverResponse); if (_UserMessages.Response.HasMorePages) { @@ -215,53 +146,23 @@ namespace ChatController.HauptKlassen } catch (Exception e) { - MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK); + MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); } } - public IOrderedEnumerable LadeWeiterNachrichten(Contact kontakt) + public IOrderedEnumerable LoadMoreMessages(Contact pContact) { if (_HasNextPage) { - HoleWeitereNachrichtenVomServer(kontakt.GroupId, _NextPage); - - foreach (var ChatMessage in _AdditionalUserMessages.Response.Messages) - { - var time = DateTime.Parse(ChatMessage.Timestamp.Date); - var clientZone = TimeZoneInfo.Local; - var timeformated = TimeZoneInfo.ConvertTimeFromUtc(time, clientZone); + LoadMoreMessagesFromServer(pContact.GroupId, _NextPage); - var isLoggedInUsersMessage = ChatMessage.UserId == ChatDaten.Userid.Value; - - if (!string.IsNullOrEmpty(ChatMessage.File)) - { - var messageText = ""; - - if (ChatMessage.Text != null) - { - messageText = ChatMessage.Text; - } - - if (string.IsNullOrEmpty(messageText)) - { - messageText = ChatMessage.Original_Filename; - } - - _Messages.Add(Constants.ImageFileExtensions.Contains(Path.GetExtension(ChatMessage.File).ToUpperInvariant()) ? - new ChatMessage(ChatMessage.User_Name, messageText, timeformated, isLoggedInUsersMessage, DownloadImage(ChatMessage.Smaller_Image), ChatMessage.File, ChatMessage.Original_Filename) : - new ChatMessage(ChatMessage.User_Name, messageText, timeformated, ChatMessage.Smaller_Image, isLoggedInUsersMessage, ChatMessage.File)); - } - else - { - _Messages.Add(new ChatMessage(ChatMessage.User_Name, ChatMessage.Text, timeformated, true)); - } - } + AddMessagesFromServerResponse(_AdditionalUserMessages.Response.Messages); } - return _Messages.OrderBy(r => r.SendTime); + return Messages.OrderBy(r => r.SendTime); } - private void HoleWeitereNachrichtenVomServer(long pGroupId, string pPage) + private void LoadMoreMessagesFromServer(long pGroupId, string pPage) { try { @@ -282,9 +183,7 @@ namespace ChatController.HauptKlassen { _AdditionalUserMessages = null; - var userMessages = JsonConvert.DeserializeObject(responseFromServer); - - _AdditionalUserMessages = userMessages; + _AdditionalUserMessages = JsonConvert.DeserializeObject(responseFromServer); if (_AdditionalUserMessages.Response.HasMorePages) { @@ -301,13 +200,13 @@ namespace ChatController.HauptKlassen } catch (Exception e) { - MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK); + MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); } } - private double? _FormerMessagesCount; + private double _FormerMessagesCount; - public bool CheckIfNewMessagesExist(AktuellerKontakt pCurrentContact) + public bool CheckIfNewMessagesExist(CurrentContact pCurrentContact) { var span = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var timespan = Convert.ToInt64(span.TotalSeconds); @@ -319,14 +218,9 @@ namespace ChatController.HauptKlassen if (pCurrentContact != null) { - var currentMessagesCount = SendOwnChatNewsRequest(pCurrentContact.GroupId, timespan); + var currentMessagesCount = GetNumberOfNewMessages(pCurrentContact.GroupId, timespan); - if (_FormerMessagesCount == null) - { - _FormerMessagesCount = currentMessagesCount; - } - - if (currentMessagesCount != null && _FormerMessagesCount != null && currentMessagesCount.Equals(_FormerMessagesCount)) + if (currentMessagesCount.Equals(_FormerMessagesCount)) { return false; } @@ -339,141 +233,90 @@ namespace ChatController.HauptKlassen return false; } - private double? SendOwnChatNewsRequest(long groupId, long lastStamp) + private double GetNumberOfNewMessages(long pGroupId, long pLastTimeStamp) { try { - var endurl = ChatDaten.ServerUrl + "/api/ownchat/news/" + groupId+"/"+lastStamp; + var url = $"{ChatDaten.ServerUrl}{Constants.LoadOwnChatNewsUrl}{pGroupId}/{pLastTimeStamp}"; - var request = WebRequest.Create(endurl); + var webRequest = WebRequest.Create(url); - request.Credentials = CredentialCache.DefaultCredentials; - request.Headers[Constants.Token] = ChatDaten.AuthToken; - request.Headers[Constants.CustomerId] = ChatDaten.Kundennummer; + webRequest.Credentials = CredentialCache.DefaultCredentials; + webRequest.Headers[Constants.Token] = ChatDaten.AuthToken; + webRequest.Headers[Constants.CustomerId] = ChatDaten.Kundennummer; - var response = request.GetResponse(); + var response = webRequest.GetResponse(); var responseFromServer = Utils.ReadStream(response); - var jsonDaten = JsonConvert.DeserializeObject(responseFromServer); + var messageCounter = JsonConvert.DeserializeObject(responseFromServer); - return jsonDaten.MessageCount; + return messageCounter.MessageCount; } - catch (Exception e) - { - return null; - } - } - - public double SchaueNachAllenMessageCounts() - { - var span = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); - var unixTime = Convert.ToInt64(span.TotalSeconds); - - var x = SendeTimestampForEach(0); - - if (x > 0) - { - _LastTimeStamp = unixTime; - } - - return x; - } - - private double SendeTimestampForEach(long groupId) - { - try - { - var endurl = ChatDaten.ServerUrl + "/api/ownchat/news/" + groupId + "/" + _LastTimeStamp; - - var request = WebRequest.Create(endurl); - - request.Credentials = CredentialCache.DefaultCredentials; - request.Headers[Constants.Token] = ChatDaten.AuthToken; - request.Headers[Constants.CustomerId] = ChatDaten.Kundennummer; - ((HttpWebRequest) request).KeepAlive = false; - - var response = request.GetResponse(); - - var responseFromServer = Utils.ReadStream(response); - - var jsonDaten = JsonConvert.DeserializeObject(responseFromServer); - - return jsonDaten.MessageCount; - - } - catch (Exception e) + catch (Exception exception) { return 0; - } + } + } + + public double GetNumberOfAllNewMessages() + { + var unixTime = DateTime.UtcNow.GetUnixTimeStamp(); + + var messageCount = 0d; + + messageCount += LoadNumberOfNewMessagesFromServer(0); + + if (messageCount > 0) + { + LastTimeStamp = unixTime; + } + + return messageCount; + } + + private double LoadNumberOfNewMessagesFromServer(long pGroupId) + { + try + { + var url = ChatDaten.ServerUrl + Constants.LoadOwnChatNewsUrl + pGroupId + "/" + LastTimeStamp; + + var webRequest = WebRequest.Create(url); + + webRequest.Credentials = CredentialCache.DefaultCredentials; + webRequest.Headers[Constants.Token] = ChatDaten.AuthToken; + webRequest.Headers[Constants.CustomerId] = ChatDaten.Kundennummer; + ((HttpWebRequest) webRequest).KeepAlive = false; + + var response = webRequest.GetResponse(); + + var responseFromServer = Utils.ReadStream(response); + + var messageCounter = JsonConvert.DeserializeObject(responseFromServer); + + return messageCounter.MessageCount; + } + catch (Exception exception) + { + return 0; + } } public IOrderedEnumerable NeueGroupklassenKontakte() { var contacts = new List(); - var groupData = GruppenHolen(); + var groupData = LoadGroups(); foreach (var contact in groupData.Response) { - foreach (var value in contact.Value) - { - var message = ""; - var timeformated = new DateTime(); - - var lastMessage = value.LastMessage; - - if (lastMessage?.Text != null) - { - message = lastMessage.Text; - var timestamp = DateTime.Parse(lastMessage.Timestamp.Date); - - var clientZone = TimeZoneInfo.Local; - timeformated = TimeZoneInfo.ConvertTimeFromUtc(timestamp, clientZone); - } - - if (string.IsNullOrEmpty(message) && !string.IsNullOrEmpty(value.LastMessage?.File)) - { - message = Path.GetFileName(value.LastMessage.File); - } - - long? customerOid = null; - var isEmployee = false; - - foreach (var user in value.Users) - { - if (user.Oid != ChatDaten.Userid) - { - if (!user.Is_Employee && !string.IsNullOrEmpty(user.Userid_Manage)) - { - customerOid = long.Parse(user.Userid_Manage.Substring(1)); - } - } - } - - if (value.OnlyEmployees && value.Users.Length == 2) - { - isEmployee = true; - } - - contacts.Add(new Contact(value.Name, Utils.AvatarToImageSourceConverter(value.Avatar, isEmployee), message, timeformated, value.Oid, customerOid, value.OnlyEmployees, value.Users.Length)); - - if (lastMessage?.Timestamp?.Date != null) { - var span = DateTime.Parse(lastMessage.Timestamp.Date) - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); - var unixTime = Convert.ToInt64(span.TotalSeconds); - - if (_LastTimeStamp < unixTime) - { - _LastTimeStamp = unixTime; - } - } - } + contacts.AddRange(GenerateContactsFromServerResponse(contact.Value, true)); } return contacts.OrderByDescending(r => r.TimeStamp); } - private ChatGruppenDaten GruppenHolen() + private ChatGruppenDaten LoadGroups() { try { @@ -502,7 +345,7 @@ namespace ChatController.HauptKlassen } } - public void AddeNachrichtDerView(string pMessage) + public void AddNewMessage(string pMessage, long pGroupId) { try { @@ -516,7 +359,7 @@ namespace ChatController.HauptKlassen var time = DateTime.Now; - _Messages.Add(new ChatMessage(username, pMessage, time, true)); + Messages.Add(new ChatMessage(username, pMessage, time, true, pGroupId)); } catch (Exception e) @@ -571,7 +414,7 @@ namespace ChatController.HauptKlassen } } - public string HoleMedium() + public string OpenFile() { try { @@ -588,7 +431,7 @@ namespace ChatController.HauptKlassen } } - public void AddeMediumDerNachrichtView(string pFile, string pOriginalFilePath) + public void AddNewFile(string pFile, string pOriginalFilePath, long pGroupId) { try { @@ -603,13 +446,13 @@ namespace ChatController.HauptKlassen if (Constants.ImageFileExtensions.Contains(Path.GetExtension(pFile).ToUpperInvariant())) { - byte[] mediaFile; + byte[] file; using (Stream reader = File.OpenRead(pFile)) { - mediaFile = ReadFully(reader); + file = Utils.ReadFully(reader); } - var memoryStream = new MemoryStream(mediaFile); + var memoryStream = new MemoryStream(file); var image = System.Drawing.Image.FromStream(memoryStream); using (var bitmap = new Bitmap(image)) @@ -628,7 +471,7 @@ namespace ChatController.HauptKlassen bitmap.SetPropertyItem(item); } - var flipType = OrientationToFlipType(orient.ToString()); + var flipType = Utils.OrientationToFlipType(orient.ToString()); bitmap.RotateFlip(flipType); @@ -645,20 +488,16 @@ namespace ChatController.HauptKlassen filename = filename.Replace(".bmp", ".jpg"); - _Messages.Add(new ChatMessage(message.User_Name, filename, sendTime, true, bitmapImage, pFile, filename)); + Messages.Add(new ChatMessage(message.User_Name, filename, sendTime, true, bitmapImage, pFile, filename, pGroupId)); } } memoryStream.Dispose(); memoryStream.Close(); } - else if (Constants.DocumentFileExtension.Contains(Path.GetExtension(pFile).ToUpperInvariant())) - { - _Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFile), sendTime, message.Smaller_Image, true, pFile)); - } else { - _Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFile), sendTime, message.Smaller_Image, true, pFile)); + Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFile), sendTime, message.Smaller_Image, true, pFile, pGroupId)); } } @@ -668,7 +507,7 @@ namespace ChatController.HauptKlassen } } - public void AddMediumContextDerNachrichtView(byte[] pFile, string pFileName) + public void AddMediumContextDerNachrichtView(byte[] pFile, string pFileName, long pGroupId) { if(string.IsNullOrEmpty(pFileName)) { @@ -691,27 +530,27 @@ namespace ChatController.HauptKlassen memoryStream.Close(); ImageSource logo = bitmapImage; - _Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFileName), sendtime, true, logo, pFileName, Path.GetFileName(pFileName))); + Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFileName), sendtime, true, logo, pFileName, Path.GetFileName(pFileName), pGroupId)); } else { - _Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFileName), sendtime, message.Smaller_Image, true, pFileName)); + Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFileName), sendtime, message.Smaller_Image, true, pFileName, pGroupId)); } } - public void SendeMediumAnKontakt(AktuellerKontakt kontakt,string file,string originalFilePath) + public void SendFileToContact(CurrentContact pCurrentContact, string pFile, string pOriginalFilePath) { try { - VerarbeiteMedia(file,kontakt,originalFilePath); + SendFile(pFile, pCurrentContact, pOriginalFilePath); } catch (Exception e) { - MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK); + MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error); } } - private void VerarbeiteMedia(string pFile, AktuellerKontakt pContact, string pOriginalFilePath) + private void SendFile(string pFile, CurrentContact pContact, string pOriginalFilePath) { if(string.IsNullOrEmpty(pOriginalFilePath)) { @@ -721,7 +560,7 @@ namespace ChatController.HauptKlassen byte[] mediaFile; using (Stream reader = File.OpenRead(pFile)) { - mediaFile = ReadFully(reader); + mediaFile = Utils.ReadFully(reader); } var fileName = Path.GetFileName(pOriginalFilePath).ToLower(); @@ -745,12 +584,11 @@ namespace ChatController.HauptKlassen byte[] mediaFile; using (Stream reader = File.OpenRead(pFile)) { - mediaFile = ReadFully(reader); + mediaFile = Utils.ReadFully(reader); } var memoryStream = new MemoryStream(mediaFile); var image = System.Drawing.Image.FromStream(memoryStream); - float width, height; @@ -848,46 +686,12 @@ namespace ChatController.HauptKlassen return filePath; } - catch (Exception e) + catch (Exception exception) { return pFile; } } - public static RotateFlipType OrientationToFlipType(string orientation) - { - switch (int.Parse(orientation)) - { - case 1: - return RotateFlipType.RotateNoneFlipNone; - case 2: - return RotateFlipType.RotateNoneFlipX; - case 3: - return RotateFlipType.Rotate180FlipNone; - case 4: - return RotateFlipType.Rotate180FlipX; - case 5: - return RotateFlipType.Rotate90FlipX; - case 6: - return RotateFlipType.Rotate90FlipNone; - case 7: - return RotateFlipType.Rotate270FlipX; - case 8: - return RotateFlipType.Rotate270FlipNone; - default: - return RotateFlipType.RotateNoneFlipNone; - } - } - - private static byte[] ReadFully(Stream pStream) - { - using(var memStream = new MemoryStream()) - { - pStream.CopyTo(memStream); - return memStream.ToArray(); - } - } - private HttpRequestMessage _HttpRequest; private async void SendMediaMessage(string pMessage, long pGroupId, byte[] pMediaFile) @@ -927,15 +731,14 @@ namespace ChatController.HauptKlassen { var contextMenu = new ContextMenu(); - System.Windows.Controls.MenuItem item1 = new System.Windows.Controls.MenuItem(); - System.Windows.Controls.MenuItem item2 = new System.Windows.Controls.MenuItem(); - System.Windows.Controls.MenuItem item3 = new System.Windows.Controls.MenuItem(); + var item1 = new System.Windows.Controls.MenuItem(); + var item2 = new System.Windows.Controls.MenuItem(); + var item3 = new System.Windows.Controls.MenuItem(); contextMenu.Items.Add(item1); contextMenu.Items.Add(item2); contextMenu.Items.Add(item3); - item1.Header = "Speichern unter"; item1.Visibility = Visibility.Visible; @@ -948,15 +751,15 @@ namespace ChatController.HauptKlassen return contextMenu; } - public void SpeichernUnterFunkion(ChatMessage pChatMessage) + public void SaveFileAs(ChatMessage pChatMessage) { if (pChatMessage.ImageSources != null) { - SpeichernUnter(1, Path.GetFileName(pChatMessage.OriginalImage), DownloadMediaDatei(pChatMessage.OriginalImage)); + SaveAs(1, Path.GetFileName(pChatMessage.OriginalImage), DownloadMediaFile(pChatMessage.OriginalImage)); } } - private static byte[] DownloadMediaDatei(string pFilePath) + private static byte[] DownloadMediaFile(string pFilePath) { byte[] mediaFile = null; @@ -977,7 +780,7 @@ namespace ChatController.HauptKlassen return mediaFile; } - private static void SpeichernUnter(int pFilterType, string pFileName, byte[] pMediaFile) + private static void SaveAs(int pFilterType, string pFileName, byte[] pMediaFile) { try { @@ -1017,7 +820,7 @@ namespace ChatController.HauptKlassen } } - public void Einfuegen(long pGroupOid, ChatMainControl pChatMainControl) + public void Paste(long pGroupOid, ChatMainControl pChatMainControl) { var dataObject = Clipboard.GetDataObject(); @@ -1038,7 +841,7 @@ namespace ChatController.HauptKlassen var mediaFile = File.ReadAllBytes(fileList[0]); - AddMediumContextDerNachrichtView(mediaFile, fileName); + AddMediumContextDerNachrichtView(mediaFile, fileName, pGroupOid); CollectionViewSource.GetDefaultView(pChatMainControl.ChatListBox.ItemsSource).Refresh(); @@ -1060,7 +863,7 @@ namespace ChatController.HauptKlassen { var text = (string) dataObject.GetData(DataFormats.StringFormat); - AddeNachrichtDerView(text); + AddNewMessage(text, pGroupOid); CollectionViewSource.GetDefaultView(pChatMainControl.ChatListBox.ItemsSource).Refresh(); @@ -1073,18 +876,18 @@ namespace ChatController.HauptKlassen { var bitmap = (Bitmap) dataObject.GetData(DataFormats.Bitmap); - var imageName = GenerateTempName() + ".jpg"; + var imageName = Utils.GenerateTempName() + ".jpg"; System.Drawing.Image image = bitmap; - AddMediumContextDerNachrichtView(ImageToByteArray(image), imageName); + AddMediumContextDerNachrichtView(Utils.ImageToByteArray(image), imageName, pGroupOid); CollectionViewSource.GetDefaultView(pChatMainControl.ChatListBox.ItemsSource).Refresh(); pChatMainControl.ChatListBox.Items.MoveCurrentToLast(); pChatMainControl.ChatListBox.ScrollIntoView(pChatMainControl.ChatListBox.Items.CurrentItem); - SendMediaMessage(imageName, pGroupOid, ImageToByteArray(image)); + SendMediaMessage(imageName, pGroupOid, Utils.ImageToByteArray(image)); } else { @@ -1093,35 +896,7 @@ namespace ChatController.HauptKlassen } } - public static byte[] ImageToByteArray(System.Drawing.Image pImage) - { - try - { - using (var memoryStream = new MemoryStream()) - { - pImage.Save(memoryStream, ImageFormat.Bmp); - return memoryStream.ToArray(); - } - } - catch (Exception e) - { - MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK); - return null; - } - } - - private static string GenerateTempName() - { - const int length = 6; - const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - var random = new Random(); - - var tempName = new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray()); - - return tempName; - } - - public void Kopieren(object pData, int pDataType) + public void Copy(object pData, int pDataType) { switch(pDataType) { @@ -1137,7 +912,7 @@ namespace ChatController.HauptKlassen } } - public void ShowProfilePicture(AktuellerKontakt pCurrentContact) + public void ShowProfilePicture(CurrentContact pCurrentContact) { try { @@ -1219,7 +994,7 @@ namespace ChatController.HauptKlassen bitmap.SetPropertyItem(item); } - var flipType = OrientationToFlipType(orient.ToString()); + var flipType = Utils.OrientationToFlipType(orient.ToString()); bitmap.RotateFlip(flipType); @@ -1299,7 +1074,7 @@ namespace ChatController.HauptKlassen return false; } } - catch (Exception e) + catch (Exception exception) { MessageBox.Show("Die Verbindung konnte nicht aufgebaut werden.", "Fehler ", MessageBoxButton.OK); return false; @@ -1335,11 +1110,11 @@ namespace ChatController.HauptKlassen } } - public ChatGruppenDaten GruppenAktuallisieren() + public ChatGruppenDaten UpdateGroups() { try { - var endurl = ChatDaten.ServerUrl + "/api/chat/groups"; + var endurl = ChatDaten.ServerUrl + Constants.GetChatGroupsUrl; var request = WebRequest.Create(endurl); @@ -1353,13 +1128,7 @@ namespace ChatController.HauptKlassen response.Close(); - if (!string.IsNullOrEmpty(serverResponse)) - { - var jsonDaten = JsonConvert.DeserializeObject(serverResponse); - - return jsonDaten; - } - return null; + return !string.IsNullOrEmpty(serverResponse) ? JsonConvert.DeserializeObject(serverResponse) : null; } catch (Exception e) { @@ -1375,45 +1144,7 @@ namespace ChatController.HauptKlassen _Contacts.Clear(); foreach (var contact in chatDaten.Response) { - foreach (var value in contact.Value) - { - var message = ""; - var timestamp = new DateTime(); - - var lastMessage = value.LastMessage; - - if (lastMessage?.Text != null) - { - message = lastMessage.Text; - timestamp = DateTime.Parse(lastMessage.Timestamp.Date); - } - - if (string.IsNullOrEmpty(message) && value.LastMessage != null && !string.IsNullOrEmpty(value.LastMessage.File)) - { - message = Path.GetFileName(value.LastMessage.File); - } - - long? customerOid = null; - var isEmployee = false; - - foreach (var user in value.Users) - { - if (user.Oid != ChatDaten.Userid && !string.IsNullOrEmpty(user.Userid_Manage)) - { - if (!user.Is_Employee) - { - customerOid = long.Parse(user.Userid_Manage.Substring(1)); - } - } - } - - if (value.OnlyEmployees && value.Users.Length == 2) - { - isEmployee = true; - } - - _Contacts.Add(new Contact(value.Name, Utils.AvatarToImageSourceConverter(value.Avatar, isEmployee), message, timestamp, value.Oid, customerOid, value.OnlyEmployees, value.Users.Length)); - } + _Contacts.AddRange(GenerateContactsFromServerResponse(contact.Value)); } return _Contacts.OrderByDescending(r => r.TimeStamp); @@ -1425,58 +1156,51 @@ namespace ChatController.HauptKlassen } } - public Dictionary PruefeTimeStampsBeiStart(List kontaktliste) + public Dictionary CheckTimeStampsAtStart(List pContacts) { try { - if (File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"))) + if (File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName))) { - Dictionary merkdaten = new Dictionary(); + var syncData = new Dictionary(); - using (StreamReader sr = new StreamReader(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"), true)) + using (var streamReader = new StreamReader(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName), 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); - var plainarray = plainText.Split(';'); + var splitPlainText = plainText.Split(';'); - merkdaten.Add(plainarray[0], plainarray[1]); + syncData.Add(splitPlainText[0], splitPlainText[1]); } } - Dictionary rueckgabe = new Dictionary(); + var result = new Dictionary(); - foreach (var kontakt in kontaktliste) + foreach (var contact in pContacts) { - foreach (var daten in merkdaten) + foreach (var data in syncData) { - var groupoid = Int32.Parse(daten.Key); + var groupoid = int.Parse(data.Key); - if (kontakt.GroupId == groupoid) + if (contact.GroupId == groupoid) { - var datetime = DateTime.Parse(daten.Value); + var datetime = DateTime.Parse(data.Value); - if (kontakt.TimeStamp.Equals(datetime)) + if (contact.TimeStamp.Equals(datetime)) { - rueckgabe.Add(groupoid,datetime); + result.Add(groupoid, datetime); } } } } - if (rueckgabe.Count > 0) - { - return rueckgabe; - } - else - { - return null; - } + return result.Count > 0 ? result : null; } return null; @@ -1487,90 +1211,119 @@ namespace ChatController.HauptKlassen } } - public void SpeichereTimeStampsInDatei( List kontaktliste ) + public void SaveTimeStampsToFile(List pContacts) { try { - if (!File.Exists(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"))) + if(File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName))) { - using ( - StreamWriter sw = - new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"))) + 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); - Encoding enc = new UTF8Encoding(); - - foreach (var kontakt in kontaktliste) - { - var text = kontakt.GroupId + ";" + kontakt.TimeStamp+";"; - var byt = enc.GetBytes(text); - var bytes = Convert.ToBase64String(byt); - - sw.WriteLine(bytes); - } - - File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"), - FileAttributes.ReadOnly); + streamWriter.WriteLine(base64String); } + + File.SetAttributes(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName), FileAttributes.ReadOnly); + } + } + catch (Exception exception) + { + + } + } + + public List GenerateContactsFromServerResponse(GroupInput[] pGroupInputs, bool pShouldUpdateLastTimeStamp = false) + { + var contacts = new List(); + + foreach(var groupInput in pGroupInputs) + { + var messageText = string.Empty; + var formattedTime = new DateTime(); + + var latestMessage = groupInput.LastMessage; + + if(latestMessage?.Text != null) + { + messageText = latestMessage.Text; + + var timeStamp = DateTime.Parse(latestMessage.Timestamp.Date); + var clientZone = TimeZoneInfo.Local; + + formattedTime = TimeZoneInfo.ConvertTimeFromUtc(timeStamp, clientZone); + } + + if(string.IsNullOrEmpty(messageText) && !string.IsNullOrEmpty(groupInput.LastMessage?.File)) + { + messageText = Path.GetFileName(groupInput.LastMessage.File); + } + + string userIdManage = null; + + foreach(var user in groupInput.Users) + { + if(user.Oid != ChatDaten.Userid) + { + if(!user.Is_Employee && !string.IsNullOrEmpty(user.Userid_Manage)) + { + userIdManage = user.Userid_Manage; + } + } + } + + var avatar = Utils.AvatarToImageSourceConverter(groupInput.Avatar, groupInput.OnlyEmployees, groupInput.Users.Length > 2); + + contacts.Add(new Contact(groupInput.Name, avatar, messageText, formattedTime, groupInput.Oid, userIdManage, groupInput.OnlyEmployees, groupInput.Users.Length)); + + if(pShouldUpdateLastTimeStamp) + { + if(latestMessage?.Timestamp?.Date != null) + { + var unixTimeStamp = DateTime.Parse(latestMessage.Timestamp.Date).GetUnixTimeStamp(); + + if(LastTimeStamp < unixTimeStamp) + { + LastTimeStamp = unixTimeStamp; + } + } + } + } + + return contacts; + } + + public void AddMessagesFromServerResponse(Messages[] pMessages) + { + foreach (var message in pMessages) + { + 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); + + if (!string.IsNullOrEmpty(message.File)) + { + Messages.Add(Constants.ImageFileExtensions.Contains(Path.GetExtension(message.File).ToUpperInvariant()) ? + new ChatMessage(message.User_Name, messageText, formattedTime, isLoggedInUsersMessage, DownloadImage(message.Smaller_Image), message.File, message.Original_Filename, message.GroupId) : + new ChatMessage(message.User_Name, messageText, formattedTime, message.Smaller_Image, isLoggedInUsersMessage, message.File, message.GroupId)); } else { - File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"), FileAttributes.Normal); - File.Delete(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt")); - - using ( - StreamWriter sw = new StreamWriter(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"))) - { - - Encoding enc = new UTF8Encoding(); - - foreach (var kontakt in kontaktliste) - { - var text = kontakt.GroupId + ";" + kontakt.TimeStamp + ";"; - var byt = enc.GetBytes(text); - var bytes = Convert.ToBase64String(byt); - - sw.WriteLine(bytes); - } - - File.SetAttributes(Path.Combine(GetAndCreateUserAppDataPath(), "ownChatMessageSync.txt"), - FileAttributes.ReadOnly); - } + Messages.Add(new ChatMessage(message.User_Name, message.Text, formattedTime, isLoggedInUsersMessage, message.GroupId)); } } - catch (Exception e) - { - - } - } - - private static string GetAndCreateUserAppDataPath() - { - try - { - string localAppData = Environment.GetFolderPath( - Environment.SpecialFolder.LocalApplicationData); - string companyFilePath - = Path.Combine(localAppData, "beyondSoft"); - - if (!Directory.Exists(companyFilePath)) - Directory.CreateDirectory(companyFilePath); - - string bewoFilePath - = Path.Combine(companyFilePath, "OwnChat"); - - if (!Directory.Exists(bewoFilePath)) - Directory.CreateDirectory(bewoFilePath); - - return bewoFilePath; - } - catch (Exception ex) - { - MessageBox.Show( - "Fehler beim Anlegen des Anwendungsordners. Sie besitzen nicht die erforderlichen Rechte, bitte wenden Sie sich an Ihren Systemadministrator.\n" + - ex.Message, "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Exclamation); - } - return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } } } diff --git a/ChatController/HauptKlassen/Login.cs b/ChatController/HauptKlassen/Login.cs index 3f9d882..464bad2 100644 --- a/ChatController/HauptKlassen/Login.cs +++ b/ChatController/HauptKlassen/Login.cs @@ -5,8 +5,6 @@ using System.Net; using System.Text; using System.Web; using System.Windows; - -using ChatController.Klassen; using ChatController.LoginKlassen; using ChatController.Utilities; @@ -34,7 +32,7 @@ namespace ChatController.HauptKlassen private bool _ownchatVerbindungsaufbauOK; private bool _gruppeholenverbindungsaufbauOK; - private AuthentifizierungsDaten _serverconect; + private AuthenticationData _serverconect; private UserDaten _LoggedInUser; private ChatGruppenDaten _AllGroups; @@ -46,10 +44,10 @@ namespace ChatController.HauptKlassen _ChatCode = pChatCode; _UserName = pUserName; _Password = pPassword; - _ApiKey = "0000";//default damit nichts kaput geht + _ApiKey = "0000";//default, damit nichts kaputt geht } - public Login(string pTenant, string pChatCode, string pUserName, string pPassword,string pApiKey) + public Login(string pTenant, string pChatCode, string pUserName, string pPassword, string pApiKey) { _Tenant = pTenant; _ChatCode = pChatCode; @@ -69,31 +67,33 @@ namespace ChatController.HauptKlassen public ChatDatenUebergabe AnmeldevorgangDurchFuehren() { if(ServerErmittlung()){ - Dictionary dic = new Dictionary(); + var dic = new Dictionary + { + {"username", _UserName}, + { "password", _Password}, + { "chatcode", _ChatCode} + }; - dic.Add("username", _UserName); - dic.Add("password", _Password); - dic.Add("chatcode",_ChatCode); - - VerbindeMitChatServer(dic); + VerbindeMitChatServer(dic); - if (_ownchatVerbindungsaufbauOK) - { - GetGroups(); - } + if (_ownchatVerbindungsaufbauOK) + { + GetGroups(); + } - if (_gruppeholenverbindungsaufbauOK) - { + if (_gruppeholenverbindungsaufbauOK) + { - long maxUploadSize = GetMaiximumAllowedFileUploadSize(_AuthToken,_Tenant); + var maxUploadSize = GetMaiximumAllowedFileUploadSize(_AuthToken,_Tenant); - ChatDatenUebergabe ubergabe = new ChatDatenUebergabe(_serverconect, _LoggedInUser, _AllGroups, ServerUrl, _AuthToken, _UserId, _Tenant,_ApiKey, maxUploadSize); + var ubergabe = new ChatDatenUebergabe(_serverconect, _LoggedInUser, _AllGroups, ServerUrl, _AuthToken, _UserId, _Tenant,_ApiKey, maxUploadSize); - return ubergabe; - } - } - return null; + return ubergabe; + } + } + + return null; } public bool ServerErmittlung() @@ -128,7 +128,7 @@ namespace ChatController.HauptKlassen try { - var jsonDatentyp = JsonConvert.DeserializeObject(responseFromServer); + var jsonDatentyp = JsonConvert.DeserializeObject(responseFromServer); switch(jsonDatentyp.Status) { @@ -154,7 +154,7 @@ namespace ChatController.HauptKlassen { try { - var jsonDatentyp = JsonConvert.DeserializeObject(responseFromServer); + var jsonDatentyp = JsonConvert.DeserializeObject(responseFromServer); switch(jsonDatentyp.Status) { diff --git a/ChatController/LoginControl.xaml b/ChatController/LoginControl.xaml index 1e6724e..9f0a4c9 100644 --- a/ChatController/LoginControl.xaml +++ b/ChatController/LoginControl.xaml @@ -3,7 +3,6 @@ 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" - xmlns:local="clr-namespace:ChatController" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> @@ -23,8 +22,6 @@ - - diff --git a/ChatController/LoginControl.xaml.cs b/ChatController/LoginControl.xaml.cs index e981a6d..7e018be 100644 --- a/ChatController/LoginControl.xaml.cs +++ b/ChatController/LoginControl.xaml.cs @@ -9,7 +9,6 @@ using System.Windows; using System.Windows.Input; using ChatController.HauptKlassen; -using ChatController.Klassen; using ChatController.LoginKlassen; using Newtonsoft.Json; @@ -448,8 +447,11 @@ namespace ChatController } } #endregion - + + + public void Login() + { + Anmelden(); + } } - - } diff --git a/ChatController/LoginKlassen/AuthenticationData.cs b/ChatController/LoginKlassen/AuthenticationData.cs index 69bd617..99c53e2 100644 --- a/ChatController/LoginKlassen/AuthenticationData.cs +++ b/ChatController/LoginKlassen/AuthenticationData.cs @@ -1,18 +1,18 @@ namespace ChatController.LoginKlassen { - public class AuthentifizierungsDaten + public class AuthenticationData { public string CustomerId { get; set; } public string ServerName { get; set; } } - public class NewAuthentifizierungsDatenTyp1 + public class AuthenticationDataType1 { public int Status { get; set; } public string Url { get; set; } } - public class NewAuthentifizierungsDatenTyp2 + public class AuthenticationDataType2 { public int Status { get; set; } public string Url { get; set; } diff --git a/ChatController/LoginKlassen/ChatDatenUebergabe.cs b/ChatController/LoginKlassen/ChatDatenUebergabe.cs index 1c6b06f..3e64c0c 100644 --- a/ChatController/LoginKlassen/ChatDatenUebergabe.cs +++ b/ChatController/LoginKlassen/ChatDatenUebergabe.cs @@ -2,7 +2,7 @@ { public class ChatDatenUebergabe { - private AuthentifizierungsDaten _serverconect { get; } + private AuthenticationData _serverconect { get; } private UserDaten _angemeldeterUser { get; } private ChatGruppenDaten _alleGruppen { get; } @@ -13,7 +13,7 @@ private string _ApiKey { get; } private long _MaxUploadSize { get; } - public ChatDatenUebergabe(AuthentifizierungsDaten serverConect, UserDaten angemeldeterUser, ChatGruppenDaten alleGruppen, string serverUrl, string authToken, long? userid, string kundennummer, string apikey,long maxUploadSize) + public ChatDatenUebergabe(AuthenticationData serverConect, UserDaten angemeldeterUser, ChatGruppenDaten alleGruppen, string serverUrl, string authToken, long? userid, string kundennummer, string apikey,long maxUploadSize) { _serverconect = serverConect; _angemeldeterUser = angemeldeterUser; @@ -27,7 +27,7 @@ _MaxUploadSize = maxUploadSize; } - public AuthentifizierungsDaten Serverconect => _serverconect; + public AuthenticationData Serverconect => _serverconect; public UserDaten AngemeldeterUser => _angemeldeterUser; diff --git a/ChatController/LoginKlassen/ChatGruppenDaten.cs b/ChatController/LoginKlassen/ChatGruppenDaten.cs index ec51124..bf726a6 100644 --- a/ChatController/LoginKlassen/ChatGruppenDaten.cs +++ b/ChatController/LoginKlassen/ChatGruppenDaten.cs @@ -12,7 +12,7 @@ namespace ChatController.LoginKlassen public class GroupInput { - public long Oid { get; set; } + public int Oid { get; set; } public string Name { get; set; } public string Avatar { get; set; } public string Mobile { get; set; } diff --git a/ChatController/LoginKlassen/UserMessages.cs b/ChatController/LoginKlassen/UserMessages.cs index 6fc873b..a8848ee 100644 --- a/ChatController/LoginKlassen/UserMessages.cs +++ b/ChatController/LoginKlassen/UserMessages.cs @@ -10,7 +10,7 @@ public class UserMessageInput { - public string currentPage { get; set; } + public string CurrentPage { get; set; } public bool HasMorePages { get; set; } public string NextPage { get; set; } public int PerPage { get; set; } diff --git a/ChatController/Utilities/Constants.cs b/ChatController/Utilities/Constants.cs index 0e3453b..1ef15ea 100644 --- a/ChatController/Utilities/Constants.cs +++ b/ChatController/Utilities/Constants.cs @@ -23,10 +23,6 @@ namespace ChatController.Utilities public static readonly string UrlPageParameter = "&page="; - public static readonly string ConfigFile = "ownChat.txt"; - public static readonly string CompanyName = "beyondSoft"; - public static readonly string ApplicationFolderName = "OwnChat"; - public static readonly int NotificationTimeout = 1500; } } diff --git a/ChatController/Utilities/Utils.cs b/ChatController/Utilities/Utils.cs index 322a7ed..75ad089 100644 --- a/ChatController/Utilities/Utils.cs +++ b/ChatController/Utilities/Utils.cs @@ -2,20 +2,26 @@ using System.Drawing; using System.Drawing.Imaging; using System.IO; +using System.Linq; using System.Net; -using System.Windows.Forms; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; +using MessageBox = System.Windows.MessageBox; +using PixelFormat = System.Drawing.Imaging.PixelFormat; namespace ChatController.Utilities { public class Utils { - public static NotifyIcon NotifyIcon = new NotifyIcon {Icon = Resource.ownchat_favicon, Visible = true}; + public static DateTime DefaultDate = new DateTime(1,1,1); - public static ImageSource AvatarToImageSourceConverter(string pAvatarPath, bool pIsEmployee) + public static ImageSource AvatarToImageSourceConverter(string pAvatarPath, bool pIsEmployee, bool pIsGroup) { - return CreateImageSourceFromPath(pAvatarPath, false, pIsEmployee); + return CreateImageSourceFromPath(pAvatarPath, pIsGroup, pIsEmployee); } public static ImageSource CreateChatGroupPictureImageSource(string pPicturePath, bool pIsGroup, bool pIsEmployee) @@ -145,5 +151,172 @@ namespace ChatController.Utilities return responseFromServer; } + + public static string GetAndCreateUserAppDataPath() + { + try + { + var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + var companyFilePath = Path.Combine(localAppData, Resource.CompanyName); + + if (!Directory.Exists(companyFilePath)) + { + Directory.CreateDirectory(companyFilePath); + } + + var bewoFilePath = Path.Combine(companyFilePath, Resource.ApplicationFolderName); + + if (!Directory.Exists(bewoFilePath)) + { + Directory.CreateDirectory(bewoFilePath); + } + + return bewoFilePath; + } + catch (Exception exception) + { + MessageBox.Show("Fehler beim Anlegen des Anwendungsordners. Sie besitzen nicht die erforderlichen Rechte, bitte wenden Sie sich an Ihren Systemadministrator.\n" + exception.Message, "BeWoPlaner", MessageBoxButton.OK, MessageBoxImage.Exclamation); + } + + return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + } + + public static string GenerateTempName() + { + const int length = 6; + const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + var random = new Random(); + + var tempName = new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray()); + + return tempName; + } + + public static byte[] ImageToByteArray(Image pImage) + { + try + { + using (var memoryStream = new MemoryStream()) + { + pImage.Save(memoryStream, ImageFormat.Bmp); + return memoryStream.ToArray(); + } + } + catch (Exception e) + { + MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK); + return null; + } + } + + public static ImageSource GetImageSourceFromIcon(Icon pIcon) + { + var bitmap = new Bitmap(pIcon.Width, pIcon.Height); + + var graphics = Graphics.FromImage(bitmap); + + graphics.DrawIcon(pIcon, 0, 0); + + graphics.Dispose(); + + + bitmap.Save("icon.ico", ImageFormat.Icon); + + var imageSource = ImageSourceForBitmap(bitmap); + + bitmap.Dispose(); + + return imageSource; + } + + [DllImport("gdi32.dll", EntryPoint = "DeleteObject")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool DeleteObject([In] IntPtr hObject); + + public static ImageSource ImageSourceForBitmap(Bitmap bmp) + { + var handle = bmp.GetHbitmap(); + + try + { + return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); + } + finally + { + DeleteObject(handle); + } + } + + public static Icon ImageSourceToIcon(ImageSource pImageSource) + { + var bitmapSource = (BitmapSource) pImageSource; + + var width = bitmapSource.PixelWidth; + var height = bitmapSource.PixelHeight; + + var newWidth = width; + var newHeight = height; + + var x = 0; + var y = 0; + + if(width < height) + { + newHeight = width; + y = (height - width) / 2; + } + else + { + newWidth = height; + x = (width - height) / 2; + } + + var stride = width * ((bitmapSource.Format.BitsPerPixel + 7) / 8); + var memoryBlockPointer = Marshal.AllocHGlobal(height * stride); + + bitmapSource.CopyPixels(new Int32Rect(x, y, newWidth, newHeight), memoryBlockPointer, newHeight * stride, stride); + + var bitmap = new Bitmap(newWidth, newHeight, stride, PixelFormat.Format32bppPArgb, memoryBlockPointer); + + 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()) + { + pStream.CopyTo(memStream); + return memStream.ToArray(); + } + } + + public static RotateFlipType OrientationToFlipType(string orientation) + { + switch (int.Parse(orientation)) + { + case 1: + return RotateFlipType.RotateNoneFlipNone; + case 2: + return RotateFlipType.RotateNoneFlipX; + case 3: + return RotateFlipType.Rotate180FlipNone; + case 4: + return RotateFlipType.Rotate180FlipX; + case 5: + return RotateFlipType.Rotate90FlipX; + case 6: + return RotateFlipType.Rotate90FlipNone; + case 7: + return RotateFlipType.Rotate270FlipX; + case 8: + return RotateFlipType.Rotate270FlipNone; + default: + return RotateFlipType.RotateNoneFlipNone; + } + } } } diff --git a/PrototypChat/LoginMaske.xaml b/PrototypChat/LoginMaske.xaml index 4e6e989..db4b659 100644 --- a/PrototypChat/LoginMaske.xaml +++ b/PrototypChat/LoginMaske.xaml @@ -6,8 +6,8 @@ Icon="pack://application:,,,/ChatController;component/Ressourcen/ownchat_icon.png" xmlns:cc="clr-namespace:ChatController;assembly=ChatController" mc:Ignorable="d" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" - Title="ownChat Desktop" Height="500" Width="700" > + Title="ownChat Desktop" Height="500" Width="700" KeyDown="LoginMaske_OnKeyDown"> - + diff --git a/PrototypChat/LoginMaske.xaml.cs b/PrototypChat/LoginMaske.xaml.cs index f31d2a6..ade8f5e 100644 --- a/PrototypChat/LoginMaske.xaml.cs +++ b/PrototypChat/LoginMaske.xaml.cs @@ -1,4 +1,6 @@ -using ChatController.LoginKlassen; +using System.Windows.Input; +using ChatController; +using ChatController.LoginKlassen; namespace ownChat { @@ -17,5 +19,10 @@ namespace ownChat mainWindow.Show(); Close(); } + + private void LoginMaske_OnKeyDown(object sender, KeyEventArgs e) + { + LoginControl.Login(); + } } } diff --git a/PrototypChat/MainWindow.xaml b/PrototypChat/MainWindow.xaml index b5e3d42..537e0cb 100644 --- a/PrototypChat/MainWindow.xaml +++ b/PrototypChat/MainWindow.xaml @@ -7,6 +7,6 @@ mc:Ignorable="d" WindowStartupLocation="CenterScreen" Icon="pack://application:,,,/ChatController;component/Ressourcen/ownchat_icon.png" Title="ownChat Desktop" Height="700" Width="900" x:Name="MainView" Closed="MainWindow_OnClosed"> - + diff --git a/PrototypChat/MainWindow.xaml.cs b/PrototypChat/MainWindow.xaml.cs index 23de1fe..6339f11 100644 --- a/PrototypChat/MainWindow.xaml.cs +++ b/PrototypChat/MainWindow.xaml.cs @@ -15,7 +15,9 @@ namespace ownChat public MainWindow(ChatDatenUebergabe x) { InitializeComponent(); - + + ChatMainControl.ContainingWindow = this; + ChatMainControl.InitMitChatdaten(x); ChatMainControl.ResetStyle(); @@ -38,13 +40,8 @@ namespace ownChat private void MainWindow_OnClosed(object sender, EventArgs e) { - ChatMainControl.SpeichereMessageInfoInDatei(); - Environment.Exit(0); - } - - private void ChatMainControl_OnOnClose() - { - ChatMainControl.SpeichereMessageInfoInDatei(); + ChatMainControl.WriteToNewSyncFile(); + ChatMainControl.ClearNotifications(); Environment.Exit(0); } } diff --git a/PrototypChat/PrototypChat.csproj b/PrototypChat/PrototypChat.csproj index 9913243..996a09c 100644 --- a/PrototypChat/PrototypChat.csproj +++ b/PrototypChat/PrototypChat.csproj @@ -126,6 +126,7 @@ + Code