refactor: Переработал управление константами и путями к данным

This commit is contained in:
2026-02-01 08:34:07 +03:00
parent a9c0bb1d52
commit c3535cafe9
6 changed files with 46 additions and 29 deletions

View File

@@ -8,5 +8,4 @@ public static class GlobalConsts
public static readonly JsonSerializerOptions JsonSerializerOptions = new()
{ PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
public static string JwtFilePath { get; set; } = "data/jwt.txt";
}

View File

@@ -0,0 +1,30 @@
namespace SfeduSchedule;
public static class AppConsts
{
// Quartz Jobs Cron expressions
public const string UpdateJwtCronEnv = "UPDATE_JWT_CRON";
public const string UpdateEmployeeCronEnv = "UPDATE_EMPLOYEES_CRON";
// Modeus
public const string PreinstalledJwtTokenEnv = "TOKEN";
public const string ModeusUrlEnv = "MODEUS_URL";
public const string ModeusDefaultUrl = "https://sfedu.modeus.org/";
// Telegram
public const string TgChatIdEnv = "TG_CHAT_ID";
public const string TgTokenEnv = "TG_TOKEN";
// RateLimiter
public const string PermitLimitEnv = "PERMIT_LIMIT";
public const string TimeLimitEnv = "TIME_LIMIT";
// MS Auth
public const string AuthUrlEnv = "AUTH_URL";
public const string AuthApiKeyEnv = "AUTH_API_KEY";
// File paths
public const string JwtFileName = "jwt.txt";
public const string EmployeesFileName = "employees.json";
public const string DataFolderName = "Data";
}

View File

@@ -44,10 +44,14 @@ public class ScheduleController(ModeusService modeusService, ModeusEmployeeServi
/// <response code="200">Возвращает список сотрудников с их GUID</response>
/// <response code="404">Сотрудник не найден</response>
/// <response code="401">Неавторизованный</response>
/// <response code="503">Сервис сотрудников не инициализирован</response>
[HttpGet]
[Route("searchemployee")]
public async Task<IActionResult> SearchEmployees([Required][MinLength(1)] string fullname)
{
if (!modeusEmployeeService.IsInitialized())
return StatusCode(503, "Сервис сотрудников не инициализирован, попробуйте позже.");
var employees = await modeusEmployeeService.GetEmployees(fullname, 10);
if (employees.Count == 0)
return NotFound();

View File

@@ -8,8 +8,7 @@ public class UpdateJwtJob(
IConfiguration configuration,
ILogger<UpdateJwtJob> logger,
IHttpClientFactory httpClientFactory,
ModeusHttpClient modeusHttpClient,
ModeusService modeusService) : IJob
ModeusHttpClient modeusHttpClient) : IJob
{
private const int MaxAttempts = 5; // Максимальное число попыток
private const int DelaySeconds = 20; // Задержка между попытками в секундах
@@ -19,8 +18,8 @@ public class UpdateJwtJob(
{
logger.LogInformation("Начало выполнения UpdateJwtJob");
var authUrl = configuration["AUTH_URL"] ?? "http://msauth:8080/auth/ms";
var apiKey = configuration["AUTH_API_KEY"] ?? string.Empty;
var authUrl = configuration[AppConsts.AuthUrlEnv] ?? "http://msauth:8080/auth/ms";
var apiKey = configuration[AppConsts.AuthApiKeyEnv] ?? string.Empty;
var client = httpClientFactory.CreateClient("authClient");
client.Timeout = TimeSpan.FromSeconds(TimeoutSeconds + 10);
@@ -72,7 +71,7 @@ public class UpdateJwtJob(
configuration["TOKEN"] = body.Jwt;
modeusHttpClient.SetToken(body.Jwt);
await File.WriteAllTextAsync(GlobalConsts.JwtFilePath,
await File.WriteAllTextAsync(Path.Combine(Path.Combine(AppContext.BaseDirectory, AppConsts.DataFolderName), AppConsts.JwtFileName),
body.Jwt + "\n" + DateTime.Now.ToString("O"), cts.Token);
logger.LogInformation("JWT успешно обновлён");
return;

View File

@@ -1,13 +1,14 @@
using SfeduSchedule.Logging;
using SfeduSchedule.Logging;
namespace SfeduSchedule.Services;
public class ModeusEmployeeService(ILogger<ModeusEmployeeService> logger, ModeusService modeusService)
public class ModeusEmployeeService(ISchedulerFactory schedulerFactory)
: IHostedService
{
private Dictionary<string, (string, List<string>)> _employees = [];
private Task? _backgroundTask;
private CancellationTokenSource? _cts;
private readonly string _employeesFilePath = Path.Combine(Path.Combine(AppContext.BaseDirectory, AppConsts.DataFolderName), AppConsts.EmployeesFileName);
public async Task<Dictionary<string, (string, List<string>)>> GetEmployees(string fullname, int size = 10)
{
@@ -17,6 +18,11 @@ public class ModeusEmployeeService(ILogger<ModeusEmployeeService> logger, Modeus
.ToDictionary(e => e.Key, e => e.Value);
}
public bool IsInitialized()
{
return _employees.Count > 0;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

View File

@@ -1,21 +0,0 @@
@SfeduSchedule_HostAddress = http://localhost:5087
###
[Получить расписание по списку GUID]
GET {{SfeduSchedule_HostAddress}}/api/schedule?attendeePersonId={{guid1}}&attendeePersonId={{guid2}}
Accept: application/json
###
[Получить расписание через POST]
POST {{SfeduSchedule_HostAddress}}/api/schedule
Content-Type: application/json
Accept: application/json
{
"maxResults": 500,
"startDate": "2025-08-31T00:00:00Z",
"endDate": "2025-09-20T00:00:00Z",
"attendeePersonId": ["{{guid1}}", "{{guid2}}"]
}
###