Upload project.

This commit is contained in:
StevenJW
2020-06-09 21:02:14 +01:00
parent 656abcf9ad
commit 1164c93622
520 changed files with 28059 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace Syski.WebSocket
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}

View File

@@ -0,0 +1,13 @@
using Newtonsoft.Json.Linq;
namespace Syski.WebSocket.Services.WebSockets.Actions
{
public class Action
{
public string action { get; set; }
public JObject properties { get; set; }
}
}

View File

@@ -0,0 +1,143 @@
using Newtonsoft.Json.Linq;
using Syski.WebSocket.Services.WebSockets.Actions.Handlers;
using System;
namespace Syski.WebSocket.Services.WebSockets.Actions
{
public class ActionFactory
{
public static ActionHandler CreateActionHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider)
{
ActionHandler result = null;
switch (action.action)
{
case "user-authentication":
{
result = new UserAuthenticationHandler(action, webSocketConnection, serviceProvider);
break;
}
case "system-authentication":
{
result = new SystemAuthenticationHandler(action, webSocketConnection, serviceProvider);
break;
}
case "staticsystem":
{
result = new StaticSystemHandler(action, webSocketConnection, serviceProvider);
break;
}
case "staticcpu":
{
result = new StaticCPUHandler(action, webSocketConnection, serviceProvider);
break;
}
case "staticram":
{
result = new StaticRAMHandler(action, webSocketConnection, serviceProvider);
break;
}
case "staticgpu":
{
result = new StaticGPUHandler(action, webSocketConnection, serviceProvider);
break;
}
case "staticstorage":
{
result = new StaticStorageHandler(action, webSocketConnection, serviceProvider);
break;
}
case "staticmotherboard":
{
result = new StaticMotherboardHandler(action, webSocketConnection, serviceProvider);
break;
}
case "staticbios":
{
result = new StaticBIOSHandler(action, webSocketConnection, serviceProvider);
break;
}
case "staticos":
{
result = new StaticOperatingSystemHandler(action, webSocketConnection, serviceProvider);
break;
}
case "variableping":
{
result = new VariablePingHandler(action, webSocketConnection, serviceProvider);
break;
}
case "variablecpu":
{
result = new VariableCPUHandler(action, webSocketConnection, serviceProvider);
break;
}
case "variableram":
{
result = new VariableRAMHandler(action, webSocketConnection, serviceProvider);
break;
}
case "variablestorage":
{
result = new VariableStorageHandler(action, webSocketConnection, serviceProvider);
break;
}
case "runningprocesses":
{
result = new VariableRunningProcessesHandler(action, webSocketConnection, serviceProvider);
break;
}
default:
{
result = new DefaultHandler(action, webSocketConnection, serviceProvider);
break;
}
}
return result;
}
public static ActionHandler CreateAuthActionHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider)
{
ActionHandler result = null;
switch (action.action)
{
case "user-authentication":
{
result = new UserAuthenticationHandler(action, webSocketConnection, serviceProvider);
break;
}
case "system-authentication":
{
result = new SystemAuthenticationHandler(action, webSocketConnection, serviceProvider);
break;
}
default:
{
result = new DefaultHandler(action, webSocketConnection, serviceProvider);
break;
}
}
return result;
}
public static Action CreateAction(string actionName)
{
return CreateAction(actionName, null);
}
public static Action CreateAction(string actionName, JObject actionProperties)
{
if (actionProperties == null)
{
actionProperties = new JObject();
}
return new Action()
{
action = actionName,
properties = actionProperties
};
}
}
}

View File

@@ -0,0 +1,22 @@
using System;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public abstract class ActionHandler
{
protected readonly Action action;
protected readonly WebSocketConnection webSocketConnection;
protected readonly IServiceProvider serviceProvider;
public ActionHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider)
{
this.action = action;
this.webSocketConnection = webSocketConnection;
this.serviceProvider = serviceProvider;
}
public abstract void HandleAction();
}
}

View File

@@ -0,0 +1,42 @@
using System;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class AuthenticationHandler : ActionHandler
{
// Delay between each command run after authentication
private static readonly int delayBetweenAction = 100;
// Commands run after authentication
private static readonly string[] actions = {
"staticsystem",
"staticcpu",
"staticram",
"staticgpu",
"staticstorage",
"staticmotherboard",
"staticbios",
"staticos"
};
public AuthenticationHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override async void HandleAction()
{
webSocketConnection.Authentication = true;
WebSocketManager websocketManager = serviceProvider.GetService<WebSocketManager>();
websocketManager.AddSocket(webSocketConnection.Id, webSocketConnection);
foreach (string action in actions)
{
await webSocketConnection.SendAction(action);
Thread.Sleep(delayBetweenAction);
}
}
}
}

View File

@@ -0,0 +1,23 @@
using Newtonsoft.Json.Linq;
using System;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class DefaultHandler : ActionHandler
{
public DefaultHandler(Action action, WebSocketConnection webSocket, IServiceProvider serviceProvider) : base(action, webSocket, serviceProvider)
{
}
public override async void HandleAction()
{
JObject properties = new JObject
{
{ "message", "Invalid Action Sent (" + action.action + ")" }
};
await webSocketConnection.SendAction("error", properties);
}
}
}

View File

