leave report

This commit is contained in:
Suphonchai Phoonsawat 2025-09-02 14:55:07 +07:00
parent 3ae9be5869
commit 8001dd0c11
12 changed files with 678 additions and 244 deletions

View file

@ -1,71 +1,63 @@
using Microsoft.Extensions.Hosting;
using Quobject.SocketIoClientDotNet.Client;
using Sentry;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System;
using BMA.EHR.Insignia.Service.Configuration;
using SocketIOClient;
using System.Security.Claims;
namespace BMA.EHR.Insignia.Service.Services;
public class InsigniaRequestProcessService : BackgroundService
{
private readonly IBackgroundTaskQueue _queue;
private Socket _socket;
private bool _isConnected = false;
public InsigniaRequestProcessService(IBackgroundTaskQueue queue)
private readonly IHttpContextAccessor _httpContextAccessor;
public InsigniaRequestProcessService(
IBackgroundTaskQueue queue,
IHttpContextAccessor httpContextAccessor)
{
_queue = queue;
_httpContextAccessor = httpContextAccessor;
}
public override Task StartAsync(CancellationToken cancellationToken)
#region " Properties "
protected string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
protected string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
protected bool? IsPlacementAdmin => _httpContextAccessor?.HttpContext?.User?.IsInRole("placement1");
protected string? AccessToken => _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"];
#endregion
public override async Task StartAsync(CancellationToken cancellationToken)
{
try
var client = new SocketIO("https://bma-ehr.frappet.synology.me/api/v1/org-socket",
new SocketIOOptions
{
// เพิ่ม token ใน handshake.auth
Auth = new { token = AccessToken ?? "" }
});
client.OnConnected += async (sender, e) =>
{
_socket = IO.Socket("https://bma-ehr.frappet.synology.me", new IO.Options
{
Path = "/api/v1/org-socket",
//Query = new Dictionary<string, string>
//{
// { "EIO", "4" },
// { "transport", "polling" },
// { "t", "tkitfptn" }
//}
});
Console.WriteLine("Connected to Socket.IO server");
await client.EmitAsync("eventName", "Hello from .NET client");
};
_socket.On(Socket.EVENT_CONNECT, () =>
{
_isConnected = true;
Console.WriteLine("Connected to WebSocket server at: https://bma-ehr.frappet.synology.me/api/v1/org-socket");
});
await client.ConnectAsync();
_socket.On(Socket.EVENT_DISCONNECT, () =>
{
_isConnected = false;
Console.WriteLine("Disconnected from WebSocket server");
});
_socket.On(Socket.EVENT_ERROR, (data) =>
{
_isConnected = false;
Console.WriteLine($"WebSocket error: {data}");
});
_socket.Connect();
}
catch (Exception ex)
{
_isConnected = false;
Console.WriteLine($"Failed to initialize WebSocket connection: {ex.Message}");
}
return base.StartAsync(cancellationToken);
await base.StartAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var userId = "4064c2b2-0414-464a-97c6-4a47c325b9a3";
while (!stoppingToken.IsCancellationRequested)
{
@ -74,80 +66,34 @@ public class InsigniaRequestProcessService : BackgroundService
var workItem = await _queue.DequeueAsync(stoppingToken);
if (workItem != null)
{
Console.WriteLine($"Starting background task at: {DateTime.Now}");
await workItem(stoppingToken);
Console.WriteLine($"Finished background task at: {DateTime.Now}");
var startTime = DateTime.Now;
await workItem(stoppingToken);
var endTime = DateTime.Now;
var duration = endTime - startTime;
// Send notification to WebSocket after task completion
if (_socket != null && _isConnected)
{
_socket.Emit("send-command-notification",
new
{
success = true,
message = "Background Task Completed Successfully",
payload = new {
completedAt = DateTime.Now,
taskType = "background_processing"
}
},
new
{
userId = userId
});
Console.WriteLine("WebSocket notification sent successfully");
}
else
{
Console.WriteLine("WebSocket is not connected. Unable to send notification.");
}
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
Console.WriteLine($"Error processing background task: {ex.Message}");
// Send error notification to WebSocket
if (_socket != null && _isConnected)
{
_socket.Emit("send-command-notification",
new
{
success = false,
message = "Background Task Failed",
payload = new {
error = ex.Message,
failedAt = DateTime.Now,
taskType = "background_processing"
}
},
new
{
userId = userId
});
}
// รอสักครู่ก่อนประมวลผล task ถัดไป เพื่อป้องกันการวนลูปข้อผิดพลาด
await Task.Delay(1000, stoppingToken);
}
}
}
public override Task StopAsync(CancellationToken cancellationToken)
public override async Task StopAsync(CancellationToken cancellationToken)
{
try
{
if (_socket != null)
{
Console.WriteLine("Disconnecting from WebSocket server...");
_socket.Disconnect();
_isConnected = false;
_socket = null;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error disconnecting WebSocket: {ex.Message}");
}
return base.StopAsync(cancellationToken);
await base.StopAsync(cancellationToken);
}
}