-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathInfobipWhatsAppClient.cs
74 lines (66 loc) · 2.87 KB
/
InfobipWhatsAppClient.cs
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
64
65
66
67
68
69
70
71
72
73
74
using Bot.Builder.Community.Adapters.Infobip.Core;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Bot.Builder.Community.Adapters.Infobip.WhatsApp
{
public sealed class InfobipWhatsAppClient : InfobipClientBase, IInfobipWhatsAppClient
{
private readonly InfobipWhatsAppAdapterOptions _infobipWhatsAppOptions;
private readonly ILogger _logger;
private static readonly InfobipHttpClient _infobipHttpClient;
static InfobipWhatsAppClient()
{
_infobipHttpClient = new InfobipHttpClient();
}
public InfobipWhatsAppClient(InfobipWhatsAppAdapterOptions infobipViberWhatsAppAdapterOptions, ILogger<InfobipWhatsAppClient> logger):base(infobipViberWhatsAppAdapterOptions)
{
_infobipWhatsAppOptions = infobipViberWhatsAppAdapterOptions ?? throw new ArgumentNullException(nameof(infobipViberWhatsAppAdapterOptions));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_infobipHttpClient.Init(_infobipWhatsAppOptions.InfobipApiKey);
}
public static async Task<Attachment> GetAttachmentAsync(string url, CancellationToken cancellationToken = default)
{
var request = new HttpRequestMessage
{
RequestUri = new Uri(url, UriKind.RelativeOrAbsolute),
Method = HttpMethod.Get
};
var response = await _infobipHttpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
if (data == null) throw new Exception("Attachment was not downloaded!");
return new Attachment
{
Content = data,
ContentType = response.Content.Headers?.ContentType?.MediaType
};
}
return null;
}
public async Task<string> GetContentTypeAsync(string url, CancellationToken cancellationToken = default)
{
var request = new HttpRequestMessage
{
RequestUri = new Uri(url, UriKind.RelativeOrAbsolute),
Method = HttpMethod.Head
};
try
{
var response = await _infobipHttpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
return response.IsSuccessStatusCode ?
response.Content.Headers.ContentType.MediaType :
null;
}
catch (Exception e)
{
_logger.LogWarning($"Content type checking failed. Message: {e.Message}");
return null;
}
}
}
}