1308 lines
47 KiB
C#
1308 lines
47 KiB
C#
using ChatController.ChatKlassen;
|
|
using Newtonsoft.Json;
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.Drawing;
|
|
using System.Drawing.Drawing2D;
|
|
using System.Drawing.Imaging;
|
|
using System.IO;
|
|
using System.Linq;
|
|
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 Application = System.Windows.Forms.Application;
|
|
using Clipboard = System.Windows.Forms.Clipboard;
|
|
using Color = System.Drawing.Color;
|
|
using ContextMenu = System.Windows.Controls.ContextMenu;
|
|
using DataFormats = System.Windows.Forms.DataFormats;
|
|
using Image = System.Windows.Controls.Image;
|
|
using MessageBox = System.Windows.MessageBox;
|
|
using Size = System.Drawing.Size;
|
|
|
|
namespace ChatController.HauptKlassen
|
|
{
|
|
public class Chat
|
|
{
|
|
private readonly List<Contact> _Contacts = new List<Contact>();
|
|
public List<ChatMessage> Messages { get; } = 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)
|
|
{
|
|
ChatDaten = chatDaten;
|
|
}
|
|
|
|
public IOrderedEnumerable<Contact> 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<ChatMessage> LoadChatMessagesForContact(CurrentContact pContact)
|
|
{
|
|
if (pContact != null)
|
|
{
|
|
LoadMessagesFromServer(pContact.GroupId);
|
|
Messages.Clear();
|
|
|
|
AddMessagesFromServerResponse(_UserMessages.Response.Messages);
|
|
}
|
|
|
|
return Messages.OrderBy(r => r.SendTime);
|
|
}
|
|
|
|
private static 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)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
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))
|
|
{
|
|
_UserMessages = JsonConvert.DeserializeObject<UserMessages>(serverResponse);
|
|
|
|
if (_UserMessages.Response.HasMorePages)
|
|
{
|
|
_NextPage = _UserMessages.Response.NextPage;
|
|
_HasNextPage = true;
|
|
}
|
|
else
|
|
{
|
|
_HasNextPage = false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
|
|
}
|
|
}
|
|
|
|
public IOrderedEnumerable<ChatMessage> LoadMoreMessages(Contact pContact)
|
|
{
|
|
if (_HasNextPage)
|
|
{
|
|
LoadMoreMessagesFromServer(pContact.GroupId, _NextPage);
|
|
|
|
AddMessagesFromServerResponse(_AdditionalUserMessages.Response.Messages);
|
|
}
|
|
|
|
return Messages.OrderBy(r => r.SendTime);
|
|
}
|
|
|
|
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 e)
|
|
{
|
|
MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
|
|
}
|
|
}
|
|
|
|
private double _FormerMessagesCount;
|
|
|
|
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);
|
|
|
|
if (_UserMessages != null && _UserMessages.Response.Messages.Length > 0)
|
|
{
|
|
timespan = _UserMessages.Response.Messages.First().Created_At;
|
|
}
|
|
|
|
if (pCurrentContact != null)
|
|
{
|
|
var currentMessagesCount = GetNumberOfNewMessages(pCurrentContact.GroupId, timespan);
|
|
|
|
if (currentMessagesCount.Equals(_FormerMessagesCount))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_FormerMessagesCount = currentMessagesCount;
|
|
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
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)
|
|
{
|
|
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<MessageCounter>(responseFromServer);
|
|
|
|
return messageCounter.MessageCount;
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
public IOrderedEnumerable<Contact> NeueGroupklassenKontakte()
|
|
{
|
|
var contacts = new List<Contact>();
|
|
|
|
var groupData = LoadGroups();
|
|
|
|
foreach (var contact in groupData.Response)
|
|
{
|
|
contacts.AddRange(GenerateContactsFromServerResponse(contact.Value, 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 e)
|
|
{
|
|
MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public void AddNewMessage(string pMessage, long pGroupId)
|
|
{
|
|
try
|
|
{
|
|
var username = "";
|
|
|
|
var user = ChatDaten.AngemeldeterUser.Response.Values.FirstOrDefault();
|
|
if(user != null)
|
|
{
|
|
username = $"{user.Firstname} {user.Lastname}";
|
|
}
|
|
|
|
var time = DateTime.Now;
|
|
|
|
Messages.Add(new ChatMessage(username, pMessage, time, true, pGroupId));
|
|
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
MessageBox.Show(e.Message, "Fehler", MessageBoxButton.OK);
|
|
}
|
|
}
|
|
|
|
public async void SendMessage(string message, long groupId)
|
|
{
|
|
try
|
|
{
|
|
var endurl = ChatDaten.ServerUrl + "/api/chat/messages/send";
|
|
|
|
Dictionary<string, string> postparameter = new Dictionary<string, string>();
|
|
|
|
postparameter.Add("groupid", groupId + "");
|
|
postparameter.Add("text", message);
|
|
|
|
using (MultipartFormDataContent multiPartContent = new MultipartFormDataContent())
|
|
{
|
|
multiPartContent.Add(new StringContent(groupId + ""), "groupid");
|
|
multiPartContent.Add(new StringContent(message), "text");
|
|
|
|
Uri requestUri = new Uri(endurl);
|
|
|
|
HttpRequestMessage httpRequest = new HttpRequestMessage();
|
|
httpRequest.Method = HttpMethod.Post;
|
|
httpRequest.RequestUri = requestUri;
|
|
|
|
//wegen Kontent nachschauen
|
|
httpRequest.Content = multiPartContent;
|
|
|
|
httpRequest.Headers.Add("Token", ChatDaten.AuthToken);
|
|
httpRequest.Headers.Add("CustomerID", ChatDaten.Kundennummer);
|
|
|
|
|
|
HttpResponseMessage httpResponse = null;
|
|
|
|
HttpClient httpClient = new HttpClient();
|
|
//httpClient.Timeout = TimeSpan.FromSeconds(300);
|
|
httpResponse = await httpClient.SendAsync(httpRequest, CancellationToken.None).ConfigureAwait(false);
|
|
|
|
//string antwortResponse = await httpResponse.Content.ReadAsStringAsync();
|
|
|
|
}
|
|
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
MessageBox.Show("Fehler: " + e.Message,"Fehler",MessageBoxButton.OK);
|
|
}
|
|
}
|
|
|
|
public string OpenFile()
|
|
{
|
|
try
|
|
{
|
|
var openFileDialog = new OpenFileDialog {Filter = Resource.OpenFileDialogFilter_DocumentsAndImages};
|
|
|
|
var result = openFileDialog.ShowDialog();
|
|
|
|
return result == DialogResult.OK ? openFileDialog.FileName : null;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
|
|
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 = System.Drawing.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));
|
|
}
|
|
}
|
|
|
|
memoryStream.Dispose();
|
|
memoryStream.Close();
|
|
}
|
|
else
|
|
{
|
|
Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFile), sendTime, message.Smaller_Image, true, pFile, pGroupId));
|
|
}
|
|
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
|
|
}
|
|
}
|
|
|
|
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));
|
|
}
|
|
else
|
|
{
|
|
Messages.Add(new ChatMessage(message.User_Name, Path.GetFileName(pFileName), sendtime, message.Smaller_Image, true, pFileName, pGroupId));
|
|
}
|
|
}
|
|
|
|
public void SendFileToContact(CurrentContact pCurrentContact, string pFile, string pOriginalFilePath)
|
|
{
|
|
try
|
|
{
|
|
SendFile(pFile, pCurrentContact, pOriginalFilePath);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
|
|
}
|
|
}
|
|
|
|
private void SendFile(string pFile, CurrentContact pContact, 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, pContact.GroupId, mediaFile);
|
|
}
|
|
else
|
|
{
|
|
SendMediaMessage(fileName, pContact.GroupId, mediaFile);
|
|
}
|
|
}
|
|
|
|
public string ScaleImage(string pFile, string pFormat)
|
|
{
|
|
try
|
|
{
|
|
byte[] mediaFile;
|
|
using (Stream reader = File.OpenRead(pFile))
|
|
{
|
|
mediaFile = Utils.ReadFully(reader);
|
|
}
|
|
|
|
var memoryStream = new MemoryStream(mediaFile);
|
|
var image = System.Drawing.Image.FromStream(memoryStream);
|
|
|
|
float width, height;
|
|
|
|
if (image.Height < image.Width )
|
|
{
|
|
if (image.Height > 1080)
|
|
{
|
|
var factor = (float)image.Height / 1080;
|
|
|
|
height = 1080;
|
|
|
|
width = image.Width / factor;
|
|
}
|
|
else
|
|
{
|
|
return pFile;
|
|
}
|
|
}
|
|
else if(image.Height < 1080 && image.Width < 1080 )
|
|
{
|
|
return pFile;
|
|
}
|
|
else
|
|
{
|
|
if (image.Width > 1080)
|
|
{
|
|
var factor = (float)image.Width / 1080;
|
|
|
|
width = 1080;
|
|
|
|
height = image.Height / factor;
|
|
}
|
|
else
|
|
{
|
|
return pFile;
|
|
}
|
|
}
|
|
|
|
var scaledBitmap = new Bitmap(image, new Size((int) width, (int) height));
|
|
|
|
const int orientationId = 0x0112;
|
|
|
|
if (image.PropertyIdList.Contains(orientationId)) {
|
|
var item = image.GetPropertyItem(orientationId);
|
|
|
|
scaledBitmap.SetPropertyItem(item);
|
|
}
|
|
|
|
using (var graphics = Graphics.FromImage(image))
|
|
{
|
|
graphics.Clear(Color.Transparent);
|
|
|
|
graphics.InterpolationMode = InterpolationMode.Low;
|
|
|
|
graphics.DrawImage(scaledBitmap, (int) width, (int) height);
|
|
}
|
|
|
|
var imageConverter = new ImageConverter();
|
|
|
|
var imageData = (byte[])imageConverter.ConvertTo(scaledBitmap, typeof(byte[]));
|
|
|
|
var filePath = Path.GetTempPath() + Guid.NewGuid() + pFormat;
|
|
|
|
if (pFormat.Equals(".JPG") || pFormat.Equals(".JPE") || pFormat.Equals(".JPEG") || pFormat.Equals(".BMP"))
|
|
{
|
|
scaledBitmap.Save(filePath, ImageFormat.Jpeg);
|
|
}
|
|
else if (pFormat.Equals(".PNG"))
|
|
{
|
|
scaledBitmap.Save(filePath, ImageFormat.Png);
|
|
}
|
|
else if (pFormat.Equals(".GIF"))
|
|
{
|
|
scaledBitmap.Save(filePath, ImageFormat.Gif);
|
|
}
|
|
|
|
if (File.Exists(filePath))
|
|
{
|
|
var fileInfo = new FileInfo(filePath);
|
|
var fileInfoLength = fileInfo.Length;
|
|
|
|
if (ChatDaten.MaxUploadSize < fileInfoLength)
|
|
{
|
|
File.Delete(filePath);
|
|
return string.Empty;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
return string.Empty;
|
|
}
|
|
|
|
memoryStream.Dispose();
|
|
memoryStream.Close();
|
|
|
|
return filePath;
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
return pFile;
|
|
}
|
|
}
|
|
|
|
private HttpRequestMessage _HttpRequest;
|
|
|
|
private async void SendMediaMessage(string pMessage, long pGroupId, byte[] pMediaFile)
|
|
{
|
|
try
|
|
{
|
|
using (var multiPartContent = new MultipartFormDataContent())
|
|
{
|
|
var requestUri = new Uri(ChatDaten.ServerUrl + "/api/chat/messages/send");
|
|
|
|
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 e)
|
|
{
|
|
MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
|
|
}
|
|
}
|
|
|
|
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 static byte[] DownloadMediaFile(string pFilePath)
|
|
{
|
|
byte[] mediaFile = null;
|
|
|
|
try
|
|
{
|
|
using(var webClient = new WebClient())
|
|
{
|
|
mediaFile = webClient.DownloadData(pFilePath);
|
|
}
|
|
|
|
return mediaFile;
|
|
}
|
|
catch(Exception e)
|
|
{
|
|
MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
|
|
}
|
|
|
|
return mediaFile;
|
|
}
|
|
|
|
private static 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 e)
|
|
{
|
|
MessageBox.Show("Fehler: "+e.Message,"Fehler",MessageBoxButton.OK);
|
|
}
|
|
}
|
|
|
|
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 e)
|
|
{
|
|
MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK);
|
|
}
|
|
}
|
|
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(CurrentContact pCurrentContact)
|
|
{
|
|
try
|
|
{
|
|
using (var form = new Form())
|
|
{
|
|
var image = new Image {Source = pCurrentContact.Image};
|
|
|
|
var encoder = new BmpBitmapEncoder();
|
|
var memoryStream = new MemoryStream();
|
|
|
|
encoder.Frames.Add(BitmapFrame.Create((BitmapSource) image.Source));
|
|
encoder.Save(memoryStream);
|
|
|
|
var imageFromStream = System.Drawing.Image.FromStream(memoryStream);
|
|
|
|
var bitmap = new Bitmap(imageFromStream);
|
|
|
|
form.StartPosition = FormStartPosition.CenterScreen;
|
|
form.Size = bitmap.Size;
|
|
form.Height += 60;
|
|
form.MinimumSize = new Size(150,150);
|
|
|
|
var width = (int) Math.Round(SystemParameters.PrimaryScreenWidth / 1.25);
|
|
var height = (int) Math.Round(SystemParameters.PrimaryScreenWidth / 2);
|
|
|
|
form.MaximumSize = new Size(width,height);
|
|
form.FormBorderStyle = FormBorderStyle.Sizable;
|
|
|
|
form.MaximizeBox = false;
|
|
|
|
form.Text = "ownChat";
|
|
form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
|
|
|
|
var pictureBox = new PictureBox
|
|
{
|
|
Dock = DockStyle.Fill,
|
|
Image = bitmap,
|
|
SizeMode = PictureBoxSizeMode.CenterImage,
|
|
MaximumSize = new Size(500, 500)
|
|
};
|
|
|
|
form.Controls.Add(pictureBox);
|
|
form.ShowDialog();
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
MessageBox.Show("Fehler: " + e.Message, "Fehler" , MessageBoxButton.OK);
|
|
}
|
|
}
|
|
|
|
public void ShowPicture(ChatMessage curItem, 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 = System.Drawing.Image.FromStream(ms);
|
|
|
|
|
|
using (var bitmap = new Bitmap(image))
|
|
{
|
|
short orient = 0;
|
|
const int orientationId = 0x0112;
|
|
|
|
if (image.PropertyIdList.Contains(orientationId))
|
|
{
|
|
var item = image.GetPropertyItem(orientationId);
|
|
|
|
orient = BitConverter.ToInt16(item.Value, 0);
|
|
|
|
bitmap.SetPropertyItem(item);
|
|
}
|
|
|
|
var flipType = Utils.OrientationToFlipType(orient.ToString());
|
|
|
|
bitmap.RotateFlip(flipType);
|
|
|
|
form.StartPosition = FormStartPosition.CenterScreen;
|
|
form.ClientSize = bitmap.Size;
|
|
form.FormBorderStyle = FormBorderStyle.Sizable;
|
|
form.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
|
|
|
|
using (var pictureBox = new PictureBox())
|
|
{
|
|
pictureBox.Dock = DockStyle.Fill;
|
|
pictureBox.Image = bitmap;
|
|
|
|
pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
|
|
|
|
form.Controls.Add(pictureBox);
|
|
|
|
downloadCompletedCallback?.Invoke();
|
|
|
|
form.ShowDialog();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (Exception edf)
|
|
{
|
|
MessageBox.Show("Fehler: " + edf.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
|
|
}
|
|
|
|
};
|
|
|
|
webClient.DownloadDataAsync(new Uri(curItem.OriginalImage));
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
MessageBox.Show("Fehler: " + e.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
|
|
}
|
|
}
|
|
|
|
public bool DoSynchronisation(string pApiKey, string pCustomerId)
|
|
{
|
|
try
|
|
{
|
|
var endurl = ChatDaten.ServerUrl + "/api/ownchat/sync/schedule/"+pApiKey+"/" +pCustomerId;
|
|
|
|
var request = WebRequest.Create(endurl);
|
|
|
|
request.Credentials = CredentialCache.DefaultCredentials;
|
|
request.Proxy = null;
|
|
|
|
var response = request.GetResponse();
|
|
|
|
var serverResponse = Utils.ReadStream(response);
|
|
|
|
var definiti = new { result = "" };
|
|
|
|
var jsonDatentyp = JsonConvert.DeserializeAnonymousType(serverResponse, definiti);
|
|
|
|
switch (jsonDatentyp.result)
|
|
{
|
|
case "0":
|
|
return true;
|
|
case "11":
|
|
MessageBox.Show("Kundennummer unbekannt.\nDer Chat wird jetzt geschlossen", "Fehler", MessageBoxButton.OK);
|
|
return false;
|
|
case "12":
|
|
MessageBox.Show("Der API-Key ist falsch -> Auth-Error.\nDer Chat wird jetzt geschlossen", "Fehler", MessageBoxButton.OK);
|
|
return false;
|
|
case "13":
|
|
MessageBox.Show("Es existiert kein API-Key für die angegebene Kundennummer.\nDer Chat wird jetzt geschlossen", "Fehler", MessageBoxButton.OK);
|
|
return false;
|
|
case "x":
|
|
MessageBox.Show("MySQL Error.\nDer Chat wird jetzt geschlossen", "Fehler",MessageBoxButton.OK);
|
|
return false;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
MessageBox.Show("Die Verbindung konnte nicht aufgebaut werden.", "Fehler ", MessageBoxButton.OK);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public long GetMaiximumAllowedFileUploadSize(string pToken, string pCustomerId)
|
|
{
|
|
try
|
|
{
|
|
var endurl = ChatDaten.ServerUrl + "/api/ownchat/uploadmaxsize";
|
|
|
|
var request = WebRequest.Create(endurl);
|
|
request.Headers[Constants.Token] = pToken;
|
|
request.Headers[Constants.CustomerId] = pCustomerId;
|
|
|
|
request.Credentials = CredentialCache.DefaultCredentials;
|
|
request.Proxy = null;
|
|
|
|
var response = request.GetResponse();
|
|
|
|
var responseFromServer = Utils.ReadStream(response);
|
|
|
|
var definiti = new { file_upload_max_size = "" };
|
|
|
|
var jsonDatentyp = JsonConvert.DeserializeAnonymousType(responseFromServer, definiti);
|
|
|
|
return Convert.ToInt64(jsonDatentyp.file_upload_max_size);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public ChatGruppenDaten UpdateGroups()
|
|
{
|
|
try
|
|
{
|
|
var endurl = ChatDaten.ServerUrl + Constants.GetChatGroupsUrl;
|
|
|
|
var request = WebRequest.Create(endurl);
|
|
|
|
request.Credentials = CredentialCache.DefaultCredentials;
|
|
request.Headers[Constants.Token] = ChatDaten.AuthToken;
|
|
request.Headers[Constants.CustomerId] = ChatDaten.Kundennummer;
|
|
|
|
var response = request.GetResponse();
|
|
|
|
var serverResponse = Utils.ReadStream(response);
|
|
|
|
response.Close();
|
|
|
|
return !string.IsNullOrEmpty(serverResponse) ? JsonConvert.DeserializeObject<ChatGruppenDaten>(serverResponse) : null;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
MessageBox.Show("Beim Aktualisieren der Kontaktliste ist ein Fehler aufgetreten.\nFehler:\n"+e.Message, "Fehler", MessageBoxButton.OK);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public IOrderedEnumerable<Contact> GroupklassenAktuallisieren(ChatGruppenDaten chatDaten)
|
|
{
|
|
try
|
|
{
|
|
_Contacts.Clear();
|
|
foreach (var contact in chatDaten.Response)
|
|
{
|
|
_Contacts.AddRange(GenerateContactsFromServerResponse(contact.Value));
|
|
}
|
|
|
|
return _Contacts.OrderByDescending(r => r.TimeStamp);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
MessageBox.Show("Beim Sortieren der aktualisierten Kontakte ist ein Fehler aufgetreten.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public Dictionary<int, DateTime> CheckTimeStampsAtStart(List<Contact> pContacts)
|
|
{
|
|
try
|
|
{
|
|
if (File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName)))
|
|
{
|
|
var syncData = new Dictionary<string, string>();
|
|
|
|
using (var streamReader = new StreamReader(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName), true))
|
|
{
|
|
string line;
|
|
|
|
while ((line = streamReader.ReadLine()) != null)
|
|
{
|
|
var encodedTextBytes = Convert.FromBase64String(line);
|
|
|
|
var plainText = Encoding.UTF8.GetString(encodedTextBytes);
|
|
|
|
var splitPlainText = plainText.Split(';');
|
|
|
|
syncData.Add(splitPlainText[0], splitPlainText[1]);
|
|
}
|
|
}
|
|
|
|
var result = new Dictionary<int, DateTime>();
|
|
|
|
foreach (var contact in pContacts)
|
|
{
|
|
foreach (var data in syncData)
|
|
{
|
|
var groupoid = int.Parse(data.Key);
|
|
|
|
if (contact.GroupId == groupoid)
|
|
{
|
|
var datetime = DateTime.Parse(data.Value);
|
|
|
|
if (contact.TimeStamp.Equals(datetime))
|
|
{
|
|
result.Add(groupoid, datetime);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return result.Count > 0 ? result : null;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public void SaveTimeStampsToFile(List<Contact> pContacts)
|
|
{
|
|
try
|
|
{
|
|
if(File.Exists(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName)))
|
|
{
|
|
File.SetAttributes(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName), FileAttributes.Normal);
|
|
File.Delete(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName));
|
|
}
|
|
|
|
using (var streamWriter = new StreamWriter(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName)))
|
|
{
|
|
Encoding enc = new UTF8Encoding();
|
|
|
|
foreach (var contact in pContacts)
|
|
{
|
|
var text = contact.GroupId + ";" + contact.TimeStamp+";";
|
|
var bytes = enc.GetBytes(text);
|
|
var base64String = Convert.ToBase64String(bytes);
|
|
|
|
streamWriter.WriteLine(base64String);
|
|
}
|
|
|
|
File.SetAttributes(Path.Combine(Utils.GetAndCreateUserAppDataPath(), Resource.SyncFileName), FileAttributes.ReadOnly);
|
|
}
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
|
|
}
|
|
}
|
|
|
|
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);
|
|
|
|
contacts.Add(new Contact(groupInput.Name, avatar, groupInput.LastMessage, 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()) ? //SmallerImage ist null
|
|
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
|
|
{
|
|
Messages.Add(new ChatMessage(message.User_Name, message.Text, formattedTime, isLoggedInUsersMessage, message.GroupId));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|