@@ -0,0 +1,99 @@
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class StaticBIOSHandler : ActionHandler
{
public StaticBIOSHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
string manufacturerFromJSON = (string) action.properties.SelectToken("manufacturer");
string captionFromJSON = (string)action.properties.SelectToken("caption");
string versionFromJSON = (string) action.properties.SelectToken("version");
string dateFromJSON = (string) action.properties.SelectToken("date");
Manufacturer manufacturer = context.Manufacturers.Where(m => m.Name == manufacturerFromJSON).FirstOrDefault();
if (manufacturer == null && manufacturerFromJSON != null)
{
manufacturer = new Manufacturer
{
Name = manufacturerFromJSON
};
context.Add(manufacturer);
context.SaveChanges();
}
Guid? manufacturerId = (manufacturer != null ? manufacturer.Id : (Guid?) null);
var biosModel = context.BIOSModels.FirstOrDefault(m => m.ManufacturerId.Equals(manufacturer));
if (biosModel == null)
{
biosModel = new BIOSModel
{
ManufacturerId = manufacturerId
};
context.Add(biosModel);
context.SaveChanges();
}
var systemBIOS = context.SystemBIOSs.FirstOrDefault(m => m.SystemId.Equals(systemUUID));
if (systemBIOS == null)
{
systemBIOS = new SystemBIOS
{
SystemId = systemUUID,
BIOSModelId = biosModel.Id,
Caption = captionFromJSON,
Version = versionFromJSON,
Date = dateFromJSON,
LastUpdated = DateTime.Now
};
context.Add(systemBIOS);
context.SaveChanges();
}
else
{
if (!systemBIOS.BIOSModelId.Equals(biosModel.Id))
{
context.Remove(systemBIOS);
systemBIOS = new SystemBIOS
{
SystemId = systemUUID,
BIOSModelId = biosModel.Id,
Caption = captionFromJSON,
Version = versionFromJSON,
Date = dateFromJSON,
LastUpdated = DateTime.Now
};
context.Add(systemBIOS);
context.SaveChanges();
}
else
{
systemBIOS.Caption = captionFromJSON;
systemBIOS.Version = versionFromJSON;
systemBIOS.Date = dateFromJSON;
systemBIOS.LastUpdated = DateTime.Now;
context.Update(systemBIOS);
context.SaveChanges();
}
}
}
}
}
}

View File

@@ -0,0 +1,131 @@
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using System;
using System.Linq;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class StaticCPUHandler : ActionHandler
{
public StaticCPUHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
DateTime lastUpdated = DateTime.Now;
int slot = 0;
string modelFromJSON = (string) action.properties.SelectToken("model");
string manufacturerFromJSON = (string) action.properties.SelectToken("manufacturer");
string architectureFromJSON = (string) action.properties.SelectToken("architecture");
int clockspeedFromJSON = (int) action.properties.SelectToken("clockspeed");
int corecountFromJSON = (int) action.properties.SelectToken("corecount");
int threadcountFromJSON = (int) action.properties.SelectToken("threadcount");
Manufacturer manufacturer = context.Manufacturers.Where(m => m.Name == manufacturerFromJSON).FirstOrDefault();
if (manufacturer == null && manufacturerFromJSON != null)
{
manufacturer = new Manufacturer
{
Name = manufacturerFromJSON
};
context.Add(manufacturer);
context.SaveChanges();
}
Guid? manufacturerId = (manufacturer != null ? manufacturer.Id : (Guid?) null);
Model model = context.Models.FirstOrDefault(m => m.Name.Equals(modelFromJSON) && m.ManufacturerId.Equals(manufacturerId));
if ((model == null) && ((modelFromJSON != null && manufacturer == null) || (modelFromJSON != null || manufacturer != null)))
{
model = new Model
{
Name = modelFromJSON
};
if (manufacturer != null)
{
model.ManufacturerId = manufacturer.Id;
}
context.Add(model);
context.SaveChanges();
}
var architecture = context.Architectures.FirstOrDefault(m => m.Name.Equals(architectureFromJSON));
if (architecture == null && architectureFromJSON != null)
{
architecture = new Architecture
{
Name = architectureFromJSON
};
context.Add(architecture);
context.SaveChanges();
}
Guid? modelId = (model != null ? model.Id : (Guid?) null);
Guid? architectureId = (architecture != null ? architecture.Id : (Guid?) null);
var cpuModel = context.CPUModels.FirstOrDefault(m => m.ModelId.Equals(modelId) && m.ArchitectureId.Equals(architectureId));
if (cpuModel == null)
{
cpuModel = new CPUModel
{
ModelId = modelId,
ArchitectureId = architectureId
};
context.Add(cpuModel);
context.SaveChanges();
}
var systemCPU = context.SystemCPUs.Where(m => m.SystemId.Equals(systemUUID) && m.Slot.Equals(slot)).FirstOrDefault();
if (systemCPU == null)
{
systemCPU = new SystemCPU
{
SystemId = systemUUID,
CPUModelID = cpuModel.Id,
ClockSpeed = clockspeedFromJSON,
CoreCount = corecountFromJSON,
ThreadCount = threadcountFromJSON,
LastUpdated = lastUpdated
};
context.Add(systemCPU);
context.SaveChanges();
}
else
{
if (!systemCPU.CPUModelID.Equals(cpuModel.Id))
{
context.Remove(systemCPU);
systemCPU = new SystemCPU
{
SystemId = systemUUID,
CPUModelID = cpuModel.Id,
ClockSpeed = clockspeedFromJSON,
CoreCount = corecountFromJSON,
ThreadCount = threadcountFromJSON,
LastUpdated = lastUpdated
};
context.Add(systemCPU);
context.SaveChanges();
}
else
{
systemCPU.ClockSpeed = clockspeedFromJSON;
systemCPU.CoreCount = corecountFromJSON;
systemCPU.ThreadCount = threadcountFromJSON;
systemCPU.LastUpdated = lastUpdated;
context.Update(systemCPU);
context.SaveChanges();
}
}
//slot++;
}
}
}
}

View File

