-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPdfClient.cs
More file actions
55 lines (41 loc) · 1.67 KB
/
Copy pathPdfClient.cs
File metadata and controls
55 lines (41 loc) · 1.67 KB
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
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using PDFinch.Client.Common;
[assembly: InternalsVisibleTo("PDFinch.Client.Tests")]
namespace PDFinch.Client
{
internal class PdfClient : HttpPdfClient
{
private readonly string _clientId;
private readonly string _clientSecret;
private readonly DateTime _created;
private readonly HttpClient _client;
private ResponseToken? _responseToken;
private readonly TimeSpan _maxClientLifeTime;
private readonly TimeSpan _defaultClientLifeTime = TimeSpan.FromMinutes(60);
internal PdfClient(HttpClient httpClient, PdfClientOptions options, TimeSpan? clientLifeTime = null)
: base(options)
{
_client = httpClient;
_clientId = options.ApiKey;
_clientSecret = options.ApiSecret;
_created = DateTime.Now;
_maxClientLifeTime = clientLifeTime ?? _defaultClientLifeTime;
}
protected override async Task<HttpClient> AuthenticateClientAsync(HttpRequestMessage httpRequestMessage)
{
if (_responseToken is { IsExpired: false })
{
return _client;
}
_client.DefaultRequestHeaders.Authorization = null;
_responseToken = await _client.GetTokenAsync(_clientId, _clientSecret);
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _responseToken.AccessToken);
return _client;
}
internal bool IsExpired() => DateTime.Now - _created > _maxClientLifeTime;
}
}