/
ApiClient.cs
150 lines (123 loc) · 4.99 KB
/
ApiClient.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
using CurseForge.APIClient.Exceptions;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace CurseForge.APIClient
{
public partial class ApiClient : IDisposable
{
private IServiceCollection _serviceCollection;
private IServiceProvider _serviceProvider;
private const string curseForgeApiBaseUrl = "https://api.curseforge.com";
private readonly string _apiKey;
private readonly long _partnerId;
private readonly string _contactEmail;
public ApiClient(string apiKey, long partnerId, string contactEmail)
{
_apiKey = apiKey;
_partnerId = partnerId;
_contactEmail = contactEmail;
InitHttpClientIfMissing();
}
public ApiClient(string apiKey, string contactEmail)
{
_apiKey = apiKey;
_partnerId = -1;
_contactEmail = contactEmail;
InitHttpClientIfMissing();
}
public ApiClient(string apiKey)
{
_apiKey = apiKey;
InitHttpClientIfMissing();
}
private void InitHttpClientIfMissing()
{
if (string.IsNullOrWhiteSpace(_apiKey))
{
throw new MissingApiKeyException("You need to provide an API key to be able to call the API");
}
BootstrapDependencyInjection();
}
private void BootstrapDependencyInjection()
{
if (_serviceCollection == null)
{
_serviceCollection = new ServiceCollection();
}
_serviceCollection.AddHttpClient("curseForgeClient", _httpClient =>
{
_httpClient.BaseAddress = new Uri(curseForgeApiBaseUrl);
var cfUserAgent = new StringBuilder();
cfUserAgent.Append("CurseForgeApiClient/" + Assembly.GetExecutingAssembly().GetName().Version);
if (_partnerId > 0 || !string.IsNullOrWhiteSpace(_contactEmail))
{
cfUserAgent.Append(" (");
if (_partnerId > 0)
{
cfUserAgent.Append(_partnerId);
}
if (!string.IsNullOrWhiteSpace(_contactEmail))
{
if (_partnerId > 0)
{
cfUserAgent.Append(";");
}
cfUserAgent.Append(_contactEmail);
}
cfUserAgent.Append(")");
}
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", cfUserAgent.ToString());
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("x-api-key", _apiKey);
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
});
_serviceProvider = _serviceCollection.BuildServiceProvider();
}
internal string GetQuerystring(params (string Key, object Value)[] queryParameters)
{
return queryParameters.Count(k => k.Value != null) > 0 ? "?" +
string.Join("&",
queryParameters
.Where(k => k.Value != null)
.Select(k => $"{System.Net.WebUtility.UrlEncode(k.Key)}={System.Net.WebUtility.UrlEncode(k.Value.ToString())}")) : string.Empty;
}
internal async Task<T> GET<T>(string endpoint, params (string Key, object Value)[] queryParameters)
{
var _httpClientFactory = _serviceProvider.GetService<IHttpClientFactory>();
var _httpClient = _httpClientFactory.CreateClient("curseForgeClient");
return await HandleResponseMessage<T>(
await _httpClient.GetAsync(
endpoint + GetQuerystring(queryParameters)
)
);
}
internal async Task<T> POST<T>(string endpoint, object body)
{
var _httpClientFactory = _serviceProvider.GetService<IHttpClientFactory>();
var _httpClient = _httpClientFactory.CreateClient("curseForgeClient");
return await HandleResponseMessage<T>(
await _httpClient.PostAsync(
endpoint,
new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json")
)
);
}
internal async Task<T> HandleResponseMessage<T>(HttpResponseMessage result)
{
if (!result.IsSuccessStatusCode)
{
throw new Exception(await result.Content.ReadAsStringAsync());
}
return JsonConvert.DeserializeObject<T>(await result.Content.ReadAsStringAsync());
}
public void Dispose()
{
// Empty because of legacy
}
}
}