@@ -0,0 +1,110 @@
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using Syski.WebSocket.Services.WebSockets.Actions.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class StaticGPUHandler : ActionHandler
{
public StaticGPUHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
DateTime lastUpdated = DateTime.Now;
int slot = 0;
string modelFromJSON = (string) action.properties.SelectToken("model");
string manufacturerFromJSON = (string) action.properties.SelectToken("manufacturer");
Manufacturer manufacturer = context.Manufacturers.Where(m => m.Name == manufacturerFromJSON).FirstOrDefault();
if (manufacturer == null && manufacturerFromJSON != null)
{
manufacturer = new Manufacturer
{
Name = manufacturerFromJSON
};
context.Add(manufacturer);
context.SaveChanges();
}
Guid? manufacturerId = (manufacturer != null ? manufacturer.Id : (Guid?)null);
Model model = context.Models.FirstOrDefault(m => m.Name.Equals(modelFromJSON) && m.ManufacturerId.Equals(manufacturerId));
if ((model == null) && ((modelFromJSON != null && manufacturer == null) || (modelFromJSON != null || manufacturer != null)))
{
model = new Model
{
Name = modelFromJSON
};
if (manufacturer != null)
{
model.ManufacturerId = manufacturer.Id;
}
context.Add(model);
context.SaveChanges();
}
Guid? modelId = (model != null ? model.Id : (Guid?)null);
var gpuModel = context.GPUModels.FirstOrDefault(m => m.ModelId.Equals(modelId));
if (gpuModel == null)
{
gpuModel = new GPUModel
{
ModelId = modelId,
};
context.Add(gpuModel);
context.SaveChanges();
}
var systemGPU = context.SystemGPUs.Where(m => m.SystemId.Equals(systemUUID) && m.Slot.Equals(slot)).FirstOrDefault();
if (systemGPU == null)
{
systemGPU = new SystemGPU
{
SystemId = systemUUID,
GPUModelId = gpuModel.Id,
Slot = slot,
LastUpdated = lastUpdated
};
context.Add(systemGPU);
context.SaveChanges();
}
else
{
if (!systemGPU.GPUModelId.Equals(gpuModel.Id))
{
context.Remove(systemGPU);
systemGPU = new SystemGPU
{
SystemId = systemUUID,
GPUModelId = gpuModel.Id,
Slot = slot,
LastUpdated = lastUpdated
};
context.Add(systemGPU);
context.SaveChanges();
}
else
{
systemGPU.LastUpdated = lastUpdated;
context.Update(systemGPU);
context.SaveChanges();
}
}
//slot++;
}
}
}
}

View File

@@ -0,0 +1,106 @@
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class StaticMotherboardHandler : ActionHandler
{
public StaticMotherboardHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
string modelFromJSON = (string) action.properties.SelectToken("model");
string manufacturerFromJSON = (string) action.properties.SelectToken("manufacturer");
string versionFromJSON = (string) action.properties.SelectToken("version");
Manufacturer manufacturer = context.Manufacturers.Where(m => m.Name == manufacturerFromJSON).FirstOrDefault();
if (manufacturer == null && manufacturerFromJSON != null)
{
manufacturer = new Manufacturer
{
Name = manufacturerFromJSON
};
context.Add(manufacturer);
context.SaveChanges();
}
Guid? manufacturerId = (manufacturer != null ? manufacturer.Id : (Guid?) null);
Model model = context.Models.FirstOrDefault(m => m.Name.Equals(modelFromJSON) && m.ManufacturerId.Equals(manufacturerId));
if ((model == null) && ((modelFromJSON != null && manufacturer == null) || (modelFromJSON != null || manufacturer != null)))
{
model = new Model
{
Name = modelFromJSON
};
if (manufacturer != null)
{
model.ManufacturerId = manufacturer.Id;
}
context.Add(model);
context.SaveChanges();
}
Guid? modelId = (model != null ? model.Id : (Guid?) null);
var motherboardModel = context.MotherboardModels.FirstOrDefault(m => m.ModelId.Equals(modelId) && m.Version.Equals(versionFromJSON));
if (motherboardModel == null)
{
motherboardModel = new MotherboardModel
{
ModelId = modelId,
Version = versionFromJSON
};
context.Add(motherboardModel);
context.SaveChanges();
}
var systemMotherboard = context.SystemMotherboards.FirstOrDefault(m => m.SystemId.Equals(systemUUID));
if (systemMotherboard == null)
{
systemMotherboard = new SystemMotherboard
{
SystemId = systemUUID,
MotherboardModelId = motherboardModel.Id,
LastUpdated = DateTime.Now
};
context.Add(systemMotherboard);
context.SaveChanges();
}
else
{
if (!systemMotherboard.MotherboardModelId.Equals(motherboardModel.Id))
{
context.Remove(systemMotherboard);
systemMotherboard = new SystemMotherboard
{
SystemId = systemUUID,
MotherboardModelId = motherboardModel.Id,
LastUpdated = DateTime.Now
};
context.Add(systemMotherboard);
context.SaveChanges();
}
else
{
systemMotherboard.LastUpdated = DateTime.Now;
context.Update(systemMotherboard);
context.SaveChanges();
}
}
}
}
}
}

View File

@@ -0,0 +1,95 @@
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class StaticOperatingSystemHandler : ActionHandler
{
public StaticOperatingSystemHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
string osnameFromJSON = (string) action.properties.SelectToken("name");
string architectureFromJSON = (string) action.properties.SelectToken("architecture");
string versionFromJSON = (string) action.properties.SelectToken("version");
var osName = context.OperatingSystemModels.FirstOrDefault(m => m.Name == osnameFromJSON);
if (osName == null)
{
osName = new Data.OperatingSystemModel()
{
Name = osnameFromJSON
};
context.Add(osName);
context.SaveChanges();
}
var architecture = context.Architectures.Where(m => m.Name == architectureFromJSON).FirstOrDefault();
if (architecture == null && architectureFromJSON != null)
{
architecture = new Architecture
{
Name = architectureFromJSON
};
context.Add(architecture);
context.SaveChanges();
}
Guid? architectureId = (architecture != null ? architecture.Id : (Guid?)null);
var systemOS = context.SystemOSs.FirstOrDefault(m => m.SystemId.Equals(systemUUID));
if (systemOS == null)
{
systemOS = new SystemOS()
{
SystemId = systemUUID,
OperatingSystemId = osName.Id,
ArchitectureId = architectureId,
Version = versionFromJSON,
LastUpdated = DateTime.Now
};
context.Add(systemOS);
context.SaveChanges();
}
else
{
if (!systemOS.OperatingSystemId.Equals(osName.Id))
{
context.Remove(systemOS);
systemOS = new SystemOS()
{
SystemId = systemUUID,
OperatingSystemId = osName.Id,
ArchitectureId = architectureId,
Version = versionFromJSON,
LastUpdated = DateTime.Now
};
context.Add(systemOS);
context.SaveChanges();
}
else
{
systemOS.ArchitectureId = architectureId;
systemOS.Version = versionFromJSON;
systemOS.LastUpdated = DateTime.Now;
context.Update(systemOS);
context.SaveChanges();
}
}
}
}
}
}

View File

