-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathApiClient.cs
216 lines (182 loc) · 7.6 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
using CurseForge.APIClient.Exceptions;
using CurseForge.APIClient.Models;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Text.Json;
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<GenericListResponse<T>> GetList<T>(string endpoint, params (string Key, object Value)[] queryParameters)
{
var _httpClientFactory = _serviceProvider.GetService<IHttpClientFactory>();
var _httpClient = _httpClientFactory.CreateClient("curseForgeClient");
return await HandleListResponseMessage<T>(
await _httpClient.GetAsync(
endpoint + GetQuerystring(queryParameters)
)
);
}
internal async Task<GenericResponse<T>> GetItem<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<GenericListResponse<T>> PostList<T>(string endpoint, object body)
{
var _httpClientFactory = _serviceProvider.GetService<IHttpClientFactory>();
var _httpClient = _httpClientFactory.CreateClient("curseForgeClient");
return await HandleListResponseMessage<T>(
await _httpClient.PostAsync(
endpoint,
new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json")
)
);
}
internal async Task<GenericResponse<T>> PostItem<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(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json")
)
);
}
internal static async Task<GenericListResponse<T>> HandleListResponseMessage<T>(HttpResponseMessage result)
{
if (!result.IsSuccessStatusCode)
{
var errorMessage = await result.Content.ReadAsStringAsync();
return new GenericListResponse<T>
{
Error = new ErrorResponse
{
ErrorCode = (int)result.StatusCode,
ErrorMessage = errorMessage
}
};
}
return JsonSerializer.Deserialize<GenericListResponse<T>>(await result.Content.ReadAsStringAsync());
}
internal static async Task<GenericResponse<T>> HandleResponseMessage<T>(HttpResponseMessage result)
{
if (!result.IsSuccessStatusCode)
{
var errorMessage = await result.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(errorMessage))
{
var type = typeof(T).Name;
switch (result.StatusCode)
{
case HttpStatusCode.NotFound:
{
errorMessage = $"Could not find the {type}";
break;
}
}
}
return new GenericResponse<T>
{
Error = new ErrorResponse
{
ErrorCode = (int)result.StatusCode,
ErrorMessage = errorMessage
}
};
}
return JsonSerializer.Deserialize<GenericResponse<T>>(await result.Content.ReadAsStringAsync());
}
public void Dispose()
{
// Empty because of legacy
}
}
}