-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathApiBase.cs
378 lines (303 loc) · 19.3 KB
/
ApiBase.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using TwitchLib.Api.Core.Enums;
using TwitchLib.Api.Core.Exceptions;
using TwitchLib.Api.Core.Interfaces;
using TwitchLib.Api.Core.Models;
namespace TwitchLib.Api.Core
{
/// <summary>
/// A base class for any method calling the Twitch API. Provides authorization credentials and
/// abstracts for calling basic web methods.
/// </summary>
public class ApiBase
{
private readonly TwitchLibJsonSerializer _jsonSerializer;
private readonly IUserAccessTokenManager _userAccessTokenManager;
protected readonly IApiSettings Settings;
private readonly IRateLimiter _rateLimiter;
private readonly IHttpCallHandler _http;
internal const string BaseHelix = "https://api.twitch.tv/helix";
internal const string BaseAuth = "https://id.twitch.tv/oauth2";
private DateTime? _serverBasedAccessTokenExpiry;
private string _serverBasedAccessToken;
/// <summary>
/// Standard constructor for all derived API methods.
/// </summary>
/// <param name="settings">Can be null.</param>
/// <param name="rateLimiter">Can be null.</param>
/// <param name="http">Can be null.</param>
/// <param name="userAccessTokenManager">Can be null.</param>
public ApiBase(IApiSettings settings, IRateLimiter rateLimiter, IHttpCallHandler http, IUserAccessTokenManager userAccessTokenManager)
{
Settings = settings;
_rateLimiter = rateLimiter;
_http = http;
_jsonSerializer = new TwitchLibJsonSerializer();
_userAccessTokenManager = userAccessTokenManager;
}
private async ValueTask<string> GetAccessTokenAsync(string accessToken = null)
{
if (!string.IsNullOrWhiteSpace(accessToken))
return accessToken;
if (!string.IsNullOrWhiteSpace(Settings.AccessToken))
return Settings.AccessToken;
if (Settings.UseUserTokenForHelixCalls && _userAccessTokenManager != null)
return await GenerateUserAccessToken();
if (!string.IsNullOrWhiteSpace(Settings.Secret) && !string.IsNullOrWhiteSpace(Settings.ClientId) && !Settings.SkipAutoServerTokenGeneration)
{
if (_serverBasedAccessTokenExpiry == null || _serverBasedAccessTokenExpiry - TimeSpan.FromMinutes(1) < DateTime.Now)
return await GenerateServerBasedAccessToken().ConfigureAwait(false);
return _serverBasedAccessToken;
}
return null;
}
private async Task<string> GenerateUserAccessToken()
{
return await _userAccessTokenManager.GetUserAccessToken();
}
internal async Task<string> GenerateServerBasedAccessToken()
{
var result = await _http.GeneralRequestAsync($"{BaseAuth}/token?client_id={Settings.ClientId}&client_secret={Settings.Secret}&grant_type=client_credentials", "POST", null, ApiVersion.Auth, Settings.ClientId, null).ConfigureAwait(false);
if (result.Key == 200)
{
var data = JObject.Parse(result.Value);
var offset = int.Parse(data.SelectToken("expires_in")?.ToString() ?? string.Empty);
_serverBasedAccessTokenExpiry = DateTime.Now + TimeSpan.FromSeconds(offset);
_serverBasedAccessToken = data.SelectToken("access_token")?.ToString();
return _serverBasedAccessToken;
}
return null;
}
internal void ForceAccessTokenAndClientIdForHelix(string clientId, string accessToken, ApiVersion api)
{
if (api != ApiVersion.Helix)
return;
if (!string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(accessToken))
return;
throw new ClientIdAndOAuthTokenRequired("As of May 1, all calls to Twitch's Helix API require Client-ID and OAuth access token be set. Example: api.Settings.AccessToken = \"twitch-oauth-access-token-here\"; api.Settings.ClientId = \"twitch-client-id-here\";");
}
protected async Task<string> TwitchGetAsync(string resource, ApiVersion api, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
{
var url = ConstructResourceUrl(resource, getParams, api, customBase);
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => (await _http.GeneralRequestAsync(url, "GET", null, api, clientId, accessToken).ConfigureAwait(false)).Value).ConfigureAwait(false);
}
protected async Task<T> TwitchGetGenericAsync<T>(string resource, ApiVersion api, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
{
var url = ConstructResourceUrl(resource, getParams, api, customBase);
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "GET", null, api, clientId, accessToken).ConfigureAwait(false)).Value, _twitchLibJsonDeserializer)).ConfigureAwait(false);
}
protected async Task<T> TwitchPatchGenericAsync<T>(string resource, ApiVersion api, string payload, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
{
var url = ConstructResourceUrl(resource, getParams, api, customBase);
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "PATCH", payload, api, clientId, accessToken).ConfigureAwait(false)).Value, _twitchLibJsonDeserializer)).ConfigureAwait(false);
}
protected async Task<string> TwitchPatchAsync(string resource, ApiVersion api, string payload, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
{
var url = ConstructResourceUrl(resource, getParams, api, customBase);
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => (await _http.GeneralRequestAsync(url, "PATCH", payload, api, clientId, accessToken).ConfigureAwait(false)).Value).ConfigureAwait(false);
}
protected async Task<KeyValuePair<int, string>> TwitchDeleteAsync(string resource, ApiVersion api, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
{
var url = ConstructResourceUrl(resource, getParams, api, customBase);
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => (await _http.GeneralRequestAsync(url, "DELETE", null, api, clientId, accessToken).ConfigureAwait(false))).ConfigureAwait(false);
}
protected async Task<T> TwitchPostGenericAsync<T>(string resource, ApiVersion api, string payload, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
{
var url = ConstructResourceUrl(resource, getParams, api, customBase);
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "POST", payload, api, clientId, accessToken).ConfigureAwait(false)).Value, _twitchLibJsonDeserializer)).ConfigureAwait(false);
}
protected async Task<T> TwitchPostGenericModelAsync<T>(string resource, ApiVersion api, RequestModel model, string accessToken = null, string clientId = null, string customBase = null)
{
var url = ConstructResourceUrl(resource, api: api, overrideUrl: customBase);
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "POST", model != null ? _jsonSerializer.SerializeObject(model) : "", api, clientId, accessToken).ConfigureAwait(false)).Value, _twitchLibJsonDeserializer)).ConfigureAwait(false);
}
protected async Task<T> TwitchDeleteGenericAsync<T>(string resource, ApiVersion api, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
{
var url = ConstructResourceUrl(resource, getParams, api, customBase);
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "DELETE", null, api, clientId, accessToken).ConfigureAwait(false)).Value, _twitchLibJsonDeserializer)).ConfigureAwait(false);
}
protected async Task<T> TwitchPutGenericAsync<T>(string resource, ApiVersion api, string payload = null, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
{
var url = ConstructResourceUrl(resource, getParams, api, customBase);
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "PUT", payload, api, clientId, accessToken).ConfigureAwait(false)).Value, _twitchLibJsonDeserializer)).ConfigureAwait(false);
}
protected async Task<string> TwitchPutAsync(string resource, ApiVersion api, string payload, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
{
var url = ConstructResourceUrl(resource, getParams, api, customBase);
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => (await _http.GeneralRequestAsync(url, "PUT", payload, api, clientId, accessToken).ConfigureAwait(false)).Value).ConfigureAwait(false);
}
protected async Task<KeyValuePair<int, string>> TwitchPostAsync(string resource, ApiVersion api, string payload, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, string clientId = null, string customBase = null)
{
var url = ConstructResourceUrl(resource, getParams, api, customBase);
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => await _http.GeneralRequestAsync(url, "POST", payload, api, clientId, accessToken).ConfigureAwait(false)).ConfigureAwait(false);
}
protected Task PutBytesAsync(string url, byte[] payload)
{
return _http.PutBytesAsync(url, payload);
}
internal Task<int> RequestReturnResponseCode(string url, string method, List<KeyValuePair<string, string>> getParams = null)
{
return _http.RequestReturnResponseCodeAsync(url, method, getParams);
}
protected async Task<T> GetGenericAsync<T>(string url, List<KeyValuePair<string, string>> getParams = null, string accessToken = null, ApiVersion api = ApiVersion.Helix, string clientId = null)
{
if (getParams != null)
{
for (var i = 0; i < getParams.Count; i++)
{
if (i == 0)
url += $"?{getParams[i].Key}={Uri.EscapeDataString(getParams[i].Value)}";
else
url += $"&{getParams[i].Key}={Uri.EscapeDataString(getParams[i].Value)}";
}
}
if (string.IsNullOrWhiteSpace(clientId) && !string.IsNullOrWhiteSpace(Settings.ClientId))
clientId = Settings.ClientId;
accessToken = await GetAccessTokenAsync(accessToken).ConfigureAwait(false);
ForceAccessTokenAndClientIdForHelix(clientId, accessToken, api);
return await _rateLimiter.Perform(async () => JsonConvert.DeserializeObject<T>((await _http.GeneralRequestAsync(url, "GET", null, api, clientId, accessToken).ConfigureAwait(false)).Value, _twitchLibJsonDeserializer)).ConfigureAwait(false);
}
internal Task<T> GetSimpleGenericAsync<T>(string url, List<KeyValuePair<string, string>> getParams = null)
{
if (getParams != null)
{
for (var i = 0; i < getParams.Count; i++)
{
if (i == 0)
url += $"?{getParams[i].Key}={Uri.EscapeDataString(getParams[i].Value)}";
else
url += $"&{getParams[i].Key}={Uri.EscapeDataString(getParams[i].Value)}";
}
}
return _rateLimiter.Perform(async () => JsonConvert.DeserializeObject<T>(await SimpleRequestAsync(url).ConfigureAwait(false), _twitchLibJsonDeserializer));
}
// credit: https://stackoverflow.com/questions/14290988/populate-and-return-entities-from-downloadstringcompleted-handler-in-windows-pho
private Task<string> SimpleRequestAsync(string url)
{
var tcs = new TaskCompletionSource<string>();
var client = new WebClient();
client.DownloadStringCompleted += DownloadStringCompletedEventHandler;
client.DownloadString(new Uri(url));
return tcs.Task;
// local function
void DownloadStringCompletedEventHandler(object sender, DownloadStringCompletedEventArgs args)
{
if (args.Cancelled)
tcs.SetCanceled();
else if (args.Error != null)
tcs.SetException(args.Error);
else
tcs.SetResult(args.Result);
client.DownloadStringCompleted -= DownloadStringCompletedEventHandler;
}
}
private readonly JsonSerializerSettings _twitchLibJsonDeserializer = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore };
private class TwitchLibJsonSerializer
{
private readonly JsonSerializerSettings _settings = new JsonSerializerSettings
{
ContractResolver = new LowercaseContractResolver(),
NullValueHandling = NullValueHandling.Ignore
};
public string SerializeObject(object o)
{
return JsonConvert.SerializeObject(o, Formatting.Indented, _settings);
}
private class LowercaseContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
return propertyName.ToLower();
}
}
}
private string ConstructResourceUrl(string resource = null, List<KeyValuePair<string, string>> getParams = null, ApiVersion api = ApiVersion.Helix, string overrideUrl = null)
{
var url = "";
if (overrideUrl == null)
{
if (resource == null)
throw new Exception("Cannot pass null resource with null override url");
switch (api)
{
case ApiVersion.Helix:
url = $"{BaseHelix}{resource}";
break;
case ApiVersion.Auth:
url = $"{BaseAuth}{resource}";
break;
}
}
else
{
url = resource == null ? overrideUrl : $"{overrideUrl}{resource}";
}
if (getParams != null)
{
for (var i = 0; i < getParams.Count; i++)
{
// When "after" is null, then Uri.EscapeDataString dies with null exception.
var value = "";
if (getParams[i].Value != null)
value = getParams[i].Value;
if (i == 0)
url += "?";
else
url += "&";
url += $"{getParams[i].Key}={Uri.EscapeDataString(value)}";
}
}
return url;
}
}
}