@@ -0,0 +1,120 @@
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using Syski.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class StaticRAMHandler : ActionHandler
{
public StaticRAMHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
DateTime lastUpdated = DateTime.Now;
int slot = 0;
JArray ramArray = (JArray) action.properties.SelectToken("ram");
foreach (JToken ram in ramArray)
{
string modelFromJSON = (string) ram.SelectToken("model");
string manufacturerFromJSON = (string) ram.SelectToken("manufacturer");
string typeFromJSON = (string) ram.SelectToken("type");
int speedFromJSON = (int) ram.SelectToken("speed");
long sizeFromJSON = (long) ram.SelectToken("size");
Manufacturer manufacturer = context.Manufacturers.Where(m => m.Name == manufacturerFromJSON).FirstOrDefault();
if (manufacturer == null && manufacturerFromJSON != null)
{
manufacturer = new Manufacturer
{
Name = manufacturerFromJSON
};
context.Add(manufacturer);
context.SaveChanges();
}
Guid? manufacturerId = (manufacturer != null ? manufacturer.Id : (Guid?) null);
Model model = context.Models.FirstOrDefault(m => m.Name.Equals(modelFromJSON) && m.ManufacturerId.Equals(manufacturerId));
if ((model == null) && ((modelFromJSON != null && manufacturer == null) || (modelFromJSON != null || manufacturer != null)))
{
model = new Model
{
Name = modelFromJSON
};
if (manufacturer != null)
{
model.ManufacturerId = manufacturer.Id;
}
context.Add(model);
context.SaveChanges();
}
Guid? modelId = (model != null ? model.Id : (Guid?) null);
var ramModel = context.RAMModels.FirstOrDefault(m => m.ModelId.Equals(modelId) && m.Size.Equals(sizeFromJSON));
if (ramModel == null)
{
ramModel = new RAMModel
{
ModelId = modelId,
Size = sizeFromJSON
};
context.Add(ramModel);
context.SaveChanges();
}
var systemRAM = context.SystemRAMs.Where(m => m.SystemId.Equals(systemUUID) && m.Slot.Equals(slot)).FirstOrDefault();
if (systemRAM == null)
{
systemRAM = new SystemRAM
{
SystemId = systemUUID,
RAMModelId = ramModel.Id,
Slot = slot,
Speed = speedFromJSON,
LastUpdated = lastUpdated
};
context.Add(systemRAM);
context.SaveChanges();
}
else
{
if (!systemRAM.RAMModelId.Equals(ramModel.Id))
{
context.Remove(systemRAM);
systemRAM = new SystemRAM
{
SystemId = systemUUID,
RAMModelId = ramModel.Id,
Slot = slot,
Speed = speedFromJSON,
LastUpdated = lastUpdated
};
context.Add(systemRAM);
context.SaveChanges();
}
else
{
systemRAM.Speed = speedFromJSON;
systemRAM.LastUpdated = lastUpdated;
context.Update(systemRAM);
context.SaveChanges();
}
}
slot++;
}
}
}
}
}

View File

@@ -0,0 +1,132 @@
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using Syski.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class StaticStorageHandler : ActionHandler
{
public StaticStorageHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
DateTime lastUpdated = DateTime.Now;
int slot = 0;
JArray storageArray = (JArray)action.properties.SelectToken("storage");
foreach (JToken storage in storageArray)
{
string modelFromJSON = (string) storage.SelectToken("model");
string manufacturerFromJSON = (string) storage.SelectToken("manufacturer");
string interfaceFromJSON = (string) storage.SelectToken("interface");
long sizeFromJSON = (long) storage.SelectToken("size");
Manufacturer manufacturer = context.Manufacturers.Where(m => m.Name == manufacturerFromJSON).FirstOrDefault();
if (manufacturer == null && manufacturerFromJSON != null)
{
manufacturer = new Manufacturer
{
Name = manufacturerFromJSON
};
context.Add(manufacturer);
context.SaveChanges();
}
Guid? manufacturerId = (manufacturer != null ? manufacturer.Id : (Guid?) null);
Model model = context.Models.FirstOrDefault(m => m.Name.Equals(modelFromJSON) && m.ManufacturerId.Equals(manufacturerId));
if ((model == null) && ((modelFromJSON != null && manufacturer == null) || (modelFromJSON != null || manufacturer != null)))
{
model = new Model
{
Name = modelFromJSON
};
if (manufacturer != null)
{
model.ManufacturerId = manufacturer.Id;
}
context.Add(model);
context.SaveChanges();
}
Guid? modelId = (model != null ? model.Id : (Guid?) null);
var storageModel = context.StorageModels.FirstOrDefault(m => m.ModelId.Equals(modelId) && m.Size.Equals(sizeFromJSON));
if (storageModel == null)
{
storageModel = new StorageModel
{
ModelId = modelId,
Size = sizeFromJSON
};
context.Add(storageModel);
context.SaveChanges();
}
var interfacetype = context.StorageInterfaceTypes.Where(t => t.Name == interfaceFromJSON).FirstOrDefault();
if (interfacetype == null && interfaceFromJSON != null)
{
interfacetype = new StorageInterfaceType()
{
Name = interfaceFromJSON
};
context.Add(interfacetype);
context.SaveChanges();
}
Guid? interfacetypeId = (interfacetype != null ? interfacetype.Id : (Guid?) null);
var systemStorage = context.SystemStorages.Where(m => m.SystemId.Equals(systemUUID) && m.Slot.Equals(slot)).FirstOrDefault();
if (systemStorage == null)
{
systemStorage = new SystemStorage
{
SystemId = systemUUID,
StorageModelId = storageModel.Id,
Slot = slot,
StorageInterfaceId = interfacetypeId,
LastUpdated = lastUpdated
};
context.Add(systemStorage);
context.SaveChanges();
}
else
{
if (!systemStorage.StorageModelId.Equals(storageModel.Id))
{
context.Remove(systemStorage);
systemStorage = new SystemStorage
{
SystemId = systemUUID,
StorageModelId = storageModel.Id,
Slot = slot,
StorageInterfaceId = interfacetypeId,
LastUpdated = lastUpdated
};
context.Add(systemStorage);
context.SaveChanges();
}
else
{
systemStorage.StorageInterfaceId = interfacetypeId;
systemStorage.LastUpdated = lastUpdated;
context.Update(systemStorage);
context.SaveChanges();
}
}
slot++;
}
}
}
}
}

