aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio_22/Tango.Portal.Chat.Web/Services/N8NService.cs
blob: 6205e632752a590aaf817dd757bc77a235c317d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using Microsoft.Extensions.Options;
using System.Text;
using System.Text.Json;
using Tango.Portal.Chat.Web.Models;

namespace Tango.Portal.Chat.Web.Services
{
    public sealed class N8NService
    {
        private readonly HttpClient _httpClient;
        private readonly N8NOptions _options;
        private readonly ILogger<N8NService> _logger;

        public N8NService(HttpClient httpClient, IOptions<N8NOptions> options, ILogger<N8NService> logger)
        {
            _httpClient = httpClient;
            _options = options.Value;
            _logger = logger;

            // Set up basic authentication
            var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_options.User}:{_options.Password}"));
            _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
        }

        public async Task<bool> PostAlertDataAsync(string name, string type, string chartType, string chartTitle, string instructions, object[] rows, CancellationToken cancellationToken = default)
        {
            try
            {
                var payload = new
                {
                    Name = name,
                    Type = type,
                    Rows = rows,
                    ChartType = chartType,
                    ChartTitle = chartTitle,
                    Instructions = instructions
                };

                var json = JsonSerializer.Serialize(payload);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync(_options.URL, content, cancellationToken);

                if (response.IsSuccessStatusCode)
                {
                    _logger.LogInformation("Successfully posted alert data for {Name} to n8n", name);
                    return true;
                }
                else
                {
                    _logger.LogWarning("Failed to post alert data for {Name} to n8n. Status: {StatusCode}, Response: {Response}",
                        name, response.StatusCode, await response.Content.ReadAsStringAsync(cancellationToken));
                    return false;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Exception occurred while posting alert data for {Name} to n8n", name);
                return false;
            }
        }
    }
}