aboutsummaryrefslogtreecommitdiff
path: root/backend
diff options
context:
space:
mode:
Diffstat (limited to 'backend')
-rw-r--r--backend/api/api/Controllers/DatasetController.cs14
-rw-r--r--backend/api/api/Controllers/WebSocketController.cs63
-rw-r--r--backend/api/api/Program.cs51
-rw-r--r--backend/api/api/Services/ChatHub.cs49
-rw-r--r--backend/api/api/Services/IChat.cs8
-rw-r--r--backend/api/api/Services/IMlConnectionService.cs2
-rw-r--r--backend/api/api/Services/MLWebSocketService.cs68
-rw-r--r--backend/api/api/Services/MlConnectionService.cs9
8 files changed, 113 insertions, 151 deletions
diff --git a/backend/api/api/Controllers/DatasetController.cs b/backend/api/api/Controllers/DatasetController.cs
index e9c824f9..375b5bfd 100644
--- a/backend/api/api/Controllers/DatasetController.cs
+++ b/backend/api/api/Controllers/DatasetController.cs
@@ -162,6 +162,18 @@ namespace api.Controllers
[Authorize(Roles = "User,Guest")]
public async Task<ActionResult<Dataset>> Post([FromBody] Dataset dataset)
{
+ string uploaderId;
+ var header = Request.Headers[HeaderNames.Authorization];
+ if (AuthenticationHeaderValue.TryParse(header, out var headerValue))
+ {
+ var scheme = headerValue.Scheme;
+ var parameter = headerValue.Parameter;
+ uploaderId = jwtToken.TokenToId(parameter);
+ if (uploaderId == null)
+ return null;
+ }
+ else
+ return BadRequest();
//da li ce preko tokena da se ubaci username ili front salje
//dataset.username = usernameToken;
//username = "" ako je GUEST DODAO
@@ -175,7 +187,7 @@ namespace api.Controllers
FileModel fileModel = _fileService.getFile(dataset.fileId);
dataset.isPreProcess = false;
_datasetService.Create(dataset);
- _mlConnectionService.PreProcess(dataset,fileModel.path);
+ _mlConnectionService.PreProcess(dataset,fileModel.path,uploaderId);
return Ok();
}
}
diff --git a/backend/api/api/Controllers/WebSocketController.cs b/backend/api/api/Controllers/WebSocketController.cs
deleted file mode 100644
index 184b47e7..00000000
--- a/backend/api/api/Controllers/WebSocketController.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-using api.Services;
-using Microsoft.AspNetCore.Http;
-using Microsoft.AspNetCore.Mvc;
-using System.Net.WebSockets;
-
-namespace api.Controllers
-{
- [Route("api")]
- [ApiController]
- public class WebSocketController : ControllerBase
- {
- private IMLWebSocketService mlWS;
- public WebSocketController(IMLWebSocketService mlWS)
- {
- this.mlWS = mlWS;
- }
-
- [HttpGet("wstest")]
- public string Test()
- {
- this.mlWS.Send("ABC123");
- return "MESSAGE SENT!";
- }
-
- [HttpGet("ws")]
- public async Task Get()
- {
- if (HttpContext.WebSockets.IsWebSocketRequest)
- {
- using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
- await Echo(webSocket);
- }
- else
- {
- HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
- }
- }
-
- private static async Task Echo(WebSocket webSocket)
- {
- var buffer = new byte[1024 * 4];
- var receiveResult = await webSocket.ReceiveAsync(
- new ArraySegment<byte>(buffer), CancellationToken.None);
-
- while (!receiveResult.CloseStatus.HasValue)
- {
- await webSocket.SendAsync(
- new ArraySegment<byte>(buffer, 0, receiveResult.Count),
- receiveResult.MessageType,
- receiveResult.EndOfMessage,
- CancellationToken.None);
-
- receiveResult = await webSocket.ReceiveAsync(
- new ArraySegment<byte>(buffer), CancellationToken.None);
- }
-
- await webSocket.CloseAsync(
- receiveResult.CloseStatus.Value,
- receiveResult.CloseStatusDescription,
- CancellationToken.None);
- }
- }
-}
diff --git a/backend/api/api/Program.cs b/backend/api/api/Program.cs
index 2d6dcfbb..6f1116d9 100644
--- a/backend/api/api/Program.cs
+++ b/backend/api/api/Program.cs
@@ -36,14 +36,13 @@ builder.Services.AddScoped<IPredictorService, PredictorService>();
builder.Services.AddScoped<IFileService, FileService>();
builder.Services.AddScoped<IJwtToken, JwtToken>();
builder.Services.AddScoped<IExperimentService, ExperimentService>();
+builder.Services.AddScoped<IChat,ChatHub>();
+builder.Services.AddHostedService<TempFileService>();
+builder.Services.AddHostedService<FillAnEmptyDb>();
+
-var mlwss = new MLWebSocketService();
-builder.Services.AddSingleton<IMLWebSocketService>(mlwss);
-builder.Services.AddHostedService(_ => mlwss);
-builder.Services.AddHostedService<TempFileService>();
-builder.Services.AddHostedService<FillAnEmptyDb>();
//Add Authentication
builder.Services.AddAuthentication(
@@ -63,32 +62,54 @@ builder.Services.Configure<FormOptions>(x =>
x.MultipartBodyLengthLimit = int.MaxValue;
});
+builder.Services.AddSignalR();
builder.Services.AddControllers();
+builder.Services.AddCors(options =>
+{
+ options.AddPolicy("CorsPolicy", builder => builder
+ .WithOrigins("http://localhost:4200")
+ .AllowAnyMethod()
+ .AllowAnyHeader()
+ .AllowCredentials());
+});
+
+
+
var app = builder.Build();
-var webSocketOptions = new WebSocketOptions
+
+app.UseWebSockets(new WebSocketOptions
{
- KeepAliveInterval = TimeSpan.FromMinutes(2)
-};
+ KeepAliveInterval = TimeSpan.FromSeconds(120)
+});
+
+
+
-app.UseWebSockets(webSocketOptions);
//Add Cors
-app.UseCors(
- x=>x.AllowAnyOrigin()
- .AllowAnyMethod()
- .AllowAnyHeader()
- );
+app.UseCors("CorsPolicy");
// Configure the HTTP request pipeline.
//Add Authentication
app.UseAuthentication();
+
+
+app.UseRouting();
app.UseAuthorization();
+app.UseEndpoints(endpoints =>
+{
+ endpoints.MapControllers();
+ endpoints.MapHub<ChatHub>("/chatHub");
+});
+
+
+
+
-app.MapControllers();
app.Run();
diff --git a/backend/api/api/Services/ChatHub.cs b/backend/api/api/Services/ChatHub.cs
new file mode 100644
index 00000000..49466273
--- /dev/null
+++ b/backend/api/api/Services/ChatHub.cs
@@ -0,0 +1,49 @@
+using api.Models;
+using Microsoft.AspNetCore.SignalR;
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.Threading.Tasks;
+
+
+
+namespace api.Services
+{
+ public class ChatHub :Hub,IChat
+ {
+ static readonly Dictionary<string,string> Users=new Dictionary<string,string>();
+ private readonly IJwtToken _tokenService;
+ public ChatHub(IJwtToken tokenService)
+ {
+ _tokenService=tokenService;
+ }
+
+ public override async Task OnConnectedAsync()
+ {
+ string token=Context.GetHttpContext().Request.Query["access_token"];
+ string id=_tokenService.TokenToId(token);
+ Users.Add(id,Context.ConnectionId);
+ //await Send(id,Context.ConnectionId);
+ await SendDirect(id, "poruka");
+ await base.OnConnectedAsync();
+
+ }
+ public override async Task OnDisconnectedAsync(Exception? exception)
+ {
+ string id = Users.FirstOrDefault(u => u.Key == Context.ConnectionId).Value;
+ Users.Remove(id);
+ }
+ public async Task SendDirect(string id,string message)
+ {
+ if (Users[id]==null)
+ return;
+
+ await Clients.Client(Users[id]).SendAsync("Notify",message);
+ }
+ public async Task Send(string message)
+ {
+ await Clients.All.SendAsync("Notify",message);
+ }
+ }
+
+
+}
diff --git a/backend/api/api/Services/IChat.cs b/backend/api/api/Services/IChat.cs
new file mode 100644
index 00000000..8a905868
--- /dev/null
+++ b/backend/api/api/Services/IChat.cs
@@ -0,0 +1,8 @@
+namespace api.Services
+{
+ public interface IChat
+ {
+ Task SendDirect(string id, string message);
+ Task Send(string message);
+ }
+} \ No newline at end of file
diff --git a/backend/api/api/Services/IMlConnectionService.cs b/backend/api/api/Services/IMlConnectionService.cs
index 5edc5554..9a9a81f4 100644
--- a/backend/api/api/Services/IMlConnectionService.cs
+++ b/backend/api/api/Services/IMlConnectionService.cs
@@ -6,7 +6,7 @@ namespace api.Services
public interface IMlConnectionService
{
Task<string> SendModelAsync(object model, object dataset);
- Task PreProcess(Dataset dataset, string filePath);
+ Task PreProcess(Dataset dataset, string filePath,string id);
Task TrainModel(Model model, Experiment experiment, string filePath);
//Task<Dataset> PreProcess(Dataset dataset, byte[] file, string filename);
}
diff --git a/backend/api/api/Services/MLWebSocketService.cs b/backend/api/api/Services/MLWebSocketService.cs
deleted file mode 100644
index ca6919bf..00000000
--- a/backend/api/api/Services/MLWebSocketService.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-using System.Net.WebSockets;
-using System.Text;
-
-namespace api.Services
-{
- public class MLWebSocketService: BackgroundService, IMLWebSocketService
- {
- private static readonly string Connection = "ws://localhost:5027";
-
- private Queue<string> dataQueue = new Queue<string>();
-
- protected override async Task ExecuteAsync(CancellationToken stoppingToken)
- {
- while (!stoppingToken.IsCancellationRequested)
- using (var socket = new ClientWebSocket())
- try
- {
- await socket.ConnectAsync(new Uri(Connection), stoppingToken);
-
-
- while(dataQueue.Count > 0)
- {
- await Send(socket, dataQueue.Dequeue(), stoppingToken);
- }
-
- Receive(socket, stoppingToken);
-
- await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", stoppingToken);
- }
- catch (Exception ex)
- {
- Console.WriteLine($"ERROR - {ex.Message}");
- }
- }
-
- private async Task Send(ClientWebSocket socket, string data, CancellationToken stoppingToken) =>
- await socket.SendAsync(Encoding.UTF8.GetBytes(data), WebSocketMessageType.Text, true, stoppingToken);
-
- private async Task Receive(ClientWebSocket socket, CancellationToken stoppingToken)
- {
- var buffer = new ArraySegment<byte>(new byte[2048]);
- while (!stoppingToken.IsCancellationRequested)
- {
- WebSocketReceiveResult result;
- using (var ms = new MemoryStream())
- {
- do
- {
- result = await socket.ReceiveAsync(buffer, stoppingToken);
- ms.Write(buffer.Array, buffer.Offset, result.Count);
- } while (!result.EndOfMessage);
-
- if (result.MessageType == WebSocketMessageType.Close)
- break;
-
- ms.Seek(0, SeekOrigin.Begin);
- using (var reader = new StreamReader(ms, Encoding.UTF8))
- Console.WriteLine(await reader.ReadToEndAsync());
- }
- };
- }
-
- public void Send(string data)
- {
- dataQueue.Enqueue(data);
- }
- }
-}
diff --git a/backend/api/api/Services/MlConnectionService.cs b/backend/api/api/Services/MlConnectionService.cs
index fb42965b..8523a3ac 100644
--- a/backend/api/api/Services/MlConnectionService.cs
+++ b/backend/api/api/Services/MlConnectionService.cs
@@ -3,6 +3,7 @@ using RestSharp;
using System.Net.WebSockets;
using System.Text;
using Newtonsoft.Json;
+using Microsoft.AspNetCore.SignalR;
namespace api.Services
{
@@ -11,11 +12,13 @@ namespace api.Services
private RestClient client;
private readonly IDatasetService _datasetService;
private readonly IModelService _modelService;
+ private readonly IChat _chat;
- public MlConnectionService(IDatasetService datasetService)
+ public MlConnectionService(IDatasetService datasetService,IChat chat)
{
this.client = new RestClient("http://127.0.0.1:5543");
_datasetService=datasetService;
+ _chat=chat;
}
public async Task<string> SendModelAsync(object model, object dataset)//Don't Use
@@ -42,7 +45,7 @@ namespace api.Services
return;
}
- public async Task PreProcess(Dataset dataset,string filePath)//(Dataset dataset,byte[] file,string filename)
+ public async Task PreProcess(Dataset dataset,string filePath,string id)//(Dataset dataset,byte[] file,string filename)
{
var request=new RestRequest("preprocess", Method.Post);
request.AddParameter("dataset", JsonConvert.SerializeObject(dataset));
@@ -54,7 +57,7 @@ namespace api.Services
Dataset newDataset = JsonConvert.DeserializeObject<Dataset>(result.Content);
newDataset.isPreProcess = true;
_datasetService.Update(newDataset);
-
+ await _chat.SendDirect(id, "Procesed dataset with name "+newDataset.name);
return;
}