View File

@@ -0,0 +1,125 @@
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class StaticSystemHandler : ActionHandler
{
public StaticSystemHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
var system = context.Systems.Where(u => u.Id == systemUUID).FirstOrDefault();
if (system != null)
{
string modelFromJSON = (string) action.properties.SelectToken("model");
string manufacturerFromJSON = (string) action.properties.SelectToken("manufacturer");
string typeFromJSON = (string) action.properties.SelectToken("type");
string hostNameFromJSON = (string) action.properties.SelectToken("hostname");
Manufacturer manufacturer = context.Manufacturers.Where(m => m.Name == manufacturerFromJSON).FirstOrDefault();
if (manufacturer == null && manufacturerFromJSON != null)
{
manufacturer = new Manufacturer
{
Name = manufacturerFromJSON
};
context.Add(manufacturer);
context.SaveChanges();
}
Guid? manufacturerId = (manufacturer != null ? manufacturer.Id : (Guid?) null);
Model model = context.Models.FirstOrDefault(m => m.Name.Equals(modelFromJSON) && m.ManufacturerId.Equals(manufacturerId));
if ((model == null) && ((modelFromJSON != null && manufacturer == null) || (modelFromJSON != null || manufacturer != null)))
{
model = new Model
{
Name = modelFromJSON
};
if (manufacturer != null)
{
model.ManufacturerId = manufacturer.Id;
}
context.Add(model);
context.SaveChanges();
}
List<SystemTypeName> systemTypeNameList = new List<SystemTypeName>();
SystemTypeName systemTypeName = context.SystemTypeNames.FirstOrDefault(stn => stn.Name.Equals(typeFromJSON));
if (systemTypeName == null && typeFromJSON != null)
{
systemTypeName = new SystemTypeName
{
Name = typeFromJSON
};
context.Add(systemTypeName);
context.SaveChanges();
systemTypeNameList.Add(systemTypeName);
}
else
{
systemTypeNameList.Add(systemTypeName);
}
bool changed = false;
List<SystemType> currentSystemTypes = context.SystemTypes.Where(st => st.SystemId.Equals(systemUUID)).ToList();
List<SystemType> removeSystemTypes = currentSystemTypes.ToList();
foreach (SystemTypeName stn in systemTypeNameList)
{
bool found = false;
foreach(SystemType st in currentSystemTypes)
{
if (st.TypeId.Equals(stn.Id))
{
found = true;
removeSystemTypes.Remove(st);
}
}
if (!found)
{
SystemType systemType = new SystemType
{
SystemId = systemUUID,
TypeId = stn.Id
};
context.Add(systemType);
changed = true;
}
}
if (changed)
{
context.SaveChanges();
}
if (removeSystemTypes.Count > 0)
{
foreach (SystemType st in removeSystemTypes)
{
context.Remove(st);
}
context.SaveChanges();
}
system.ModelId = (model != null ? model.Id : (Guid?) null);
system.HostName = hostNameFromJSON;
system.LastUpdated = DateTime.Now;
context.Update(system);
context.SaveChanges();
}
}
}
}
}

View File

@@ -0,0 +1,31 @@
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using System;
using System.Linq;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class SystemAuthenticationHandler : AuthenticationHandler
{
public SystemAuthenticationHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var system = context.Systems.FirstOrDefault(s => s.Id == Guid.Parse((string) action.properties.SelectToken("system")) && s.Secret == (string) action.properties.SelectToken("secret"));
if (system != null)
{
WebSocketManager websocketManager = serviceProvider.GetService<WebSocketManager>();
websocketManager.SetSystemLink(webSocketConnection.Id, Guid.Parse((string) action.properties.SelectToken("system")));
base.HandleAction();
}
}
}
}
}

View File

@@ -0,0 +1,52 @@
using System;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Identity;
using Newtonsoft.Json.Linq;
using Syski.Data;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class UserAuthenticationHandler : AuthenticationHandler
{
public UserAuthenticationHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override async void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
ApplicationUser user = userManager.Users.SingleOrDefault(r => r.Email.Equals((string) action.properties.SelectToken("email")));
if (user != null)
{
bool validPassword = await userManager.CheckPasswordAsync(user, (string) action.properties.SelectToken("password"));
if (validPassword)
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var system = new Data.System
{
LastUpdated = DateTime.Now,
Secret = Guid.NewGuid().ToString().Replace("-", "")
};
context.Add(system);
context.SaveChanges();
var applicationUserSystems = new ApplicationUserSystems()
{
UserId = user.Id,
SystemId = system.Id
};
context.Add(applicationUserSystems);
context.SaveChanges();
await webSocketConnection.SendAction("authentication", new JObject { { "system", system.Id }, { "secret", system.Secret } });
}
}
}
}
}
}

View File

@@ -0,0 +1,40 @@
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class VariableCPUHandler : ActionHandler
{
public VariableCPUHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
double loadFromJSON = (double) action.properties.SelectToken("load");
int processesFromJSON = (int) action.properties.SelectToken("processes");
var systemCPUData = new SystemCPUData()
{
SystemId = systemUUID,
CollectionDateTime = DateTime.Now,
Load = loadFromJSON,
Processes = processesFromJSON
};
context.Add(systemCPUData);
context.SaveChanges();
}
}
}
}

View File

@@ -0,0 +1,32 @@
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class VariablePingHandler : ActionHandler
{
public VariablePingHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
var pingData = context.SystemPingData.OrderByDescending(i => i.SendPingTime).FirstOrDefault(spd => spd.SystemId.Equals(systemUUID));
pingData.CollectionDateTime = DateTime.Now;
context.Update(pingData);
context.SaveChanges();
}
}
}
}

View File

@@ -0,0 +1,38 @@
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class VariableRAMHandler : ActionHandler
{
public VariableRAMHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
int freeFromJSON = (int) action.properties.SelectToken("free");
var systemRAMData = new SystemRAMData()
{
SystemId = systemUUID,
CollectionDateTime = DateTime.Now,
Free = freeFromJSON,
};
context.Add(systemRAMData);
context.SaveChanges();
}
}
}
}

