Files
SfeduSchedule/SfeduSchedule/Services/ModeusHttpClient.cs
Sergey Karmanov daf3639038
Some checks failed
Create and publish a Docker image / Publish image (push) Failing after 1m10s
Добавил correlation id
2025-11-21 16:03:14 +03:00

131 lines
5.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Text;
using System.Text.Json;
using Microsoft.Net.Http.Headers;
using ModeusSchedule.Abstractions;
using ModeusSchedule.Abstractions.DTO;
namespace SfeduSchedule.Services;
public class ModeusHttpClient
{
private readonly HttpClient _httpClient;
private readonly IConfiguration _configuration;
private readonly ILogger<ModeusHttpClient> _logger;
public ModeusHttpClient(IHttpClientFactory httpClientFactory,
ILogger<ModeusHttpClient> logger,
IConfiguration configuration)
{
_httpClient = httpClientFactory.CreateClient("modeus");
_logger = logger;
_configuration = configuration;
SetToken(_configuration["TOKEN"]); // Установка предустановленного токена при инициализации, на случай если нет возможности связи с AUTH сервисом
}
public void SetToken(string? token)
{
if (string.IsNullOrWhiteSpace(token)) {
_logger.LogError("SetToken: Предоставленный токен пустой.");
return;
}
_httpClient.DefaultRequestHeaders.Remove(HeaderNames.Authorization);
_httpClient.DefaultRequestHeaders.Add(HeaderNames.Authorization, $"Bearer {token}");
}
public async Task<string?> GetScheduleAsync(ModeusScheduleRequest msr)
{
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);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
_logger.LogError("GetScheduleAsync: Неуспешный статус при получении расписания: {StatusCode}, Request: {msr}",
response.StatusCode, msr);
return null;
}
return await response.Content.ReadAsStringAsync();
}
public async Task<List<Attendees>> GetAttendeesAsync(Guid eventId)
{
var request = new HttpRequestMessage(HttpMethod.Get,
$"schedule-calendar-v2/api/calendar/events/{eventId}/attendees");
var response = await _httpClient.SendAsync(request);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
_logger.LogError("GetAttendeesAsync: Неуспешный статус при получении расписания: {StatusCode}, eventId: {eventId}",
response.StatusCode, eventId);
}
List<Attendees>? attendees;
try
{
attendees = Attendees.FromJson(await response.Content.ReadAsStringAsync());
return attendees;
}
catch (Exception ex)
{
_logger.LogError(ex, "GetAttendeesAsync: Deserialization failed.");
}
return new List<Attendees>();
}
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);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
_logger.LogError("GetScheduleAsync: Неуспешный статус при получении расписания: {StatusCode}, Request: {requestDto}",
response.StatusCode, requestDto);
return null;
}
return await response.Content.ReadAsStringAsync();
}
public async Task<string?> GetGuidAsync(string fullName)
{
var request = new HttpRequestMessage(HttpMethod.Post, "schedule-calendar-v2/api/people/persons/search");
request.Content = new StringContent(JsonSerializer.Serialize(new
{
fullName,
sort = "+fullName",
size = 10,
page = 0
}), Encoding.UTF8, "application/json");
var response = await _httpClient.SendAsync(request);
_logger.LogInformation("GetGuidAsync: Ответ получен: {StatusCode}", response.StatusCode);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
_logger.LogError("GetGuidAsync: Неуспешный статус при получении расписания: {StatusCode}, Name: {fullName}",
response.StatusCode, fullName);
return null;
}
var json = await response.Content.ReadAsStringAsync();
string? personId;
try
{
personId = JsonDocument.Parse(json).RootElement
.GetProperty("_embedded")
.GetProperty("persons")[0]
.GetProperty("id")
.GetString();
}
catch
{
_logger.LogWarning(
"GetGuidAsync: не удалось получить идентификатор пользователя. FullName={FullName}", fullName);
return null;
}
return personId;
}
}