-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
469 lines (429 loc) · 22.4 KB
/
Copy pathProgram.cs
File metadata and controls
469 lines (429 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
using Newtonsoft.Json;
using P2PProject.Client;
using P2PProject.Client.Extensions;
using P2PProject.Client.Models;
using P2PProject.Data;
using System.Linq;
using System.Net;
namespace P2PProject
{
public static class Program
{
public enum SendTypes { String = 1, Object = 2,};
public static bool Connected => _localClient.NetworkId.HasValue;
private static List<string> _commands = new() { "Connect to network via IP", "Connect to network via discovery service", "Initalise Network", "Add Data",
"View Nodes on Network", "View Data", "Disconnect from network", "Generate malformed data", "Check for inactive nodes", "Get File from path",
"Add file and notify network", "Get file on network", "Sync Data from network", "Shutdown Network", "Generate example data", "Simulate unreliable connection", "Add data locally" };
private static bool _quit = false;
private static Node _localClient = new();
private static Action _inputError = () => { Console.WriteLine("Input not recognised, returning to menu\n");};
private static DirectoryService? _directoryService;
public static async Task Main(string[] args)
{
//Set client information
_localClient.InitialiseNode();
Console.WriteLine($"Your information is {_localClient.LocalClientInfo.LocalNodeIP}:{_localClient.LocalClientInfo.Port}\n");
Console.WriteLine("Set the nodes nickname");
var nickname = Console.ReadLine();
_localClient.LocalClientInfo.ClientName = nickname ?? _localClient.LocalClientInfo.LocalNodeIP;
var connectedInvalid = new[] { 1, 2, 3 };
_directoryService = new DirectoryService(_localClient);
_localClient.DirectoryService = _directoryService;
Action _printNodes = () =>
{
Console.WriteLine("Nodes currently on the network:");
int i = 1;
foreach (var node in DataStore.NodeMap.Select(x => x.Value))
{
Console.WriteLine($"{i}. {node.ClientName} {node.LocalNodeIP}:{node.Port}");
i++;
}
};
//Show Networks before menu
await ViewNetworks();
while (!_quit)
{
Console.WriteLine("Hello! Here are the supported features:\n");
for (int i = 0; i < _commands.Count; i++)
{
if (Connected && connectedInvalid.Contains(i+1)) continue;
var y = Connected ? i - 2 : i + 1;
Console.WriteLine($"{y}. {_commands[i]}");
}
if (int.TryParse(Console.ReadLine(), out int command))
{
command = Connected ? command + 3 : command;
switch (command)
{
case 1:
Console.WriteLine("Enter the IP of a node on the network");
if (IPAddress.TryParse(Console.ReadLine(), out IPAddress? ipAddress))
{
Console.WriteLine("Enter the Port of the node");
if (int.TryParse(Console.ReadLine(), out int port))
{
var connectEndpoint = new IPEndPoint(ipAddress, port);
Console.WriteLine($"Attempting connection to {ipAddress}:{port}");
var connectionMessage = new ConnectionNotification
{
IP = _localClient.LocalClientInfo.LocalNodeIP.ToString(),
Port = _localClient.LocalClientInfo.Port,
Id = Guid.NewGuid(),
SenderId = _localClient.LocalClientInfo.ClientId,
SendData = true,
Timestamp = DateTime.UtcNow,
NodeName = _localClient.LocalClientInfo.ClientName,
};
await _localClient.IPInitialConnection(connectEndpoint, connectionMessage);
Console.WriteLine("Connection request made, waiting for response...");
}
else
{
_inputError.Invoke();
continue;
}
}
else
{
_inputError.Invoke();
continue;
}
break;
case 2:
await ViewNetworks();
break;
case 3:
Console.WriteLine("Initialising network...");
var id = await _directoryService.InitialiseNetwork();
if (id == default) { Console.WriteLine("Error initialising network"); break; }
_localClient.NetworkId = id.Value;
break;
case 4:
await AddData();
break;
case 5:
_printNodes.Invoke();
break;
case 6:
Console.WriteLine("Data currently stored:");
foreach (var dataPair in DataStore.NetworkData.OrderBy(x => x.Value.Timestamp))
{
var content = dataPair.Value is StringNotification sn ? sn.Content :
dataPair.Value is SendableItem si ? JsonConvert.SerializeObject(si.Item) : string.Empty;
Console.WriteLine($"({dataPair.Value.Timestamp}) {dataPair.Key}: {dataPair.Value.GetType().Name} \n{content}");
}
break;
case 7:
Console.WriteLine("Disconnecting from network...");
await _localClient.DisconnectFromNetwork();
_quit = true;
Environment.Exit(0);
break;
case 8:
var data = new StringNotification
{
Id = Guid.NewGuid(),
Content = string.Empty,
SenderId = _localClient.LocalClientInfo.ClientId,
Timestamp = DateTime.Now,
};
DataStore.NetworkData.Add(data.Id, data);
var sendData = ByteExtensions.GetByteArray(data);
await _localClient.SendMalformedUDP(sendData.Take(sendData.Length / 2).ToArray(), DataStore.NodeMap.First().Value.LocalIPEndPoint);
break;
case 9:
_localClient.PingService = new PingService(_localClient);
await _localClient.PingService.InitaliseSync();
break;
case 10:
Console.WriteLine("Enter the name or path of the file you want");
var fileName = Console.ReadLine();
Console.WriteLine("Enter the location you want to save the file in");
var saveLocation = Console.ReadLine();
if (fileName != null)
{
var request = new RequestPacket
{
Id = Guid.NewGuid(),
SenderId = _localClient.LocalClientInfo.ClientId,
FileName = fileName,
FromPath = true,
};
_localClient.FileTransferClient = new UDPFileTransferClient(_localClient, saveLocation);
await _localClient.FileTransferClient.SendUDPToNodes(DataStore.NodeMap.Select(x => x.Key).ToList(), request);
}
break;
case 11:
Console.WriteLine("Enter the path of the file you want to add");
var filePath = Console.ReadLine();
if (File.Exists(filePath))
{
string workingDirectory = Environment.CurrentDirectory;
var directory = $"{workingDirectory}\\{_localClient.LocalClientInfo.ClientName}";
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
if(!File.Exists(directory + "\\" + Path.GetFileName(filePath)))
{
File.Copy(filePath, directory + "\\" +Path.GetFileName(filePath));
var fileNotification = new FileNotification
{
Id = Guid.NewGuid(),
SenderId = _localClient.LocalClientInfo.ClientId,
FileName = Path.GetFileName(filePath),
Timestamp = DateTime.UtcNow,
};
DataStore.NetworkData.Add(fileNotification.Id, fileNotification);
await _localClient.SendUDPToNodes(DataStore.NodeMap.Select(x => x.Key).ToList(), fileNotification);
}
else if(DataStore.NetworkData.Any(x => x.Value is FileNotification file && file.FileName == Path.GetFileName(filePath)))
{
Console.WriteLine("Network already knows about this file");
}
else
{
var fileNotification = new FileNotification
{
Id = Guid.NewGuid(),
SenderId = _localClient.LocalClientInfo.ClientId,
FileName = Path.GetFileName(filePath),
Timestamp = DateTime.UtcNow,
};
DataStore.NetworkData.Add(fileNotification.Id, fileNotification);
await _localClient.SendUDPToNodes(DataStore.NodeMap.Select(x => x.Key).ToList(), fileNotification);
}
}
else Console.WriteLine("File does not exist");
break;
case 12:
Console.WriteLine("Enter the name of the file you want\n");
var networkFiles = DataStore.NetworkData.Where(x => x.Value is FileNotification).Select(x => x.Value as FileNotification).ToList();
if (networkFiles.Any())
{
for (int y = 0; y < networkFiles.Count; y++)
{
Console.WriteLine($"{y + 1}. {networkFiles[y]?.FileName}");
}
var fileSelected = Console.ReadLine();
if (int.TryParse(fileSelected, out int fileNumber))
{
string workingDirectory = Environment.CurrentDirectory;
var directory = $"{workingDirectory}\\{_localClient.LocalClientInfo.ClientName}";
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var file = networkFiles[fileNumber - 1];
var request = new RequestPacket
{
Id = Guid.NewGuid(),
SenderId = _localClient.LocalClientInfo.ClientId,
FileName = file.FileName,
FromPath = false,
};
_localClient.FileTransferClient = new UDPFileTransferClient(_localClient, $"{directory}\\{file.FileName}");
await _localClient.FileTransferClient.SendUDPToNodes(DataStore.NodeMap.Select(x => x.Key).ToList(), request);
}
else
{
_inputError.Invoke();
continue;
}
}
else
{
Console.WriteLine("No files currently on the network\n");
}
break;
case 13:
_localClient.SyncService = new DataSyncService(_localClient, true);
await _localClient.SyncService.InitaliseSync();
break;
case 14:
Console.WriteLine("Shutting down network...");
var shutdown = new NetworkNotification
{
Id = Guid.NewGuid(),
SenderId = _localClient.LocalClientInfo.ClientId,
Timestamp = DateTime.UtcNow,
Type = NotificationType.NetworkShutdown,
};
_quit = true;
await _localClient.SendUDPToNodes(DataStore.NodeMap.Select(x => x.Key).ToList(), shutdown);
await _directoryService.NetworkShutdown(_localClient.NetworkId.Value);
Console.WriteLine("Network shutdown, Shutting down node");
Environment.Exit(0);
break;
case 15:
await GenerateExampleData();
break;
case 16:
await SimulateUnstableConnection();
break;
case 17:
await AddData(true);
break;
default:
_inputError.Invoke();
continue;
}
}
else
{
_inputError.Invoke();
continue;
}
}
}
private static async Task ViewNetworks()
{
var networks = await _directoryService.GetNetworks();
if (networks == null || networks.Count == 0)
{
Console.WriteLine("No networks currently available to join\n");
return;
}
Console.WriteLine("Networks currently available:");
int i = 1;
foreach (var network in networks)
{
Console.WriteLine($"{i}. Network: {network.Id} \nConnectedNodes: {network.NodeCount}");
i++;
}
Console.WriteLine("Select the network to connect to or type N to go to menu\n");
var networkSelected = Console.ReadLine();
if (networkSelected?.ToLower() == "n")
{
return;
}
else if (int.TryParse(networkSelected, out int networkNumber))
{
if (networkNumber > networks.Count || networkNumber < 1)
{
_inputError.Invoke();
return;
}
var network = networks[networkNumber - 1];
var id = await _directoryService.ConnectViaDirectory(network.Id);
if (id == default || id == Guid.Empty) { Console.WriteLine("Error connecting to network"); return; }
_localClient.NetworkId = id.Value;
return;
}
else
{
_inputError.Invoke();
return;
}
}
private static async Task AddData(bool localOnly = false)
{
Console.WriteLine("What kind of data do you want to add?");
int i = 1;
foreach (var type in Enum.GetNames(typeof(SendTypes)))
{
Console.WriteLine($"{i}. {type}");
i++;
}
if (int.TryParse(Console.ReadLine(), out int messageType))
{
switch (messageType)
{
case 1:
Console.WriteLine("What is the string content?");
var content = Console.ReadLine();
var message = new StringNotification
{
Id = Guid.NewGuid(),
Content = content ?? string.Empty,
SenderId = _localClient.LocalClientInfo.ClientId,
Timestamp = DateTime.Now,
};
DataStore.NetworkData.Add(message.Id, message);
if (DataStore.NodeMap.Any() && !localOnly)
{
await _localClient.SendUDPToNodes(DataStore.NodeMap.Select(x => x.Key).ToList(), message);
}
else
{
Console.WriteLine("You are not connected to a network, data has been saved");
}
break;
case 2:
Console.WriteLine("What is the object content as JSON?");
var objectContent = Console.ReadLine();
var obj = JsonConvert.DeserializeObject(objectContent ?? string.Empty);
var sendableItem = new SendableItem
{
Id = Guid.NewGuid(),
Item = obj,
SenderId = _localClient.LocalClientInfo.ClientId,
Timestamp = DateTime.Now,
};
DataStore.NetworkData.Add(sendableItem.Id, sendableItem);
if (DataStore.NodeMap.Any() && !localOnly)
{
await _localClient.SendUDPToNodes(DataStore.NodeMap.Select(x => x.Key).ToList(), sendableItem);
}
else
{
Console.WriteLine("You are not connected to a network, data has been saved");
}
break;
}
}
else { _inputError.Invoke(); return;}
}
private static async Task GenerateExampleData(bool localOnly = false)
{
var items = new List<ISendableItem>();
for(int i =0; i<10; i++)
{
var message = new StringNotification
{
Id = Guid.NewGuid(),
Content = "Example String",
SenderId = _localClient.LocalClientInfo.ClientId,
Timestamp = DateTime.Now,
};
items.Add(message);
var sendableItem = new SendableItem
{
Id = Guid.NewGuid(),
Item = new { Example = "Example Object", Age = 19, Name = "Rory", University = "Queen's University Belfast" },
SenderId = _localClient.LocalClientInfo.ClientId,
Timestamp = DateTime.Now,
};
items.Add(sendableItem);
}
foreach(var item in items)
{
DataStore.NetworkData.Add(item.Id, item);
if (DataStore.NodeMap.Any() && !localOnly)
{
var itemTasks = new List<Task>();
var ids = DataStore.NodeMap.Select(x => x.Key).ToList();
itemTasks.Add(_localClient.SendUDPToNodes(ids, item));
await Task.WhenAll(itemTasks);
}
}
}
private static async Task SimulateUnstableConnection()
{
Console.WriteLine("Simulating Unstable Connection\n");
var data = new StringNotification
{
Id = Guid.NewGuid(),
Content = string.Empty,
SenderId = _localClient.LocalClientInfo.ClientId,
Timestamp = DateTime.Now,
};
DataStore.NetworkData.Add(data.Id, data);
var nodeCount = DataStore.NodeMap.Count;
var malformedNode = DataStore.NodeMap.First();
var sendData = ByteExtensions.GetByteArray(data);
await _localClient.SendMalformedUDP(sendData.Take(sendData.Length / 2).ToArray(), malformedNode.Value.LocalIPEndPoint);
await _localClient.SendUDPToNodes(DataStore.NodeMap.Select(x => x.Key).Where(x => x != malformedNode.Key).Take(nodeCount / 2).ToList(), data);
}
}
}