Files
Chat/ChatController/HauptKlassen/Chat.cs
Lyndon Jetten e8ef515e7a Der Login läuft jetzt mit RestSharp.
Die Akzentfarbe von den Chatgruppen vom Server wird berücksichtigt.
Bilder sind im richtigen Seitenverhältnis skaliert.
Ein Bild, das man gerade erst verschickt hat und das man öffnen will, bevor es auf dem Server angekommen ist, wird jetzt erst angezeigt, sobald es auf dem Server ist.
Die Textbox für eine neue Nachricht wird nur angezeigt, wenn eine Gruppe ausgewählt ist und wenn man das Recht hat Nachrichten an diese Gruppe zu verschicken.
Diverse Codeverbesserungen.
2020-06-17 19:36:52 +02:00

1196 lines
44 KiB
C#

using ChatController.ChatKlassen;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Data;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using ChatController.LoginKlassen;
using ChatController.Utilities;
using ChatController.Utilities.Extensions;
using RestSharp;
using RestSharp.Extensions.MonoHttp;
using Application = System.Windows.Forms.Application;
using Clipboard = System.Windows.Forms.Clipboard;
using ContextMenu = System.Windows.Controls.ContextMenu;
using DataFormats = System.Windows.Forms.DataFormats;
using MessageBox = System.Windows.MessageBox;
using Size = System.Drawing.Size;
namespace ChatController.HauptKlassen
{
public class Chat
{
public Action<Exception> ExceptionCallback { get; set; }
private readonly List<Contact> _Contacts = new List<Contact>();
public List<ChatMessage> Messages { get; set; } = new List<ChatMessage>();
public ChatDatenUebergabe ChatDaten { get; set; }
private UserMessages _UserMessages;
private UserMessages _AdditionalUserMessages;
private string _NextPage;
private bool _HasNextPage;
public long LastTimeStamp { get; set; }
public Chat(ChatDatenUebergabe chatDaten, Action<Exception> exceptionCallback)
{
ChatDaten = chatDaten;
ExceptionCallback = exceptionCallback;
}
// WebRequest
public List<Contact> AddContacts()
{
_Contacts.AddRange(GenerateContactsFromServerResponse(ChatDaten.AlleGruppen.Response.Groups.ToArray(), true));
return _Contacts;
}
public IOrderedEnumerable<ChatMessage> LoadChatMessagesForContact(Contact currentContact)
{
if (currentContact != null)
{
LoadMessagesFromServer(currentContact.GroupId);
Messages.Clear();
AddMessagesFromServerResponse(_UserMessages.Response.Messages);
}
return Messages.OrderBy(r => r.SendTime);
}
// WebRequest
// TODO: Auth-Token zum Header hinzufügen
private ImageSource DownloadImage(string pUri)
{
try
{
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri(pUri);
bitmapImage.CacheOption = BitmapCacheOption.OnDemand;
bitmapImage.EndInit();
return bitmapImage;
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
return null;
}
}
// WebRequest
private void LoadMessagesFromServer(long pGroupId)
{
try
{
var endurl = ChatDaten.ServerUrl + Constants.LoadMessagesForGroupUrl + pGroupId;
var webRequest = WebRequest.Create(endurl);
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.Headers[Constants.Token] = ChatDaten.AuthToken;
webRequest.Headers[Constants.CustomerId] = ChatDaten.Kundennummer;
using (var response = webRequest.GetResponse())
{
var serverResponse = Utils.ReadStream(response);
if (!string.IsNullOrEmpty(serverResponse))
{
Debug.WriteLine(serverResponse);
_UserMessages = JsonConvert.DeserializeObject<UserMessages>(serverResponse);
if (_UserMessages.Response.HasMorePages)
{
_NextPage = _UserMessages.Response.NextPage;
_HasNextPage = true;
}
else
{
_HasNextPage = false;
}
}
}
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
// WebRequest
public void LoadMoreMessages(Contact pContact)
{
if (_HasNextPage)
{
LoadMoreMessagesFromServer(pContact.GroupId, _NextPage);
AddMessagesFromServerResponse(_AdditionalUserMessages.Response.Messages);
}
}
private void LoadMoreMessagesFromServerAsync(long groupId, string page, Action callback)
{
try
{
var pageParam = page.Split('=');
var url = $"{ChatDaten.ServerUrl}/api/chat/messages?groupid={groupId}&page={pageParam}";
var client = new RestClient(url);
var request = new RestRequest();
request.AddHeader(Constants.Token, ChatDaten.AuthToken);
request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer);
client.ExecuteAsync(request, response =>
{
_AdditionalUserMessages = null;
_AdditionalUserMessages = JsonConvert.DeserializeObject<UserMessages>(response.Content);
if(_AdditionalUserMessages.Response.HasMorePages)
{
_NextPage = _AdditionalUserMessages.Response.NextPage;
}
_HasNextPage = _AdditionalUserMessages.Response.HasMorePages;
callback?.Invoke();
});
}
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
// WebRequest
private void LoadMoreMessagesFromServer(long pGroupId, string pPage)
{
try
{
var page = pPage.Split('=');
var endurl = ChatDaten.ServerUrl + "/api/chat/messages?groupid=" + pGroupId + "&page=" + page[1];
var request = WebRequest.Create(endurl);
request.Credentials = CredentialCache.DefaultCredentials;
request.Headers[Constants.Token] = ChatDaten.AuthToken;
request.Headers[Constants.CustomerId] = ChatDaten.Kundennummer;
var response = request.GetResponse();
var responseFromServer = Utils.ReadStream(response);
if (!string.IsNullOrEmpty(responseFromServer))
{
_AdditionalUserMessages = null;
_AdditionalUserMessages = JsonConvert.DeserializeObject<UserMessages>(responseFromServer);
if (_AdditionalUserMessages.Response.HasMorePages)
{
_NextPage = _AdditionalUserMessages.Response.NextPage;
_HasNextPage = true;
}
else
{
_HasNextPage = false;
}
}
response.Close();
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
private double _FormerMessagesCount;
// WebRequest
public bool CheckIfNewMessagesExist(Contact currentContact)
{
var span = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var timespan = Convert.ToInt64(span.TotalSeconds);
if (_UserMessages != null && _UserMessages.Response.Messages.Length > 0)
{
timespan = _UserMessages.Response.Messages.First().Created_At;
}
if (currentContact != null)
{
var currentMessagesCount = GetNumberOfNewMessages(currentContact.GroupId, timespan);
if (currentMessagesCount.Equals(_FormerMessagesCount))
{
return false;
}
_FormerMessagesCount = currentMessagesCount;
return true;
}
return false;
}
// WebRequest
private double GetNumberOfNewMessages(long pGroupId, long pLastTimeStamp)
{
try
{
var url = $"{ChatDaten.ServerUrl}{Constants.LoadOwnChatNewsUrl}{pGroupId}/{pLastTimeStamp}";
var webRequest = WebRequest.Create(url);
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.Headers[Constants.Token] = ChatDaten.AuthToken;
webRequest.Headers[Constants.CustomerId] = ChatDaten.Kundennummer;
var response = webRequest.GetResponse();
var responseFromServer = Utils.ReadStream(response);
var messageCounter = JsonConvert.DeserializeObject<MessageCounter>(responseFromServer);
return messageCounter.MessageCount;
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
return 0;
}
}
// WebRequest
public double GetNumberOfAllNewMessages()
{
var unixTime = DateTime.UtcNow.GetUnixTimeStamp();
var messageCount = 0d;
messageCount += LoadNumberOfNewMessagesFromServer(0);
if (messageCount > 0)
{
LastTimeStamp = unixTime;
}
return messageCount;
}
// WebRequest
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<MessageCounter>(responseFromServer);
return messageCounter.MessageCount;
}
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
return 0;
}
}
// WebRequest: LoadGroups
public IOrderedEnumerable<Contact> NeueGroupklassenKontakte()
{
var contacts = new List<Contact>();
var groupData = LoadGroups();
contacts.AddRange(GenerateContactsFromServerResponse(groupData.Response.Groups.ToArray(), true));
return contacts.OrderByDescending(r => r.TimeStamp);
}
private ChatGruppenDaten LoadGroups()
{
try
{
var url = ChatDaten.ServerUrl + Constants.GetChatGroupsUrl;
var request = WebRequest.Create(url);
request.Credentials = CredentialCache.DefaultCredentials;
request.Headers[Constants.Token] = ChatDaten.AuthToken;
request.Headers[Constants.CustomerId] = ChatDaten.Kundennummer;
var response = request.GetResponse();
var responseFromServer = Utils.ReadStream(response);
var jsonDaten = JsonConvert.DeserializeObject<ChatGruppenDaten>(responseFromServer);
response.Close();
return jsonDaten;
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
return null;
}
}
public void AddNewMessage(string pMessage, long pGroupId)
{
try
{
var username = string.Empty;
var user = ChatDaten.LoggedInUser.Response.User;
if(user != null)
{
username = $"{user.Firstname} {user.Lastname}";
}
var time = DateTime.Now;
Messages.Add(new ChatMessage(username, pMessage, time, true, pGroupId, 0));
AddSeparators();
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
// TODO: Funktioniert nicht mit der Version von RestSharp, die mit .NET Version 4.5 kompatibel ist
public void SendMessageAsync(string message, long groupId)
{
try
{
var url = ChatDaten.ServerUrl + Constants.SendMessageUrl;
var requestBody = $"{HttpUtility.UrlEncode("groupid")}={HttpUtility.UrlEncode(groupId.ToString())}&{HttpUtility.UrlEncode("text")}={HttpUtility.UrlEncode(message)}";
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader(Constants.ContentTypeKey, Constants.MultipartContentTypeValue);
request.AddParameter(Constants.Token, ChatDaten.AuthToken);
request.AddParameter(Constants.CustomerId, ChatDaten.Kundennummer);
request.AddParameter(Constants.MultipartContentTypeValue, requestBody, ParameterType.RequestBody);
client.PostAsync(request, (response, handle) =>
{
});
/*
*
multiPartContent.Add(new StringContent(groupId.ToString()), "groupid");
multiPartContent.Add(new StringContent(message), "text");
//wegen Kontent nachschauen
httpRequest.Content = multiPartContent;
httpRequest.Headers.Add("Token", ChatDaten.AuthToken);
httpRequest.Headers.Add("CustomerID", ChatDaten.Kundennummer);
---------------------------------------------------------------------------------------------------------------------------------------------------
var url = _BaseUrl + Constants.LoginWithChatCodeUrl;
var requestBody = $"{HttpUtility.UrlEncode("username")}={HttpUtility.UrlEncode(_UserName)}&{HttpUtility.UrlEncode("password")}={HttpUtility.UrlEncode(_Password)}&{HttpUtility.UrlEncode("chatcode")}={HttpUtility.UrlEncode(_ChatCode)}";
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader(Constants.ContentTypeKey, Constants.FormUrlEncodedContentTypeValue);
request.AddParameter(Constants.CustomerId, _Tenant, ParameterType.HttpHeader);
request.AddParameter(Constants.FormUrlEncodedContentTypeValue, requestBody, ParameterType.RequestBody);
client.PostAsync(request, (response, handle) =>
{
Debug.WriteLine(response.Content);
var connectionData = JsonConvert.DeserializeObject<UserDaten>(response.Content);
if (connectionData.Success)
{
_AuthToken = connectionData.Response.User.Token;
_UserId = connectionData.Response.User.Oid;
Utils.AuthToken = _AuthToken;
Utils.Tenant = _Tenant;
_LoggedInUser = connectionData;
callback?.Invoke(true);
}
else
{
var errorMessage = string.Empty;
if (connectionData.Error?.ChatCodeFailed != null)
{
errorMessage = $"Fehler: {connectionData.Error.ChatCodeFailed[0]}\nBitte überprüfen Sie die Anmeldeinformationen.";
}
else if (connectionData.Error?.LoginFailed != null)
{
errorMessage = $"Fehler: {connectionData.Error.LoginFailed[0]}\nBitte überprüfen Sie die Anmeldeinformationen.";
}
if (!string.IsNullOrWhiteSpace(errorMessage))
{
exceptionCallback?.Invoke(errorMessage);
}
}
});
*/
}
catch(Exception exception)
{
MessageBox.Show(exception.Message, "Fehler", MessageBoxButton.OK);
}
}
public async void SendMessage(string message, long groupId)
{
try
{
var endurl = ChatDaten.ServerUrl + Constants.SendMessageUrl;
using (var multiPartContent = new MultipartFormDataContent())
{
multiPartContent.Add(new StringContent(groupId.ToString()), "groupid");
multiPartContent.Add(new StringContent(message), "text");
var requestUri = new Uri(endurl);
var httpRequest = new HttpRequestMessage {Method = HttpMethod.Post, RequestUri = requestUri, Content = multiPartContent};
//wegen Kontent nachschauen
httpRequest.Headers.Add("Token", ChatDaten.AuthToken);
httpRequest.Headers.Add("CustomerID", ChatDaten.Kundennummer);
var httpClient = new HttpClient();
await httpClient.SendAsync(httpRequest, CancellationToken.None).ConfigureAwait(false);
}
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
public string OpenFile()
{
try
{
var openFileDialog = new OpenFileDialog
{
Filter = Resource.OpenFileDialogFilter_Test //Resource.OpenFileDialogFilter_DocumentsAndImages
};
var result = openFileDialog.ShowDialog();
return result == DialogResult.OK ? openFileDialog.FileName : null;
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
return null;
}
}
public void AddNewFile(string pFile, string pOriginalFilePath, long pGroupId)
{
try
{
if(string.IsNullOrEmpty(pFile) || string.IsNullOrEmpty(pOriginalFilePath))
{
return;
}
var message = _UserMessages.Response.Messages.Last();
var sendTime = DateTime.Now;
if (Constants.ImageFileExtensions.Contains(Path.GetExtension(pFile).ToUpperInvariant()))
{
byte[] file;
using (Stream reader = File.OpenRead(pFile))
{
file = Utils.ReadFully(reader);
}
var memoryStream = new MemoryStream(file);
var image = Image.FromStream(memoryStream);
using (var bitmap = new Bitmap(image))
{
using (var stream = new MemoryStream())
{
short orient = 0;
const int orientationId = 0x0112;
if (image.PropertyIdList.Contains(orientationId))
{
var item = image.GetPropertyItem(orientationId);
orient = BitConverter.ToInt16(item.Value, 0);
bitmap.SetPropertyItem(item);
}
var flipType = Utils.OrientationToFlipType(orient.ToString());
bitmap.RotateFlip(flipType);
bitmap.Save(stream, ImageFormat.Jpeg);
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(stream.ToArray());
bitmapImage.EndInit();
var filename = Path.GetFileName(pOriginalFilePath).ToLower();
filename = filename.Replace(".bmp", ".jpg");
Messages.Add(new ChatMessage(message.User_Name, filename, sendTime, true, bitmapImage, pFile, filename, pGroupId, file.LongLength));
}
}
memoryStream.Dispose();
memoryStream.Close();
}
else
{
Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFile), sendTime, message.Smaller_Image, true, pFile, pGroupId, 0));
}
AddSeparators();
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
public void AddMediumContextDerNachrichtView(byte[] pFile, string pFileName, long pGroupId)
{
if(string.IsNullOrEmpty(pFileName))
{
return;
}
var message = _UserMessages.Response.Messages.Last();
var sendtime = DateTime.Now;
if (Constants.ImageFileExtensions.Contains(Path.GetExtension(pFileName).ToUpperInvariant()))
{
var bitmapImage = new BitmapImage();
var memoryStream = new MemoryStream(pFile);
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
memoryStream.Close();
ImageSource logo = bitmapImage;
Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFileName), sendtime, true, logo, pFileName, Path.GetFileName(pFileName), pGroupId, memoryStream.Length));
}
else
{
Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFileName), sendtime, message.Smaller_Image, true, pFileName, pGroupId, 0));
}
AddSeparators();
}
public void SendFileToContact(Contact currentContact, string pFile, string pOriginalFilePath)
{
try
{
SendFile(pFile, currentContact, pOriginalFilePath);
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
// WebRequest
private void SendFile(string pFile, Contact currentContact, string pOriginalFilePath)
{
if(string.IsNullOrEmpty(pOriginalFilePath))
{
return;
}
byte[] mediaFile;
using (Stream reader = File.OpenRead(pFile))
{
mediaFile = Utils.ReadFully(reader);
}
var fileName = Path.GetFileName(pOriginalFilePath).ToLower();
if (Constants.ImageFileExtensions.Contains(Path.GetExtension(fileName).ToUpperInvariant())){
fileName = fileName.Replace(".bmp", ".jpg");
SendMediaMessage(fileName, currentContact.GroupId, mediaFile);
}
else
{
SendMediaMessage(fileName, currentContact.GroupId, mediaFile);
}
}
private HttpRequestMessage _HttpRequest;
// WebRequest
private async void SendMediaMessage(string pMessage, long pGroupId, byte[] pMediaFile)
{
try
{
using (var multiPartContent = new MultipartFormDataContent())
{
var requestUri = new Uri(ChatDaten.ServerUrl + Constants.SendMessageUrl);
multiPartContent.Add(new ByteArrayContent(pMediaFile, 0, pMediaFile.Length), "file", pMessage);
multiPartContent.Add(new StringContent(pGroupId.ToString()), "groupid");
_HttpRequest = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = requestUri,
Content = multiPartContent
};
_HttpRequest.Headers.Add(Constants.Token, ChatDaten.AuthToken);
_HttpRequest.Headers.Add(Constants.CustomerId, ChatDaten.Kundennummer);
var httpClient = new HttpClient();
var httpResponse = await httpClient.SendAsync(_HttpRequest, CancellationToken.None).ConfigureAwait(false);
var antwortResponse = await httpResponse.Content.ReadAsStringAsync();
}
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
public ContextMenu ErstelleKontextMenue()
{
var contextMenu = new ContextMenu();
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;
item2.Header = "Einfügen";
item2.Visibility = Visibility.Visible;
item3.Header = "Kopieren";
item3.Visibility = Visibility.Visible;
return contextMenu;
}
public void SaveFileAs(ChatMessage pChatMessage)
{
if (pChatMessage.ImageSources != null)
{
SaveAs(1, Path.GetFileName(pChatMessage.OriginalImage), DownloadMediaFile(pChatMessage.OriginalImage));
}
}
private byte[] DownloadMediaFile(string pFilePath)
{
byte[] mediaFile = null;
try
{
using(var webClient = new WebClient())
{
webClient.Credentials = CredentialCache.DefaultCredentials;
webClient.Headers[Constants.Token] = ChatDaten.AuthToken;
webClient.Headers[Constants.CustomerId] = ChatDaten.Kundennummer;
mediaFile = webClient.DownloadData(pFilePath);
}
return mediaFile;
}
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
return mediaFile;
}
private void SaveAs(int pFilterType, string pFileName, byte[] pMediaFile)
{
try
{
var saveFileDialog = new SaveFileDialog {FileName = Path.GetFileName(pFileName)};
switch(pFilterType)
{
case 1:
saveFileDialog.Filter = Resource.SaveFileDialogFilter_Images;
saveFileDialog.Title = Resource.SaveFIleDialogTitle_Images;
saveFileDialog.ShowDialog();
break;
case 2:
saveFileDialog.Filter = Resource.SaveFileDialogFilter_Documents;
saveFileDialog.Title = Resource.SaveFIleDialogTitle_Documents;
saveFileDialog.ShowDialog();
break;
case 3:
saveFileDialog.Filter = Resource.SaveFileDialogFilter_Audio;
saveFileDialog.Title = Resource.SaveFIleDialogTitle_Audio;
saveFileDialog.ShowDialog();
break;
}
if (!string.IsNullOrEmpty(saveFileDialog.FileName))
{
var fileStream = (FileStream)saveFileDialog.OpenFile();
fileStream.Write(pMediaFile, 0, pMediaFile.Length);
fileStream.Close();
}
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
public void Paste(long pGroupOid, ChatMainControl pChatMainControl)
{
var dataObject = Clipboard.GetDataObject();
if(dataObject == null)
{
return;
}
if (dataObject.GetDataPresent(DataFormats.FileDrop))
{
try
{
if (dataObject.GetData(DataFormats.FileDrop) is string[] fileList)
{
if (File.Exists(fileList[0]))
{
var fileName = Path.GetFileName(fileList[0]);
var mediaFile = File.ReadAllBytes(fileList[0]);
AddMediumContextDerNachrichtView(mediaFile, fileName, pGroupOid);
CollectionViewSource.GetDefaultView(pChatMainControl.ChatListBox.ItemsSource).Refresh();
pChatMainControl.ChatListBox.Items.MoveCurrentToLast();
pChatMainControl.ChatListBox.ScrollIntoView(pChatMainControl.ChatListBox.Items.CurrentItem);
SendMediaMessage(fileName, pGroupOid, mediaFile);
}
}
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
else
{
if (dataObject.GetDataPresent(DataFormats.Text))
{
var text = (string) dataObject.GetData(DataFormats.StringFormat);
AddNewMessage(text, pGroupOid);
CollectionViewSource.GetDefaultView(pChatMainControl.ChatListBox.ItemsSource).Refresh();
pChatMainControl.ChatListBox.Items.MoveCurrentToLast();
pChatMainControl.ChatListBox.ScrollIntoView(pChatMainControl.ChatListBox.Items.CurrentItem);
SendMessage(text, pGroupOid);
}
else if (dataObject.GetDataPresent(DataFormats.Bitmap))
{
var bitmap = (Bitmap) dataObject.GetData(DataFormats.Bitmap);
var imageName = Utils.GenerateTempName() + ".jpg";
System.Drawing.Image image = bitmap;
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, Utils.ImageToByteArray(image));
}
else
{
MessageBox.Show("Der Zwischen-Speicher kann nicht verarbeitet werden.", "Fehler", MessageBoxButton.OK);
}
}
}
public void Copy(object pData, int pDataType)
{
switch(pDataType)
{
case 1:
Clipboard.SetData(DataFormats.Text, pData);
break;
case 2:
Clipboard.SetData(DataFormats.Bitmap, pData);
break;
case 3:
Clipboard.SetData(DataFormats.FileDrop, pData);
break;
}
}
public void ShowProfilePicture(Contact currentContact)
{
try
{
using (var form = new Form())
{
var bitmap = currentContact.ProfilePicture;
form.StartPosition = FormStartPosition.CenterScreen;
var bitmapWidth = bitmap.Width;
var bitmapHeight = bitmap.Height;
var aspectRatio = bitmapWidth / (double) bitmapHeight;
var primaryScreenWidth = SystemParameters.PrimaryScreenWidth;
var primaryScreenHeight = SystemParameters.PrimaryScreenHeight;
var maxWidth = bitmapWidth;
var maxHeight = bitmapHeight;
if(maxWidth > primaryScreenWidth || maxHeight > primaryScreenHeight)
{
if(primaryScreenWidth > primaryScreenHeight)
{
maxHeight = (int) (.9 * primaryScreenHeight);
maxWidth = (int) (maxHeight * aspectRatio);
}
else
{
maxWidth = (int) (.9 * primaryScreenWidth);
maxHeight = (int) (maxWidth * aspectRatio);
}
}
var maximumSize = new Size(maxWidth, maxHeight);
form.Size = maximumSize;
form.FormBorderStyle = FormBorderStyle.Sizable;
form.MaximizeBox = false;
form.Text = currentContact.Name;
form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
var pictureBox = new PictureBox
{
Dock = DockStyle.Fill,
Image = bitmap,
SizeMode = PictureBoxSizeMode.Zoom,
Padding = new Padding(0),
Margin = new Padding(0)
};
form.MinimumSize = new Size(232, (int)(232 / aspectRatio));
form.Padding = new Padding(0);
form.Margin = new Padding(0);
form.Controls.Add(pictureBox);
form.ShowDialog();
}
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
public void ShowPicture(string originalImage, Action downloadCompletedCallback)
{
try
{
var webClient = new WebClient();
webClient.DownloadDataCompleted += (s, e) =>
{
try
{
using(var form = new Form())
{
using(var ms = new MemoryStream(e.Result))
{
var image = Image.FromStream(ms);
using(var bitmap = new Bitmap(image))
{
short orient = 0;
const int orientationId = 0x0112;
if(image.PropertyIdList.Contains(orientationId))
{
var item = image.GetPropertyItem(orientationId);
orient = BitConverter.ToInt16(item.Value, 0);
bitmap.SetPropertyItem(item);
}
var flipType = Utils.OrientationToFlipType(orient.ToString());
bitmap.RotateFlip(flipType);
form.StartPosition = FormStartPosition.CenterScreen;
form.ClientSize = bitmap.Size;
form.FormBorderStyle = FormBorderStyle.Sizable;
form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
using(var pictureBox = new PictureBox())
{
pictureBox.Dock = DockStyle.Fill;
pictureBox.Image = bitmap;
pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
form.Controls.Add(pictureBox);
downloadCompletedCallback?.Invoke();
form.ShowDialog();
}
}
}
}
}
catch(Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
};
webClient.DownloadDataAsync(new Uri(originalImage));
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
}
}
public void ReloadGroupsAsync(Action<ChatGruppenDaten> callback)
{
var url = ChatDaten.ServerUrl + Constants.GetChatGroupsUrl;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient(url);
var request = new RestRequest();
request.AddHeader(Constants.Token, ChatDaten.AuthToken);
request.AddHeader(Constants.CustomerId, ChatDaten.Kundennummer);
client.ExecuteAsync(request, response =>
{
var groups = JsonConvert.DeserializeObject<ChatGruppenDaten>(response.Content);
callback?.Invoke(groups);
});
}
public List<Contact> GroupklassenAktuallisieren(ChatGruppenDaten chatDaten)
{
try
{
_Contacts.Clear();
_Contacts.AddRange(GenerateContactsFromServerResponse(chatDaten.Response.Groups.ToArray()));
return _Contacts;
}
catch (Exception exception)
{
ExceptionCallback?.Invoke(exception);
return null;
}
}
public List<Contact> GenerateContactsFromServerResponse(GroupInput[] pGroupInputs, bool pShouldUpdateLastTimeStamp = false)
{
var contacts = new List<Contact>();
foreach(var groupInput in pGroupInputs)
{
var formattedTime = new DateTime();
var latestMessage = groupInput.LastMessage;
if(latestMessage?.Text != null)
{
var timeStamp = DateTime.Parse(latestMessage.Timestamp.Date);
var clientZone = TimeZoneInfo.Local;
formattedTime = TimeZoneInfo.ConvertTimeFromUtc(timeStamp, clientZone);
}
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);
var profilePicture = Utils.ConvertAvatarToBitmap(groupInput.Avatar, groupInput.OnlyEmployees, groupInput.Users.Length > 2);
contacts.Add(new Contact(groupInput.Name, groupInput.LastMessage, formattedTime, groupInput.Oid, userIdManage, groupInput.OnlyEmployees, groupInput.Users.Length, groupInput.CanWrite, groupInput.AccentColor, profilePicture, avatar));
if(pShouldUpdateLastTimeStamp)
{
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()) ? //SmallerImage ist null
new ChatMessage(message.User_Name, messageText, formattedTime, isLoggedInUsersMessage, DownloadImage(message.Smaller_Image), message.File, message.Original_Filename, message.GroupId, message.FileSize) :
new ChatMessage(message.User_Name, messageText, formattedTime, message.Smaller_Image, isLoggedInUsersMessage, message.File, message.GroupId, message.FileSize));
}
else
{
Messages.Add(new ChatMessage(message.User_Name, message.Text, formattedTime, isLoggedInUsersMessage, message.GroupId, message.FileSize));
}
}
AddSeparators();
}
private void AddSeparators()
{
var messagesWithoutSeparators = Messages.Where(message => !message.IsSeparator).OrderBy(message => message.SendTime).ToList();
var separators = new List<ChatMessage>();
var previousMessage = messagesWithoutSeparators.OrderBy(message => message.SendTime).FirstOrDefault();
foreach(var message in messagesWithoutSeparators.OrderBy(message => message.SendTime))
{
if(!message.Equals(previousMessage) && previousMessage != null)
{
if(message.SendTime.Date != previousMessage.SendTime.Date)
{
var separatorMessage = new ChatMessage(null, null, message.SendTime.Date, false, 0, 0) { IsSeparator = true };
separators.Add(separatorMessage);
previousMessage = message;
}
}
}
messagesWithoutSeparators.AddRange(separators);
Messages = messagesWithoutSeparators.OrderBy(message => message.SendTime).ToList();
}
}
}