View File

@@ -0,0 +1,55 @@
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using Syski.Data;
using System;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class VariableRunningProcessesHandler : ActionHandler
{
public VariableRunningProcessesHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
DateTime lastUpdated = DateTime.Now;
JArray processesArray = (JArray) action.properties.SelectToken("processes");
foreach (JToken process in processesArray)
{
int idFromJSON = (int) process.SelectToken("id");
string nameFromJSON = (string) process.SelectToken("name");
long memsizetimeFromJSON = (long) process.SelectToken("memsize");
long kerneltimeFromJSON = (long) process.SelectToken("kerneltime");
string pathFromJSON = (string) process.SelectToken("path");
int threadsFromJSON = (int) process.SelectToken("threads");
long uptimeFromJSON = (long) process.SelectToken("uptime");
int parentidFromJSON = (int) process.SelectToken("parentid");
var systemProcess = new SystemRunningProcesses()
{
SystemId = systemUUID,
Id = idFromJSON,
Name = nameFromJSON,
MemSize = memsizetimeFromJSON,
KernelTime = kerneltimeFromJSON,
Path = pathFromJSON,
Threads = threadsFromJSON,
UpTime = uptimeFromJSON,
ParentId = parentidFromJSON,
CollectionDateTime = lastUpdated
};
context.Add(systemProcess);
}
context.SaveChanges();
}
}
}
}

View File

@@ -0,0 +1,49 @@
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets.Actions.Handlers
{
public class VariableStorageHandler : ActionHandler
{
public VariableStorageHandler(Action action, WebSocketConnection webSocketConnection, IServiceProvider serviceProvider) : base(action, webSocketConnection, serviceProvider)
{
}
public override void HandleAction()
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
float timeFromJSON = (float) action.properties.SelectToken("time");
float transfersFromJSON = (float) action.properties.SelectToken("transfers");
float readsFromJSON = (float) action.properties.SelectToken("reads");
float writesFromJSON = (float) action.properties.SelectToken("writes");
float byteReadsFromJSON = (float) action.properties.SelectToken("bytereads");
float byteWritesFromJSON = (float) action.properties.SelectToken("bytewrites");
DateTime dateTime = DateTime.Now;
var systemStorageData = new SystemStorageData()
{
SystemId = systemUUID,
CollectionDateTime = dateTime,
Time = timeFromJSON,
Transfers = transfersFromJSON,
Reads = readsFromJSON,
Writes = writesFromJSON,
ByteReads = byteReadsFromJSON,
ByteWrites = byteWritesFromJSON
};
context.Add(systemStorageData);
context.SaveChanges();
}
}
}
}

View File

@@ -0,0 +1,22 @@
using Syski.Data;
using System;
namespace Syski.WebSocket.Services.WebSockets.Actions.Tasks
{
public abstract class ActionTask
{
protected readonly string action;
protected readonly IServiceProvider serviceProvider;
protected readonly SyskiDBContext context;
public ActionTask(string action, IServiceProvider serviceProvider)
{
this.action = action;
this.serviceProvider = serviceProvider;
}
public abstract void ExecuteActionTask(WebSocketConnection webSocketConnection);
}
}

View File

@@ -0,0 +1,42 @@
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using Syski.Data;
using System;
using System.Linq;
namespace Syski.WebSocket.Services.WebSockets.Actions.Tasks
{
public class CommandTask : ActionTask
{
public CommandTask(IServiceProvider serviceProvider) : base("command", serviceProvider)
{
}
public override void ExecuteActionTask(WebSocketConnection webSocketConnection)
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
var command = context.SystemCommands.FirstOrDefault(sc => sc.SystemId.Equals(systemUUID) && sc.ExecutedTime == null);
if (command != null)
{
command.ExecutedTime = DateTime.Now;
context.Update(command);
if (command.Properties != null)
{
JObject properties = JObject.Parse(command.Properties);
webSocketConnection.SendAction(command.Action, properties);
}
else
{
webSocketConnection.SendAction(command.Action);
}
context.SaveChanges();
}
}
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Syski.Data;
namespace Syski.WebSocket.Services.WebSockets.Actions.Tasks
{
public class DefaultTask : ActionTask
{
public DefaultTask(string action, IServiceProvider serviceProvider) : base(action, serviceProvider)
{
}
public override void ExecuteActionTask(WebSocketConnection webSocketConnection)
{
webSocketConnection.SendAction(action);
}
}
}

View File

@@ -0,0 +1,31 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
namespace Syski.WebSocket.Services.WebSockets.Actions.Tasks
{
public class VariablePingTask : ActionTask
{
public VariablePingTask(IServiceProvider serviceProvider) : base("variableping", serviceProvider)
{
}
public override void ExecuteActionTask(WebSocketConnection webSocketConnection)
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SyskiDBContext>();
var systemUUID = serviceProvider.GetService<WebSocketManager>().GetSystemId(webSocketConnection.Id);
context.Add(new SystemPingData
{
SystemId = systemUUID,
SendPingTime = DateTime.Now
});
context.SaveChanges();
webSocketConnection.SendAction(action);
}
}
}
}

View File

@@ -0,0 +1,15 @@
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets
{
public interface IWebSocketHandler
{
Task OnConnected(WebSocketConnection webSocketConnection);
Task OnDisconnected(WebSocketConnection webSocketConnection);
Task OnReceiveMessage(WebSocketConnection webSocketConnection);
}
}

View File

