165 lines
No EOL
5.2 KiB
C#
165 lines
No EOL
5.2 KiB
C#
using Microsoft.Extensions.Configuration;
|
|
using RabbitMQ.Client;
|
|
using RabbitMQ.Client.Events;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
|
|
var basePath = Directory.GetCurrentDirectory();
|
|
var configuration = new ConfigurationBuilder()
|
|
.SetBasePath(basePath)
|
|
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
|
|
.Build();
|
|
|
|
WriteToConsole("Consumer Start!");
|
|
|
|
// Wait until 8:00 AM before starting to consume messages
|
|
await WaitUntil8AM();
|
|
|
|
var host = configuration["Rabbit:Host"] ?? "";
|
|
var user = configuration["Rabbit:User"] ?? "";
|
|
var pass = configuration["Rabbit:Password"] ?? "";
|
|
var queue = configuration["Rabbit:Queue"] ?? "basic-queue";
|
|
|
|
// create connection
|
|
var factory = new ConnectionFactory()
|
|
{
|
|
//Uri = new Uri("amqp://admin:P@ssw0rd@192.168.4.11:5672")
|
|
HostName = host,// หรือ hostname ของ RabbitMQ Server ที่คุณใช้
|
|
UserName = user, // ใส่ชื่อผู้ใช้ของคุณ
|
|
Password = pass // ใส่รหัสผ่านของคุณ
|
|
};
|
|
|
|
using var connection = factory.CreateConnection();
|
|
using var channel = connection.CreateModel();
|
|
|
|
//channel.QueueDeclare(queue: "bma-checkin-queue", durable: true, exclusive: false, autoDelete: false, arguments: null);
|
|
channel.QueueDeclare(queue: queue, durable: true, exclusive: false, autoDelete: false, arguments: null);
|
|
|
|
var consumer = new EventingBasicConsumer(channel);
|
|
|
|
consumer.Received += async (model, ea) =>
|
|
{
|
|
var body = ea.Body.ToArray();
|
|
var message = Encoding.UTF8.GetString(body);
|
|
await CallRestApi(message);
|
|
|
|
// convert string into object
|
|
//var request = JsonConvert.DeserializeObject<CheckInRequest>(message);
|
|
//using (var db = new ApplicationDbContext())
|
|
//{
|
|
// var item = new AttendantItem
|
|
// {
|
|
// Name = request.Name,
|
|
// CheckInDateTime = request.CheckInDateTime,
|
|
// };
|
|
// db.AttendantItems.Add(item);
|
|
// db.SaveChanges();
|
|
|
|
// WriteToConsole($"ได้รับคำขอจาก Queue: {message}");
|
|
// WriteToConsole($"ตอบกลับจาก REST API: {JsonConvert.SerializeObject(item)}");
|
|
//}
|
|
|
|
WriteToConsole($"ได้รับคำขอจาก Queue: {message}");
|
|
//WriteToConsole($"ตอบกลับจาก REST API: {JsonConvert.SerializeObject(item)}");
|
|
};
|
|
|
|
//channel.BasicConsume(queue: "bma-checkin-queue", autoAck: true, consumer: consumer);
|
|
channel.BasicConsume(queue: queue, autoAck: true, consumer: consumer);
|
|
|
|
//Console.WriteLine("\nPress 'Enter' to exit the process...");
|
|
|
|
await Task.Delay(-1);
|
|
|
|
static void WriteToConsole(string message)
|
|
{
|
|
Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} : {message}");
|
|
}
|
|
|
|
async Task CallRestApi(string requestData)
|
|
{
|
|
using var client = new HttpClient();
|
|
var apiPath = $"{configuration["API"]}/leave/process-check-in";
|
|
|
|
var content = new StringContent(requestData, Encoding.UTF8, "application/json");
|
|
|
|
var response = await client.PostAsync(apiPath, content);
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
var responseContent = await response.Content.ReadAsStringAsync();
|
|
WriteToConsole(responseContent);
|
|
}
|
|
else
|
|
{
|
|
var errorMessage = await response.Content.ReadAsStringAsync();
|
|
var res = JsonSerializer.Deserialize<ResponseObject>(errorMessage);
|
|
WriteToConsole($"Error: {res.Message}");
|
|
}
|
|
}
|
|
|
|
async Task WaitUntil8AM()
|
|
{
|
|
// Get current time in Bangkok timezone
|
|
var bangkokTimeZone = TimeZoneInfo.FindSystemTimeZoneById("SE Asia Standard Time");
|
|
var currentTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, bangkokTimeZone);
|
|
|
|
var targetTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 8, 10, 0);
|
|
|
|
// If current time is already past 8:10 AM today, start immediately
|
|
if (currentTime >= targetTime)
|
|
{
|
|
WriteToConsole($"Current time is {currentTime:HH:mm:ss}. Starting consumer immediately.");
|
|
return;
|
|
}
|
|
|
|
// Calculate time to wait
|
|
var timeToWait = targetTime - currentTime;
|
|
WriteToConsole($"Current time is {currentTime:HH:mm:ss}. Waiting until 08:10:00 to start consuming messages.");
|
|
WriteToConsole($"Time to wait: {timeToWait.Hours} hours, {timeToWait.Minutes} minutes, {timeToWait.Seconds} seconds");
|
|
|
|
await Task.Delay(timeToWait);
|
|
WriteToConsole("It's now 08:10:00. Starting to consume messages from queue.");
|
|
}
|
|
|
|
|
|
public class ResponseObject
|
|
{
|
|
[JsonPropertyName("status")]
|
|
public int Status { get; set; }
|
|
|
|
[JsonPropertyName("message")]
|
|
public string? Message { get; set; }
|
|
|
|
[JsonPropertyName("result")]
|
|
public object? Result { get; set; }
|
|
}
|
|
|
|
public class CheckTimeDtoRB
|
|
{
|
|
public Guid? CheckInId { get; set; }
|
|
|
|
|
|
public double Lat { get; set; } = 0;
|
|
|
|
|
|
public double Lon { get; set; } = 0;
|
|
|
|
|
|
public string POI { get; set; } = string.Empty;
|
|
|
|
|
|
public bool IsLocation { get; set; } = true;
|
|
|
|
public string? LocationName { get; set; } = string.Empty;
|
|
|
|
public string? Remark { get; set; } = string.Empty;
|
|
|
|
public Guid? UserId { get; set; }
|
|
|
|
public DateTime? CurrentDate { get; set; }
|
|
|
|
public string? CheckInFileName { get; set; }
|
|
|
|
public byte[]? CheckInFileBytes { get; set; }
|
|
} |