< Summary

Information
Class: AppRepository.ApiServices.OzonApi.OzonChatHttpClient
Assembly: Services
File(s): /home/runner/work/Studio2Prod/Studio2Prod/AppRepository/ApiServices/OzonApi/OzonChatHttpClient.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 58
Coverable lines: 58
Total lines: 167
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 20
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%210%
.ctor(...)0%4260%
PostAsync()0%210140%
GetChatListAsync()100%210%
GetChatHistoryAsync()100%210%
MarkAsReadAsync()100%210%
SendMessageAsync()100%210%
SendFileAsync()100%210%

File(s)

/home/runner/work/Studio2Prod/Studio2Prod/AppRepository/ApiServices/OzonApi/OzonChatHttpClient.cs

#LineLine coverage
 1using System.Text;
 2using System.Text.Json;
 3using Microsoft.Extensions.Http;
 4using AppRepository.ApiServices.OzonApi.Filters;
 5
 6namespace AppRepository.ApiServices.OzonApi
 7{
 8    /// <summary>
 9    /// Простой HTTP клиент специально для работы с Ozon Chat API
 10    /// Без rate limiting и дополнительных ограничений
 11    /// </summary>
 12    public class OzonChatHttpClient
 13    {
 14        private readonly IHttpClientFactory _httpClientFactory;
 15        private readonly string _clientId;
 16        private readonly string _apiKey;
 17        private const string BaseUrl = "https://api-seller.ozon.ru";
 18
 019        private static readonly JsonSerializerOptions _serializeOptions = new()
 020        {
 021            DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
 022            PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
 023        };
 24
 025        private static readonly JsonSerializerOptions _deserializeOptions = new()
 026        {
 027            PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
 028            NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString
 029        };
 30
 031        public OzonChatHttpClient(
 032            IHttpClientFactory httpClientFactory,
 033            string clientId,
 034            string apiKey)
 35        {
 036            _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
 037            _clientId = clientId ?? throw new ArgumentNullException(nameof(clientId));
 038            _apiKey = apiKey ?? throw new ArgumentNullException(nameof(apiKey));
 039        }
 40
 41        /// <summary>
 42        /// Выполняет POST запрос к Ozon Chat API
 43        /// </summary>
 44        /// <typeparam name="TRequest">Тип запроса</typeparam>
 45        /// <typeparam name="TResponse">Тип ответа</typeparam>
 46        /// <param name="request">Объект запроса</param>
 47        /// <param name="endpoint">Endpoint API (например, "/v3/chat/list")</param>
 48        /// <returns>Десериализованный ответ или null в случае ошибки</returns>
 49        public async Task<TResponse?> PostAsync<TRequest, TResponse>(TRequest request, string endpoint)
 50            where TRequest : class
 51            where TResponse : class
 52        {
 53            try
 54            {
 055                using var httpClient = _httpClientFactory.CreateClient();
 056                httpClient.Timeout = TimeSpan.FromSeconds(30);
 57
 58                // Устанавливаем заголовки аутентификации
 059                httpClient.DefaultRequestHeaders.Clear();
 060                httpClient.DefaultRequestHeaders.Add("Client-Id", _clientId);
 061                httpClient.DefaultRequestHeaders.Add("Api-Key", _apiKey);
 62
 63                // Сериализуем запрос в JSON (System.Text.Json для поддержки JsonPropertyName атрибутов)
 064                var jsonRequest = JsonSerializer.Serialize(request, _serializeOptions);
 065                using var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
 66
 67                // Строим полный URL
 068                var fullUrl = $"{BaseUrl}{endpoint}";
 69
 70                // Выполняем POST запрос
 071                using var response = await httpClient.PostAsync(fullUrl, content).ConfigureAwait(false);
 72
 73                // Читаем ответ
 074                var jsonResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
 75
 76
 077                if (!response.IsSuccessStatusCode)
 78                {
 79                    // Проверяем на ошибку Premium Plus
 080                    if (!string.IsNullOrEmpty(jsonResponse) && jsonResponse.Contains("PermissionDenied") && jsonResponse
 81                    {
 82                        // Для ChatHistoryResponse — возвращаем специальный объект с флагом
 083                        if (typeof(TResponse).Name == "ChatHistoryResponse")
 84                        {
 085                            var premiumResp = new Filters.ChatHistoryResponse();
 86                            // Добавим свойство через dynamic cast (или расширьте модель при необходимости)
 87                            // Здесь используем хак через словарь, если потребуется
 88                            // Можно добавить публичное свойство IsPremiumRequired в ChatHistoryResponse
 089                            typeof(Filters.ChatHistoryResponse).GetProperty("IsPremiumRequired")?.SetValue(premiumResp, 
 090                            return premiumResp as TResponse;
 91                        }
 92                    }
 093                    Console.WriteLine($"Ozon Chat API Error: {response.StatusCode} - {jsonResponse}");
 094                    return null;
 95                }
 96
 097                if (string.IsNullOrWhiteSpace(jsonResponse))
 98                {
 099                    return null;
 100                }
 101
 102                // Десериализуем ответ
 0103                return JsonSerializer.Deserialize<TResponse>(jsonResponse, _deserializeOptions);
 104            }
 0105            catch (Exception ex)
 106            {
 0107                Console.WriteLine($"Ozon Chat HTTP Client Error: {ex.Message}");
 0108                return null;
 109            }
 0110        }
 111
 112        /// <summary>
 113        /// Получает список чатов
 114        /// </summary>
 115        /// <param name="request">Параметры запроса</param>
 116        /// <returns>Ответ с чатами или null</returns>
 117        public async Task<ChatListResponse?> GetChatListAsync(ChatListRequest request)
 118        {
 0119            return await PostAsync<ChatListRequest, ChatListResponse>(request, "/v3/chat/list")
 0120                .ConfigureAwait(false);
 0121        }
 122
 123        /// <summary>
 124        /// Получает историю сообщений чата
 125        /// </summary>
 126        /// <param name="request">Параметры запроса</param>
 127        /// <returns>Ответ с сообщениями или null</returns>
 128        public async Task<ChatHistoryResponse?> GetChatHistoryAsync(ChatHistoryRequest request)
 129        {
 0130            return await PostAsync<ChatHistoryRequest, ChatHistoryResponse>(request, "/v3/chat/history")
 0131                .ConfigureAwait(false);
 0132        }
 133
 134        /// <summary>
 135        /// Отмечает сообщения в чате как прочитанные
 136        /// </summary>
 137        /// <param name="request">Параметры запроса (chat_id и from_message_id)</param>
 138        /// <returns>Ответ с количеством непрочитанных сообщений или null</returns>
 139        public async Task<ChatReadResponse?> MarkAsReadAsync(ChatReadRequest request)
 140        {
 0141            return await PostAsync<ChatReadRequest, ChatReadResponse>(request, "/v2/chat/read")
 0142                .ConfigureAwait(false);
 0143        }
 144
 145        /// <summary>
 146        /// Отправляет сообщение в чат
 147        /// </summary>
 148        /// <param name="request">Параметры запроса (chat_id и text)</param>
 149        /// <returns>Ответ с результатом отправки или null</returns>
 150        public async Task<ChatSendMessageResponse?> SendMessageAsync(ChatSendMessageRequest request)
 151        {
 0152            return await PostAsync<ChatSendMessageRequest, ChatSendMessageResponse>(request, "/v1/chat/send/message")
 0153                .ConfigureAwait(false);
 0154        }
 155
 156        /// <summary>
 157        /// Отправляет файл в чат
 158        /// </summary>
 159        /// <param name="request">Параметры запроса (chat_id, base64_content и name)</param>
 160        /// <returns>Ответ с результатом отправки или null</returns>
 161        public async Task<ChatSendFileResponse?> SendFileAsync(ChatSendFileRequest request)
 162        {
 0163            return await PostAsync<ChatSendFileRequest, ChatSendFileResponse>(request, "/v1/chat/send/file")
 0164                .ConfigureAwait(false);
 0165        }
 166    }
 167}