@@ -0,0 +1,62 @@
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Syski.WebSocket.Services.WebSockets.Actions;
namespace Syski.WebSocket.Services.WebSockets
{
public class WebSocketConnection
{
public Guid Id { get; } = Guid.NewGuid();
public System.Net.WebSockets.WebSocket WebSocket { get; }
public WebSocketCloseStatus? CloseStatus { get; set; } = null;
public bool Authentication { get; set; } = false;
public string CloseStatusDescription { get; set; } = null;
public CancellationTokenSource CancellationTokenSource;
public WebSocketConnection(System.Net.WebSockets.WebSocket webSocket)
{
WebSocket = webSocket;
CancellationTokenSource = new CancellationTokenSource(60000);
}
public void ResetCancelationToken()
{
CancellationTokenSource.CancelAfter(20000);
}
public CancellationToken GetCancellationToken()
{
return CancellationTokenSource.Token;
}
public async Task SendAction(String actionName)
{
await SendMessage(JsonConvert.SerializeObject(ActionFactory.CreateAction(actionName)));
}
public async Task SendAction(String actionName, JObject actionProperties)
{
await SendMessage(JsonConvert.SerializeObject(ActionFactory.CreateAction(actionName, actionProperties)));
}
private async Task SendMessage(String message)
{
if (WebSocket.State == WebSocketState.Open)
{
await WebSocket.SendAsync(buffer: new ArraySegment<byte>(array: Encoding.ASCII.GetBytes(message), offset: 0, count: message.Length), messageType: WebSocketMessageType.Text, endOfMessage: true, cancellationToken: CancellationToken.None);
}
}
}
}

View File

@@ -0,0 +1,127 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Syski.WebSocket.Services.WebSockets.Actions;
using System;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets
{
public class WebSocketHandler : IWebSocketHandler
{
private readonly IServiceProvider serviceProvider;
private readonly WebSocketManager webSocketManager;
public WebSocketHandler(IServiceProvider serviceProvider, WebSocketManager webSocketManager)
{
this.serviceProvider = serviceProvider;
this.webSocketManager = webSocketManager;
}
public async Task OnConnected(WebSocketConnection webSocketConnection)
{
await webSocketConnection.SendAction("authentication");
}
public async Task OnDisconnected(WebSocketConnection webSocketConnection)
{
webSocketManager.RemoveSocket(webSocketConnection.Id);
if (webSocketConnection.CloseStatus.HasValue)
{
await webSocketConnection.WebSocket.CloseAsync(webSocketConnection.CloseStatus.Value, webSocketConnection.CloseStatusDescription, CancellationToken.None);
}
}
public async Task OnReceiveMessage(WebSocketConnection webSocketConnection)
{
try
{
byte[] receivePayloadBuffer = new byte[4 * 1024];
WebSocketReceiveResult webSocketReceiveResult = await webSocketConnection.WebSocket.ReceiveAsync(new ArraySegment<byte>(receivePayloadBuffer), webSocketConnection.GetCancellationToken());
webSocketConnection.ResetCancelationToken();
while (webSocketReceiveResult.MessageType != WebSocketMessageType.Close)
{
byte[] result = await ReceiveMessagePayloadAsync(webSocketConnection.WebSocket, webSocketReceiveResult, receivePayloadBuffer);
try
{
Actions.Action action = JsonConvert.DeserializeObject<Actions.Action>(Encoding.UTF8.GetString(result, 0, result.Length));
if (webSocketConnection.Authentication)
{
ActionFactory.CreateActionHandler(action, webSocketConnection, serviceProvider).HandleAction();
}
else
{
ActionFactory.CreateAuthActionHandler(action, webSocketConnection, serviceProvider).HandleAction();
}
}
/*catch (JsonReaderException e)
{
var properties = new JObject { { "message", "Invalid message format sent" } };
await webSocketConnection.sendAction("error", properties);
}
*/
catch(Exception e)
{
if (e is NotImplementedException)
{
var properties = new JObject { { "message", "This API version does not support this action yet" } };
await webSocketConnection.SendAction("error", properties);
}
else if (e is JsonReaderException)
{
var properties = new JObject { { "message", "Invalid message format sent" } };
await webSocketConnection.SendAction("error", properties);
}
}
webSocketReceiveResult = await webSocketConnection.WebSocket.ReceiveAsync(new ArraySegment<byte>(receivePayloadBuffer), webSocketConnection.GetCancellationToken());
webSocketConnection.ResetCancelationToken();
}
webSocketConnection.CloseStatus = webSocketReceiveResult.CloseStatus.Value;
webSocketConnection.CloseStatusDescription = webSocketReceiveResult.CloseStatusDescription;
}
/*catch (WebSocketException wsex) when (wsex.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
{
}
catch (OperationCanceledException oce)
{
}
*/
catch
{
}
}
private static async Task<byte[]> ReceiveMessagePayloadAsync(System.Net.WebSockets.WebSocket webSocket, WebSocketReceiveResult webSocketReceiveResult, byte[] receivePayloadBuffer)
{
byte[] messagePayload = null;
if (webSocketReceiveResult.EndOfMessage)
{
messagePayload = new byte[webSocketReceiveResult.Count];
Array.Copy(receivePayloadBuffer, messagePayload, webSocketReceiveResult.Count);
}
else
{
using (MemoryStream messagePayloadStream = new MemoryStream())
{
messagePayloadStream.Write(receivePayloadBuffer, 0, webSocketReceiveResult.Count);
while (!webSocketReceiveResult.EndOfMessage)
{
webSocketReceiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receivePayloadBuffer), CancellationToken.None);
messagePayloadStream.Write(receivePayloadBuffer, 0, webSocketReceiveResult.Count);
}
messagePayload = messagePayloadStream.ToArray();
}
}
return messagePayload;
}
}
}

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Concurrent;
using System.Linq;
namespace Syski.WebSocket.Services.WebSockets
{
public class WebSocketManager
{
private ConcurrentDictionary<Guid, WebSocketConnection> webSockets = new ConcurrentDictionary<Guid, WebSocketConnection>();
private ConcurrentDictionary<Guid, Guid> webSocketSystem = new ConcurrentDictionary<Guid, Guid>();
public WebSocketManager()
{
}
public ConcurrentDictionary<Guid, WebSocketConnection> GetWebSockets()
{
return webSockets;
}
public WebSocketConnection GetSocketById(Guid id)
{
return webSockets.FirstOrDefault(p => p.Key == id).Value;
}
public Guid GetId(WebSocketConnection webSocketConnection)
{
return webSockets.FirstOrDefault(p => p.Value == webSocketConnection).Key;
}
public Guid GetSystemId(Guid webSocketConnectionId)
{
webSocketSystem.TryGetValue(webSocketConnectionId, out Guid result);
return result;
}
public void AddSocket(Guid webSocketConnectionId, WebSocketConnection webSocketConnection)
{
webSockets.TryAdd(webSocketConnectionId, webSocketConnection);
}
public void SetSystemLink(Guid webSocketConnectionId, Guid SystemId)
{
webSocketSystem.TryAdd(webSocketConnectionId, SystemId);
}
public void RemoveSocket(Guid webSocketConnectionId)
{
webSockets.TryRemove(webSocketConnectionId, out WebSocketConnection webSocketConnection);
webSocketSystem.TryRemove(webSocketConnectionId, out Guid systemId);
}
}
}

