Removed Old Models, extended ChatMessage to json

This commit is contained in:
Patrick Hellebrand
2021-09-22 14:09:26 +02:00
parent f2202e6aa7
commit 0c5579198f
12 changed files with 20 additions and 393 deletions

View File

@@ -2,6 +2,7 @@
using System.Diagnostics;
using Newtonsoft.Json.Linq;
using System.Net;
using PolyChat.Models;
namespace PolyChat
{

View File

@@ -99,10 +99,10 @@
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden">
<ListView x:Name="listViewMessages" VerticalAlignment="Bottom" Margin="4 16">
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Message">
<DataTemplate x:DataType="models:ChatMessage">
<StackPanel x:Name="Message" Margin="0 4" Padding="16 8" CornerRadius="4" Background="{ThemeResource SystemAccentColor}">
<TextBlock Text="{x:Bind Msg}"/>
<TextBlock Text="{x:Bind Timestamp.ToShortDateString()}"/>
<TextBlock Text="{x:Bind Content}"/>
<TextBlock Text="{x:Bind TimeStamp.ToShortDateString()}"/>
<TextBlock Text="{x:Bind Foreign}"/>
</StackPanel>
</DataTemplate>

View File

@@ -50,7 +50,7 @@ namespace PolyChat
public void OnSendMessage(object sender = null, RoutedEventArgs e = null)
{
selectedPartner.AddMessage(new Message(inputSend.Text,false));
selectedPartner.AddMessage(new ChatMessage(username, "message" , inputSend.Text));
Controller.SendMessage(selectedPartner.Code, inputSend.Text);
// clear input
inputSend.Text = "";
@@ -100,14 +100,10 @@ namespace PolyChat
/// Adds an message to the UI, based on .sender if known
/// </summary>
/// <param name="message">ChatMessage</param>
public void OnIncomingMessage(Message message)
public void OnIncomingMessage(string origin, string json)
{
ChatPartner sendingPartner = Partners.First(p => p.Code == message.Ip);
sendingPartner.AddMessage(new Message(
message.Msg,
true,
message.Sender
));
ChatPartner sendingPartner = Partners.First(p => p.Code == origin);
sendingPartner.AddMessage(new ChatMessage(origin, json));
}
private void OnDeleteChat(object sender = null, RoutedEventArgs e = null)

View File

@@ -6,20 +6,18 @@ namespace PolyChat.Models
{
public class ChatMessage
{
private string Origin;
private string Type;
private string Content;
private DateTime TimeStamp;
public string Origin;
public string Type;
public string Content;
public DateTime TimeStamp;
public readonly bool Foreign;
//
public readonly string Ip;
public ChatMessage(string content = "", string origin = "Unknown", string ip = "127.0.0.1")
public ChatMessage(string origin, string type, string content)
{
Origin = origin;
TimeStamp = DateTime.Now;
Type = type;
Content = content;
Ip = ip;
// no json = my messages
Foreign = false;
Debug.WriteLine("Created Message: " + ToString());

View File

@@ -7,20 +7,20 @@ namespace PolyChat.Models
{
public string Name;
public string Code;
public ObservableCollection<Message> Messages;
public ObservableCollection<ChatMessage> Messages;
private SocketIOSocket socketIOSocket;
public ChatPartner(string name, string code, ObservableCollection<Message> messages = null)
public ChatPartner(string name, string code, ObservableCollection<ChatMessage> messages = null)
{
Name = name;
Code = code;
if (messages == null) Messages = new ObservableCollection<Message>();
if (messages == null) Messages = new ObservableCollection<ChatMessage>();
else Messages = messages;
}
public SocketIOSocket SocketIOSocket { get => socketIOSocket; set => socketIOSocket = value; }
public void AddMessage(Message message)
public void AddMessage(ChatMessage message)
{
Messages.Add(message);
}

View File

@@ -1,144 +0,0 @@
using System;
using SocketIOSharp.Common;
using SocketIOSharp.Client;
using SocketIOSharp.Server.Client;
using Json.Net;
using System.Threading;
using PolyChat.Models.Exceptions;
using System.Diagnostics;
namespace PolyChat.Models
{
class Client
{
private SocketIOClient connection_client = null;
private SocketIOSocket connection_server = null;
private Boolean connected = true;
private String ipSelf;
public Client(SocketIOClient connection, String ip, MainPage uiController)
{
this.ipSelf = ip;
this.connection_client = connection;
InitEventHandlers(this, connection, uiController);
}
public Client(SocketIOSocket connection, String ip, MainPage uiController)
{
this.ipSelf = ip;
this.connection_server = connection;
InitEventHandlers(this, connection, uiController);
}
//Sending
//===================================================================================
/// <summary>
/// converts String message into json file and sends it to the server.
/// </summary>
/// <remarks>
/// gets called by gui if someone wants to send Message
/// </remarks>
/// <param name="sender">Sender of Message</param>
/// <param name="chatMessage">the accual text the user wants to send</param>
/// <param name="timestamp">current time</param>
public void sendMessage(SendCode code, String chatMessage)
{
new Thread(() =>
{
Debug.WriteLine($"connected is {connected}");
//create msg
Message msg = new Message(chatMessage, false, ipSelf);
//convert msg
String petJson = JsonNet.Serialize(msg);
//wait if not connected and send msg
int i=0;
int sleeptimer = 2000;
while(!this.connected)
{
Thread.Sleep(sleeptimer);
i++;
if(i>=10)
{
throw new MessageTimedOutException(i*sleeptimer);
}
}
if (connection_client != null)
{
connection_client.Emit(code.ToString(), petJson);
}else if (connection_server != null)
{
connection_server.Emit(code.ToString(), petJson);
}
}).Start();
}
//==================================================================================
//EventHandeling
//===================================================================================
/// <summary>
/// handles all events of client
/// </summary>
/// <param name="client">self</param>
/// <param name="connection"></param>
private static void InitEventHandlers(Client client, SocketIOClient connection, MainPage uiController)
{
connection.On(SendCode.Message.ToString(), (Data) =>
{
Message msg = new Message(Data[0]);
uiController.OnIncomingMessage(msg);
//TODO: send message to GUI
});
connection.On(SendCode.Command.ToString(), (Data) =>
{
Console.WriteLine("Command recieved!" + Data[0]);
});
connection.On(SocketIOEvent.CONNECTION, () =>
{
client.connected = true;
});
}
/// <summary>
/// handles all events of server
/// </summary>
/// <param name="client">self</param>
/// <param name="connection"></param>
private static void InitEventHandlers(Client client, SocketIOSocket connection, MainPage uiController)
{
connection.On(SendCode.Message.ToString(), (Data) =>
{
Message msg = new Message(Data[0]);
uiController.OnIncomingMessage(msg);
//TODO: send message to GUI
});
connection.On(SendCode.Command.ToString(), (Data) =>
{
Console.WriteLine("Command recieved!" + Data[0]);
});
client.connected = true;
}
//==================================================================================
//Getter and Setter
//==================================================================================
public String getIP()
{
return this.ipSelf;
}
public Boolean isConnected()
{
return this.connected;
}
}
}

View File

@@ -7,7 +7,7 @@ using SocketIOSharp.Common;
using SocketIOSharp.Server;
using SocketIOSharp.Server.Client;
namespace PolyChat
namespace PolyChat.Models
{
public class Connection
{

View File

@@ -1,29 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace PolyChat.Models
{
/// <summary>
/// dumy class for json converter
/// </summary>
public class MSG
{
public String sender = "unknown";
public DateTime timestamp = new DateTime(2000, 01, 01);
public String msg = "empty";
public IPAddress ip = new IPAddress(new byte[] { 49,48,46,49,46,50,49,49,46,50,54 });
public MSG(IPAddress ip, String msg, DateTime timestamp)
{
this.sender = sender;
this.ip = ip;
this.timestamp = timestamp;
this.msg = msg;
}
}
}

View File

@@ -1,55 +0,0 @@
using Newtonsoft.Json.Linq;
using System;
namespace PolyChat.Models
{
public class Message
{
public readonly string Sender;
public readonly DateTime Timestamp = new DateTime(1970, 01, 01);
public readonly string Msg = "empty";
public readonly string Ip;
public readonly bool Foreign;
public readonly string StringTimeStamp;
/// <summary>
/// create new Message object from parameters
/// </summary>
/// <param name="Msg"></param>
/// <param name="Foreign"></param>
/// <param name="Sender"></param>
/// <param name="Ip"></param>
public Message(string Msg = "", bool Foreign = true, string Sender= "Unknown", string Ip = "127.0.0.1")
{
this.Sender = Sender;
this.Timestamp = DateTime.Now;
StringTimeStamp = Timestamp.ToString();
this.Msg = Msg;
this.Foreign = Foreign;
this.Ip = Ip;
}
/// <summary>
/// create new Message object from JToken (json)
/// </summary>
/// <param name="data"></param>
public Message(JToken data)
{
Message m = (Message) data[0].ToObject<Message>();
Sender = m.Sender;
Timestamp = m.Timestamp;
StringTimeStamp = Timestamp.ToString();
Msg = m.Msg;
Ip = m.Ip;
Foreign = m.Foreign;
}
override
public string ToString()
{
string prefix = Foreign ? "Other" : "Me";
return $"{prefix}: {Msg}({Sender})";
}
}
}

View File

@@ -1,126 +0,0 @@
using System;
using System.Diagnostics;
using System.Collections.Generic;
using SocketIOSharp.Client;
using EngineIOSharp.Common.Enum;
using System.Net;
using PolyChat.Models.Exceptions;
//dependencies for server functionality
using SocketIOSharp.Server;
using SocketIOSharp.Server.Client;
using Newtonsoft.Json.Linq;
using System.Threading;
namespace PolyChat.Models
{
class NetworkingController
{
public List<Client> clients = new List<Client>();
private String ownName = "";
private IPAddress ownIP;
private readonly ushort Port;
private SocketIOServer Server;
private readonly MainPage uiController;
public NetworkingController (MainPage uiController, ushort Port = 8050)
{
this.uiController = uiController;
this.Port = Port;
ownIP = getIP();
startServer();
}
//EXTERNAL METHODS
//=========================================================================================================================================================================================
/// <summary>
/// connects self to server with given ip
/// </summary>
/// <param name="ip"> server to connect to </param>
public void connectNewClient(String ip)
{
SocketIOClient connection = new SocketIOClient(new SocketIOClientOption(EngineIOScheme.http, ip, 8050));
connection.Connect();
clients.Add(new Client(connection, ip, uiController));
}
/// <summary>
/// handle incomming connection
/// </summary>
/// <param name="ip"> server to connect to </param>
private void connectNewClient(SocketIOSocket socket)
{
socket.On(SendCode.Initial.ToString(), (JToken[] Data) =>
{
Debug.WriteLine("Client connected!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
Message m = new Message(Data[0]);
clients.Add(new Client(socket,m.Ip, uiController));
});
}
/// <summary>
/// sends Message to given ip
/// </summary>
/// <param name="ip"> partner to send to </param>
/// <param name="msg"> to send </param>
public void sendMessage(String ip, String msg)
{
this.getClient(ip).sendMessage(SendCode.Initial, msg);
}
/// <summary>
/// returns own ip adress
/// </summary>
/// <returns></returns>
public IPAddress getIP()
{
IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
IPAddress[] addrList = ipEntry.AddressList;
for (short i = 0; i < addrList.Length; i++)
{
if (addrList[i].ToString().Substring(0, 3).Equals("10."))
{
return addrList[i];
}
}
return null;
}
public MainPage getUIController()
{
return this.uiController;
}
//=========================================================================================================================================================================================
//INTERNAL METHODS
//=========================================================================================================================================================================================
private void startServer()
{
Server = new SocketIOServer(new SocketIOServerOption(Port));
Server.OnConnection((socket) => connectNewClient(socket));
Server.Start();
Debug.WriteLine($"Your ip is: {ownIP}");
Debug.WriteLine($"Server started, binding to port {Port}, waiting for connection...");
}
/// <summary>
/// returns client that fit to ip address
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
private Client getClient(String ip)
{
foreach (Client cl in clients)
{
if (cl.getIP().Equals(ip))
{
return cl;
}
}
return null;
}
}
}

View File

@@ -1,10 +0,0 @@
namespace PolyChat.Models
{
enum SendCode
{
Message,
Command,
NameChange,
Initial
}
}

View File

@@ -119,19 +119,15 @@
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
</Compile>
<Compile Include="Connection.cs" />
<Compile Include="Models\Connection.cs" />
<Compile Include="Controller.cs" />
<Compile Include="MainPage.xaml.cs">
<DependentUpon>MainPage.xaml</DependentUpon>
</Compile>
<Compile Include="Models\ChatMessage.cs" />
<Compile Include="Models\Message.cs" />
<Compile Include="Models\ChatPartner.cs" />
<Compile Include="Models\Exceptions\MessageTimedOutException.cs" />
<Compile Include="Models\NetworkingController.cs" />
<Compile Include="Models\Client.cs" />
<Compile Include="Models\Exceptions\ConnectionFailedException.cs" />
<Compile Include="Models\SendCode.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Util\IP.cs" />
<Compile Include="Views\ConnectionFailedDialog.xaml.cs">