Compare commits
8 Commits
ed9717df07
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| f08d6af4c7 | |||
| 46bdc07910 | |||
| 46c50dc8e2 | |||
| c3535cafe9 | |||
| a9c0bb1d52 | |||
| 0b9e6d3c95 | |||
| fa8418aedb | |||
| 50ca622b3e |
@@ -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";
|
||||
}
|
||||
30
SfeduSchedule/AppConsts.cs
Normal file
30
SfeduSchedule/AppConsts.cs
Normal 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";
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
78
SfeduSchedule/Jobs/UpdateEmployeesJob.cs
Normal file
78
SfeduSchedule/Jobs/UpdateEmployeesJob.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using Quartz;
|
||||
using SfeduSchedule.Logging;
|
||||
using SfeduSchedule.Services;
|
||||
|
||||
namespace SfeduSchedule.Jobs;
|
||||
|
||||
// TODO: Обновляет список сотрудников из modeus и сохраняет в локальный файл
|
||||
// TODO: Нужно вынести функционал обновления сюда, а в сервисе оставить только загрузку с диска
|
||||
// TODO: Нужно настроить выполнение задачи на часов 10 утра каждый день
|
||||
// TODO: Нужно обработать событие когда данные о сотрудниках запрашиваются до первого обновления
|
||||
|
||||
public class UpdateEmployeesJob(
|
||||
ILogger<UpdateEmployeesJob> logger,
|
||||
ModeusEmployeeService employeeService,
|
||||
ModeusService modeusService) : IJob
|
||||
{
|
||||
private const int MaxAttempts = 5; // Максимальное число попыток
|
||||
private const int DelaySeconds = 50; // Задержка между попытками в секундах
|
||||
private const int TimeoutSeconds = 60; // Таймаут для каждого запроса в секундах
|
||||
|
||||
public async Task Execute(IJobExecutionContext jobContext)
|
||||
{
|
||||
logger.LogInformation("Начало выполнения UpdateEmployeesJob");
|
||||
|
||||
for (var attempt = 1; attempt <= MaxAttempts; attempt++)
|
||||
try
|
||||
{
|
||||
logger.LogInformation("Попытка {Attempt}/{MaxAttempts} получения списка сотрудников из Modeus", attempt,
|
||||
MaxAttempts);
|
||||
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(TimeoutSeconds));
|
||||
|
||||
var employees = await modeusService.GetEmployeesAsync(cts.Token);
|
||||
if (employees.Count == 0)
|
||||
{
|
||||
logger.LogWarningHere("Не удалось получить список сотрудников из Modeus.");
|
||||
|
||||
if (attempt == MaxAttempts)
|
||||
{
|
||||
logger.LogError("Достигнуто максимальное число попыток получения JWT");
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(DelaySeconds), jobContext.CancellationToken);
|
||||
continue;
|
||||
}
|
||||
|
||||
await employeeService.SetEmployees(employees);
|
||||
logger.LogInformationHere($"Получено {employees.Count} сотрудников из Modeus.");
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Таймаут при получении JWT (попытка {Attempt}/{MaxAttempts})", attempt,
|
||||
MaxAttempts);
|
||||
|
||||
if (attempt == MaxAttempts)
|
||||
{
|
||||
logger.LogError("Достигнут лимит по таймаутам при запросе JWT");
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(DelaySeconds), jobContext.CancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogErrorHere(ex, "Ошибка при загрузке сотрудников из Modeus.");
|
||||
|
||||
if (attempt == MaxAttempts)
|
||||
{
|
||||
logger.LogError("Достигнуто максимальное число попыток из-за ошибок при запросе JWT");
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(DelaySeconds), jobContext.CancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -11,6 +11,8 @@ using Microsoft.OpenApi.Models;
|
||||
using ModeusSchedule.Abstractions;
|
||||
using Prometheus;
|
||||
using Quartz;
|
||||
using Quartz.Listener;
|
||||
using Quartz.Impl.Matchers;
|
||||
using SfeduSchedule;
|
||||
using SfeduSchedule.Auth;
|
||||
using SfeduSchedule.Jobs;
|
||||
@@ -24,29 +26,24 @@ var builder = WebApplication.CreateBuilder(args);
|
||||
#region Работа с конфигурацией
|
||||
|
||||
var configuration = builder.Configuration;
|
||||
var preinstalledJwtToken = configuration["TOKEN"];
|
||||
var tgChatId = configuration["TG_CHAT_ID"];
|
||||
var tgToken = configuration["TG_TOKEN"];
|
||||
var updateJwtCron = configuration["UPDATE_JWT_CRON"] ?? "0 0 4 ? * *";
|
||||
|
||||
var preinstalledJwtToken = configuration[AppConsts.PreinstalledJwtTokenEnv];
|
||||
configuration[AppConsts.ModeusUrlEnv] ??= AppConsts.ModeusDefaultUrl;
|
||||
configuration[AppConsts.UpdateJwtCronEnv] ??= "0 0 4 ? * *";
|
||||
configuration[AppConsts.UpdateEmployeeCronEnv] ??= "0 0 6 ? * *";
|
||||
// Если не указана TZ, ставим Europe/Moscow
|
||||
if (string.IsNullOrEmpty(configuration["TZ"]))
|
||||
configuration["TZ"] = "Europe/Moscow";
|
||||
configuration["TZ"] ??= "Europe/Moscow";
|
||||
|
||||
if (string.IsNullOrEmpty(configuration["MODEUS_URL"]))
|
||||
configuration["MODEUS_URL"] = "https://sfedu.modeus.org/";
|
||||
|
||||
var permitLimit = int.TryParse(configuration["PERMIT_LIMIT"], out var parsedPermitLimit) ? parsedPermitLimit : 40;
|
||||
var timeLimit = int.TryParse(configuration["TIME_LIMIT"], out var parsedTimeLimit) ? parsedTimeLimit : 10;
|
||||
var permitLimit = int.TryParse(configuration[AppConsts.PermitLimitEnv], out var parsedPermitLimit) ? parsedPermitLimit : 40;
|
||||
var timeLimit = int.TryParse(configuration[AppConsts.TimeLimitEnv], out var parsedTimeLimit) ? parsedTimeLimit : 10;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Работа с папкой данных
|
||||
// Создать папку data если не существует
|
||||
var dataDirectory = Path.Combine(AppContext.BaseDirectory, "data");
|
||||
var dataDirectory = Path.Combine(AppContext.BaseDirectory, AppConsts.DataFolderName);
|
||||
if (!Directory.Exists(dataDirectory)) Directory.CreateDirectory(dataDirectory);
|
||||
|
||||
GlobalConsts.JwtFilePath = Path.Combine(dataDirectory, "jwt.txt");
|
||||
var jwtFilePath = Path.Combine(dataDirectory, AppConsts.JwtFileName);
|
||||
|
||||
// Создать подкаталог для плагинов
|
||||
var pluginsPath = Path.Combine(dataDirectory, "Plugins");
|
||||
@@ -63,7 +60,7 @@ builder.Logging.AddConsole(options => options.FormatterName = "CustomConsoleForm
|
||||
.AddConsoleFormatter<ConsoleFormatter, ConsoleFormatterOptions>();
|
||||
|
||||
builder.Logging.AddFilter("Quartz", LogLevel.Warning);
|
||||
if (!string.IsNullOrEmpty(tgChatId) && !string.IsNullOrEmpty(tgToken))
|
||||
if (!string.IsNullOrEmpty(configuration[AppConsts.TgChatIdEnv]) && !string.IsNullOrEmpty(configuration[AppConsts.TgTokenEnv]))
|
||||
builder.Logging.AddTelegram(options =>
|
||||
{
|
||||
options.FormatterConfiguration = new X.Extensions.Logging.Telegram.Base.Configuration.FormatterConfiguration
|
||||
@@ -71,8 +68,8 @@ if (!string.IsNullOrEmpty(tgChatId) && !string.IsNullOrEmpty(tgToken))
|
||||
IncludeException = true,
|
||||
IncludeProperties = true,
|
||||
};
|
||||
options.ChatId = tgChatId;
|
||||
options.AccessToken = tgToken;
|
||||
options.ChatId = configuration[AppConsts.TgChatIdEnv]!;
|
||||
options.AccessToken = configuration[AppConsts.TgTokenEnv]!;
|
||||
options.FormatterConfiguration.UseEmoji = true;
|
||||
options.FormatterConfiguration.ReadableApplicationName = "Modeus Schedule Proxy";
|
||||
options.LogLevel = new Dictionary<string, LogLevel>
|
||||
@@ -92,7 +89,8 @@ builder.Services.AddHttpClient("modeus", client =>
|
||||
client.BaseAddress = new Uri(configuration["MODEUS_URL"]!);
|
||||
});
|
||||
builder.Services.AddSingleton<ModeusHttpClient>();
|
||||
builder.Services.AddHostedService<ModeusEmployeeService>();
|
||||
builder.Services.AddSingleton<ModeusEmployeeService>();
|
||||
builder.Services.AddHostedService(sp => sp.GetRequiredService<ModeusEmployeeService>());
|
||||
builder.Services.AddSingleton<ModeusService>();
|
||||
builder.Services.AddHttpClient("authClient");
|
||||
|
||||
@@ -148,23 +146,35 @@ foreach (var p in loadedPlugins)
|
||||
mvcBuilder.PartManager.ApplicationParts.Add(new AssemblyPart(p.Assembly));
|
||||
}
|
||||
|
||||
var jobKey = new JobKey("UpdateJWTJob");
|
||||
var updateJwtJob = new JobKey("UpdateJWTJob");
|
||||
|
||||
if (string.IsNullOrEmpty(preinstalledJwtToken))
|
||||
{
|
||||
builder.Services.AddQuartz(q =>
|
||||
builder.Services.AddQuartz(q =>
|
||||
{
|
||||
q.AddJob<UpdateJwtJob>(opts => opts.WithIdentity(jobKey));
|
||||
q.AddJob<UpdateJwtJob>(opts => opts.WithIdentity(updateJwtJob));
|
||||
|
||||
if (string.IsNullOrEmpty(preinstalledJwtToken))
|
||||
{
|
||||
q.AddTrigger(opts => opts
|
||||
.ForJob(updateJwtJob)
|
||||
.WithIdentity("UpdateJWTJob-trigger")
|
||||
.WithCronSchedule(configuration["UPDATE_JWT_CRON"]!)
|
||||
);
|
||||
}
|
||||
|
||||
q.AddJob<UpdateEmployeesJob>(opts => opts.WithIdentity(nameof(UpdateEmployeesJob)));
|
||||
q.AddTrigger(opts => opts
|
||||
.ForJob(jobKey)
|
||||
.WithIdentity("UpdateJWTJob-trigger")
|
||||
.WithCronSchedule(updateJwtCron)
|
||||
.ForJob(nameof(UpdateEmployeesJob))
|
||||
.WithIdentity("UpdateEmployeesJob-trigger")
|
||||
.WithCronSchedule(configuration[AppConsts.UpdateEmployeeCronEnv]!)
|
||||
);
|
||||
|
||||
// после успешного выполнения UpdateJwtJob сразу выполняем UpdateEmployeesJob
|
||||
var chainListener = new JobChainingJobListener("chain");
|
||||
chainListener.AddJobChainLink(updateJwtJob, new JobKey(nameof(UpdateEmployeesJob)));
|
||||
q.AddJobListener(chainListener, GroupMatcher<JobKey>.GroupEquals(JobKey.DefaultGroup));
|
||||
});
|
||||
|
||||
builder.Services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
|
||||
}
|
||||
builder.Services.AddQuartzHostedService(q => q.WaitForJobsToComplete = false);
|
||||
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(options =>
|
||||
@@ -257,45 +267,48 @@ app.UseForwardedHeaders();
|
||||
// Корреляция логов по запросам
|
||||
app.UseMiddleware<CorrelationIdMiddleware>();
|
||||
|
||||
if (string.IsNullOrEmpty(preinstalledJwtToken))
|
||||
{
|
||||
var schedulerFactory = app.Services.GetRequiredService<ISchedulerFactory>();
|
||||
var scheduler = await schedulerFactory.GetScheduler();
|
||||
|
||||
// Проверить существование файла jwt.txt
|
||||
if (File.Exists(GlobalConsts.JwtFilePath))
|
||||
var schedulerFactory = app.Services.GetRequiredService<ISchedulerFactory>();
|
||||
var scheduler = await schedulerFactory.GetScheduler();
|
||||
|
||||
var refreshJwt = true;
|
||||
|
||||
// Если есть предустановленный токен, используем его
|
||||
if (!string.IsNullOrEmpty(preinstalledJwtToken))
|
||||
{
|
||||
logger.LogInformation("Используем предустановленный токен из конфигурации");
|
||||
configuration["TOKEN"] = preinstalledJwtToken;
|
||||
refreshJwt = false;
|
||||
}
|
||||
|
||||
// Проверить существование файла jwt.txt
|
||||
if (File.Exists(jwtFilePath) && refreshJwt)
|
||||
{
|
||||
logger.LogInformation("Обнаружена прошлая сессия");
|
||||
var lines = await File.ReadAllLinesAsync(jwtFilePath);
|
||||
if (lines.Length > 1 && DateTime.TryParse(lines[1], out var expirationDate))
|
||||
{
|
||||
logger.LogInformation("Обнаружена прошлая сессия");
|
||||
var lines = await File.ReadAllLinesAsync(GlobalConsts.JwtFilePath);
|
||||
if (lines.Length > 1 && DateTime.TryParse(lines[1], out var expirationDate))
|
||||
logger.LogInformation("Дата истечения токена: {ExpirationDate}", expirationDate);
|
||||
if (expirationDate.AddHours(23) > DateTime.Now)
|
||||
{
|
||||
logger.LogInformation("Дата истечения токена: {ExpirationDate}", expirationDate);
|
||||
if (expirationDate.AddHours(23) > DateTime.Now)
|
||||
{
|
||||
var token = lines[0];
|
||||
logger.LogInformation("Используем существующий токен");
|
||||
configuration["TOKEN"] = token;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogInformation("Токен истек или скоро истечет, выполняем обновление токена");
|
||||
await scheduler.TriggerJob(jobKey);
|
||||
}
|
||||
var token = lines[0];
|
||||
logger.LogInformation("Используем существующий токен");
|
||||
configuration["TOKEN"] = token;
|
||||
refreshJwt = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Файл jwt.txt не содержит дату истечения или она некорректна, выполняем обновление токена");
|
||||
await scheduler.TriggerJob(jobKey);
|
||||
}
|
||||
logger.LogInformation("Токен истек или скоро истечет, выполняем обновление токена");
|
||||
}
|
||||
else
|
||||
{
|
||||
await scheduler.TriggerJob(jobKey);
|
||||
}
|
||||
logger.LogInformation(
|
||||
"Файл jwt.txt не содержит дату истечения или она некорректна, выполняем обновление токена");
|
||||
}
|
||||
|
||||
// Обновить JWT если нужно, либо сразу запустить обновление сотрудников
|
||||
if (refreshJwt)
|
||||
await scheduler.TriggerJob(updateJwtJob);
|
||||
else
|
||||
logger.LogInformation("Используем предустановленный токен из конфигурации");
|
||||
await scheduler.TriggerJob(new JobKey(nameof(UpdateEmployeesJob)));
|
||||
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
using SfeduSchedule.Logging;
|
||||
using Quartz;
|
||||
using SfeduSchedule.Jobs;
|
||||
using System.Text.Json;
|
||||
|
||||
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,38 +20,18 @@ 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);
|
||||
_backgroundTask = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(15), _cts.Token);
|
||||
|
||||
var employees = await modeusService.GetEmployeesAsync();
|
||||
if (employees.Count == 0)
|
||||
{
|
||||
logger.LogWarningHere("Не удалось получить список сотрудников из Modeus.");
|
||||
}
|
||||
else
|
||||
{
|
||||
_employees = employees;
|
||||
logger.LogInformationHere($"Получено {employees.Count} сотрудников из Modeus.");
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(5), _cts.Token);
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// ignore
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogErrorHere(ex, "Ошибка при загрузке сотрудников из Modeus.");
|
||||
}
|
||||
// Загрузка с диска
|
||||
await LoadEmployeesFromDisk();
|
||||
}, _cts.Token);
|
||||
|
||||
return Task.CompletedTask;
|
||||
@@ -72,4 +55,26 @@ public class ModeusEmployeeService(ILogger<ModeusEmployeeService> logger, Modeus
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SetEmployees(Dictionary<string, (string, List<string>)> employees)
|
||||
{
|
||||
_employees = employees;
|
||||
await SaveEmployeesToDisk();
|
||||
}
|
||||
|
||||
private async Task LoadEmployeesFromDisk()
|
||||
{
|
||||
|
||||
if (File.Exists(_employeesFilePath))
|
||||
{
|
||||
var json = await File.ReadAllTextAsync(_employeesFilePath);
|
||||
_employees = JsonSerializer.Deserialize<Dictionary<string, (string, List<string>)>>(json) ?? new Dictionary<string, (string, List<string>)>();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveEmployeesToDisk()
|
||||
{
|
||||
var json = JsonSerializer.Serialize(_employees, new JsonSerializerOptions { WriteIndented = false });
|
||||
await File.WriteAllTextAsync(_employeesFilePath, json);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
using ModeusSchedule.Abstractions;
|
||||
using ModeusSchedule.Abstractions.DTO;
|
||||
@@ -38,11 +38,10 @@ public class ModeusHttpClient
|
||||
|
||||
public async Task<string?> GetScheduleAsync(ModeusScheduleRequest msr)
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Post,
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post,
|
||||
$"schedule-calendar-v2/api/calendar/events/search?tz={_configuration["TZ"]!}");
|
||||
request.Content = new StringContent(JsonSerializer.Serialize(msr, GlobalConsts.JsonSerializerOptions),
|
||||
Encoding.UTF8, "application/json");
|
||||
var response = await _httpClient.SendAsync(request);
|
||||
request.Content = JsonContent.Create(msr, options: GlobalConsts.JsonSerializerOptions);
|
||||
using var response = await _httpClient.SendAsync(request);
|
||||
if (response.StatusCode != System.Net.HttpStatusCode.OK)
|
||||
{
|
||||
_logger.LogErrorHere($"Неуспешный статус при получении расписания: {response.StatusCode}, Request: {JsonSerializer.Serialize(msr, GlobalConsts.JsonSerializerOptions)}");
|
||||
@@ -53,18 +52,20 @@ public class ModeusHttpClient
|
||||
|
||||
public async Task<List<Attendees>> GetAttendeesAsync(Guid eventId)
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Get,
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get,
|
||||
$"schedule-calendar-v2/api/calendar/events/{eventId}/attendees");
|
||||
var response = await _httpClient.SendAsync(request);
|
||||
using var response = await _httpClient.SendAsync(request);
|
||||
if (response.StatusCode != System.Net.HttpStatusCode.OK)
|
||||
{
|
||||
_logger.LogErrorHere($"Неуспешный статус при получении расписания: {response.StatusCode}, eventId: {eventId}");
|
||||
}
|
||||
List<Attendees>? attendees;
|
||||
try
|
||||
{
|
||||
attendees = Attendees.FromJson(await response.Content.ReadAsStringAsync());
|
||||
return attendees;
|
||||
await using var contentStream = await response.Content.ReadAsStreamAsync();
|
||||
var attendees = await JsonSerializer.DeserializeAsync<List<Attendees>>(
|
||||
contentStream,
|
||||
GlobalConsts.JsonSerializerOptions);
|
||||
return attendees ?? [];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -74,15 +75,13 @@ public class ModeusHttpClient
|
||||
return [];
|
||||
}
|
||||
|
||||
public async Task<ModeusSearchPersonResponse?> SearchPersonAsync(ModeusSearchPersonRequest modeusSearchPersonRequest)
|
||||
public async Task<ModeusSearchPersonResponse?> SearchPersonAsync(ModeusSearchPersonRequest modeusSearchPersonRequest, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post,
|
||||
$"schedule-calendar-v2/api/people/persons/search");
|
||||
request.Content = new StringContent(
|
||||
JsonSerializer.Serialize(modeusSearchPersonRequest, GlobalConsts.JsonSerializerOptions),
|
||||
Encoding.UTF8, "application/json");
|
||||
request.Content = JsonContent.Create(modeusSearchPersonRequest, options: GlobalConsts.JsonSerializerOptions);
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
|
||||
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
var requestMs = stopwatch.ElapsedMilliseconds;
|
||||
if (response.StatusCode != System.Net.HttpStatusCode.OK)
|
||||
{
|
||||
@@ -96,7 +95,7 @@ public class ModeusHttpClient
|
||||
await using var contentStream = await response.Content.ReadAsStreamAsync();
|
||||
var content = await JsonSerializer.DeserializeAsync<ModeusSearchPersonResponse>(
|
||||
contentStream,
|
||||
GlobalConsts.JsonSerializerOptions);
|
||||
GlobalConsts.JsonSerializerOptions, cancellationToken);
|
||||
var groupMs = stopwatch.ElapsedMilliseconds - deserializeStartMs;
|
||||
|
||||
_logger.LogInformationHere($"SearchPersonAsync: Request time: {requestMs} ms, Deserialization time: {groupMs} ms, Total time: {stopwatch.ElapsedMilliseconds} ms.");
|
||||
@@ -113,11 +112,9 @@ public class ModeusHttpClient
|
||||
|
||||
public async Task<string?> SearchRoomsAsync(RoomSearchRequest requestDto)
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, "schedule-calendar-v2/api/campus/rooms/search");
|
||||
request.Content =
|
||||
new StringContent(JsonSerializer.Serialize(requestDto, GlobalConsts.JsonSerializerOptions),
|
||||
Encoding.UTF8, "application/json");
|
||||
var response = await _httpClient.SendAsync(request);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "schedule-calendar-v2/api/campus/rooms/search");
|
||||
request.Content = JsonContent.Create(requestDto, options: GlobalConsts.JsonSerializerOptions);
|
||||
using var response = await _httpClient.SendAsync(request);
|
||||
if (response.StatusCode != System.Net.HttpStatusCode.OK)
|
||||
{
|
||||
_logger.LogErrorHere($"Неуспешный статус при получении расписания: {response.StatusCode}, Request: {JsonSerializer.Serialize(requestDto, GlobalConsts.JsonSerializerOptions)}");
|
||||
|
||||
@@ -186,10 +186,10 @@ public class ModeusService(
|
||||
return serializedCalendar;
|
||||
}
|
||||
|
||||
public async Task<Dictionary<string, (string, List<string>)>> GetEmployeesAsync()
|
||||
public async Task<Dictionary<string, (string, List<string>)>> GetEmployeesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var searchPersonResponse =
|
||||
await modeusHttpClient.SearchPersonAsync(new ModeusSearchPersonRequest() { Size = 38000 });
|
||||
await modeusHttpClient.SearchPersonAsync(new ModeusSearchPersonRequest() { Size = 38000 }, cancellationToken);
|
||||
if (searchPersonResponse == null)
|
||||
{
|
||||
logger.LogErrorHere("persons is null");
|
||||
|
||||
@@ -10,11 +10,11 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Ical.Net" Version="5.1.2"/>
|
||||
<PackageReference Include="Microsoft.Identity.Web" Version="3.14.1"/>
|
||||
<PackageReference Include="Ical.Net" Version="5.2.0" />
|
||||
<PackageReference Include="Microsoft.Identity.Web" Version="4.3.0" />
|
||||
<PackageReference Include="prometheus-net.AspNetCore" Version="8.2.1"/>
|
||||
<PackageReference Include="Quartz.AspNetCore" Version="3.15.1"/>
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.6"/>
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.6" />
|
||||
<PackageReference Include="X.Extensions.Logging.Telegram" Version="2.0.2"/>
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -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}}"]
|
||||
}
|
||||
|
||||
###
|
||||
Reference in New Issue
Block a user