View File

@@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets
{
public class WebSocketMiddleware
{
private readonly RequestDelegate next;
private readonly IWebSocketHandler webSocketHandler;
public WebSocketMiddleware(RequestDelegate next, IWebSocketHandler webSocketHandler)
{
this.next = next;
this.webSocketHandler = webSocketHandler;
}
public async Task Invoke(HttpContext context)
{
if (context.WebSockets.IsWebSocketRequest)
{
var webSocket = await context.WebSockets.AcceptWebSocketAsync();
WebSocketConnection webSocketConnection = new WebSocketConnection(webSocket);
await webSocketHandler.OnConnected(webSocketConnection);
await webSocketHandler.OnReceiveMessage(webSocketConnection);
await webSocketHandler.OnDisconnected(webSocketConnection);
}
else
{
await next.Invoke(context);
}
}
}
}

View File

@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Builder;
namespace Syski.WebSocket.Services.WebSockets
{
public static class WebSocketMiddlewareExtensions
{
public static IApplicationBuilder UseWebSocketMiddleware(this IApplicationBuilder app)
{
app.UseMiddleware<WebSocketMiddleware>();
return app;
}
}
}

View File

@@ -0,0 +1,70 @@
using Microsoft.Extensions.Hosting;
using Syski.Data;
using Syski.WebSocket.Services.WebSockets.Actions.Tasks;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Syski.WebSocket.Services.WebSockets
{
public class WebSocketTaskScheduler : IHostedService
{
private readonly WebSocketManager webSocketManager;
private readonly IServiceProvider serviceProvider;
private List<Timer> timers = new List<Timer>();
public WebSocketTaskScheduler(WebSocketManager webSocketManager, IServiceProvider serviceProvider)
{
this.webSocketManager = webSocketManager;
this.serviceProvider = serviceProvider;
}
public Task StartAsync(CancellationToken cancellationToken)
{
timers.Add(new Timer(SendAction, new CommandTask(serviceProvider), TimeSpan.Zero, TimeSpan.FromSeconds(1)));
timers.Add(new Timer(SendAction, new VariablePingTask(serviceProvider), TimeSpan.Zero, TimeSpan.FromSeconds(10)));
timers.Add(new Timer(SendAction, new DefaultTask("variablecpu", serviceProvider), TimeSpan.Zero, TimeSpan.FromSeconds(3)));
timers.Add(new Timer(SendAction, new DefaultTask("variableram", serviceProvider), TimeSpan.Zero, TimeSpan.FromSeconds(3)));
timers.Add(new Timer(SendAction, new DefaultTask("variablestorage", serviceProvider), TimeSpan.Zero, TimeSpan.FromSeconds(3)));
//timers.Add(new Timer(SendAction, new DefaultTask("variablenetwork", serviceProvider), TimeSpan.Zero, TimeSpan.FromSeconds(3)));
timers.Add(new Timer(SendAction, new DefaultTask("processes", serviceProvider), TimeSpan.Zero, TimeSpan.FromSeconds(30)));
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
foreach (Timer timer in timers)
{
timer?.Change(Timeout.Infinite, 0);
}
return Task.CompletedTask;
}
public void Dispose()
{
foreach (Timer timer in timers)
{
timer?.Dispose();
}
}
private void SendAction(object state)
{
ActionTask actionTask = (ActionTask) state;
foreach (var webSocketConnection in webSocketManager.GetWebSockets())
{
try
{
actionTask.ExecuteActionTask(webSocketConnection.Value);
}
catch
{
}
}
}
}
}

View File

@@ -0,0 +1,112 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Syski.Data;
using Syski.WebSocket.Services.WebSockets;
using System;
namespace Syski.WebSocket
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Make all the urls lowercase as this is good web practice
services.AddRouting(options => options.LowercaseUrls = true);
// Load the connection string from the settings file and use it for storing data
services.AddDbContext<SyskiDBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
);
// Add Identity to the application
services.AddDefaultIdentity<ApplicationUser>()
.AddEntityFrameworkStores<SyskiDBContext>();
services.AddHostedService<WebSocketTaskScheduler>();
services.AddTransient<IWebSocketHandler, WebSocketHandler>();
services.AddSingleton<Services.WebSockets.WebSocketManager>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
// Check if behind a reverse proxy if so use Forwarded Headers for the connection information
try
{
if (Convert.ToBoolean(Configuration["ReverseProxy"]))
{
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
}
}
/*catch (FormatException fe)
{
// Error parsing config, do nothing assume not behind a reverse proxy
}
*/
catch
{
}
// Load WebSocket options from the config file
var wsOptions = new WebSocketOptions();
try
{
wsOptions.KeepAliveInterval = TimeSpan.FromSeconds(Convert.ToInt32(Configuration["WebSocket:KeepAliveInterval"]));
}
catch
{
// Default option of keep alive set to 2 minutes
wsOptions.KeepAliveInterval = TimeSpan.FromSeconds(120);
}
try
{
wsOptions.ReceiveBufferSize = Convert.ToInt32(Configuration["WebSocket:ReceiveBufferSize"]);
}
catch
{
// Default option of buffer set to 4096 bytes
wsOptions.ReceiveBufferSize = 4096;
}
app.UseHttpsRedirection();
app.UseWebSockets(wsOptions);
app.UseWebSocketMiddleware();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Error: Not a websocket");
});
}
}
}

View File

@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.1.7" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\uk.co.syski.data\Syski.Data.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

View File

@@ -0,0 +1,16 @@
{
"ReverseProxy": true,
"WebSocket": {
"KeepAliveInterval": 120,
"ReceiveBufferSize": 4096
},
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=SyskiAPI;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}