-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTerryWatchClient.cs
More file actions
223 lines (184 loc) · 7.23 KB
/
TerryWatchClient.cs
File metadata and controls
223 lines (184 loc) · 7.23 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
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
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace TerryWatch.Client;
public static class TerryWatch
{
public static TerryWatchClient Init(
string apiKey,
string appId,
string baseUrl = "https://terrywatch.com",
HttpClient? httpClient = null)
{
return new TerryWatchClient(
httpClient ?? new HttpClient
{
Timeout = TimeSpan.FromSeconds(10),
},
new Uri(baseUrl.TrimEnd('/') + "/"),
appId,
apiKey);
}
}
public static class Terrywatch
{
public static TerryWatchClient Init(
string apiKey,
string appId,
string baseUrl = "https://terrywatch.com",
HttpClient? httpClient = null)
{
return TerryWatch.Init(apiKey, appId, baseUrl, httpClient);
}
}
public sealed class TerryWatchClient
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
private readonly HttpClient httpClient;
private readonly string appId;
private readonly string apiSecret;
public TerryWatchClient(
HttpClient httpClient,
Uri baseUrl,
string appId,
string apiSecret)
{
this.httpClient = httpClient;
this.httpClient.BaseAddress = baseUrl;
this.appId = appId;
this.apiSecret = apiSecret;
}
public async Task<TerryWatchSession> StartSessionAsync(
string steamId,
string authToken,
CancellationToken cancellationToken = default)
{
using var request = new HttpRequestMessage(HttpMethod.Post, "api/sessions/start")
{
Content = JsonContent.Create(
new StartSessionRequest(steamId, authToken),
options: JsonOptions),
};
request.Headers.Add("X-App-Id", appId);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiSecret);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await httpClient.SendAsync(request, cancellationToken);
var body = await ReadJsonAsync<StartSessionResponse>(response, cancellationToken);
return new TerryWatchSession(httpClient, body.SessionId, body.SessionToken, body.Player.Uuid);
}
private static async Task<T> ReadJsonAsync<T>(
HttpResponseMessage response,
CancellationToken cancellationToken)
{
var body = await response.Content.ReadAsStringAsync(cancellationToken);
if (!response.IsSuccessStatusCode)
{
string? errorCode = null;
try
{
errorCode = JsonSerializer.Deserialize<ApiError>(body, JsonOptions)?.Error;
}
catch (JsonException)
{
// The API should return JSON errors, but keep the raw body for diagnostics.
}
throw new TerryWatchApiException(response.StatusCode, errorCode, body);
}
var result = JsonSerializer.Deserialize<T>(body, JsonOptions);
if (result is null)
{
throw new TerryWatchApiException(response.StatusCode, null, body);
}
return result;
}
private sealed record StartSessionRequest(string SteamId, string AuthToken);
private sealed record StartSessionResponse(
[property: JsonPropertyName("session_id")] string SessionId,
[property: JsonPropertyName("session_token")] string SessionToken,
PlayerResponse Player);
private sealed record PlayerResponse(string Uuid);
private sealed record ApiError(string? Error);
public sealed class TerryWatchSession
{
private readonly HttpClient httpClient;
internal TerryWatchSession(
HttpClient httpClient,
string sessionId,
string sessionToken,
string playerUuid)
{
this.httpClient = httpClient;
SessionId = sessionId;
SessionToken = sessionToken;
PlayerUuid = playerUuid;
}
public string SessionId { get; }
public string SessionToken { get; }
public string PlayerUuid { get; }
public async Task SendEventAsync(
string name,
object? properties = null,
DateTimeOffset? occurredAt = null,
CancellationToken cancellationToken = default)
{
using var request = new HttpRequestMessage(HttpMethod.Post, "api/events")
{
Content = JsonContent.Create(
new TrackEventRequest(
name,
properties is null
? null
: JsonSerializer.SerializeToElement(properties, JsonOptions),
occurredAt),
options: JsonOptions),
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", SessionToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using var response = await httpClient.SendAsync(request, cancellationToken);
await ReadJsonAsync<TrackEventResponse>(response, cancellationToken);
}
public async Task<EndSessionResponse> EndAsync(
DateTimeOffset? endedAt = null,
CancellationToken cancellationToken = default)
{
using var request = new HttpRequestMessage(HttpMethod.Post, "api/sessions/end")
{
Content = JsonContent.Create(new EndSessionRequest(endedAt), options: JsonOptions),
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", SessionToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using var response = await httpClient.SendAsync(request, cancellationToken);
return await ReadJsonAsync<EndSessionResponse>(response, cancellationToken);
}
private sealed record TrackEventRequest(
string Name,
JsonElement? Properties = null,
DateTimeOffset? OccurredAt = null);
private sealed record TrackEventResponse(int Id);
private sealed record EndSessionRequest(DateTimeOffset? EndedAt = null);
}
}
public sealed class TerryWatchApiException : Exception
{
public TerryWatchApiException(HttpStatusCode statusCode, string? errorCode, string responseBody)
: base(errorCode is null
? $"TerryWatch API request failed with {(int)statusCode}."
: $"TerryWatch API request failed with {(int)statusCode}: {errorCode}.")
{
StatusCode = statusCode;
ErrorCode = errorCode;
ResponseBody = responseBody;
}
public HttpStatusCode StatusCode { get; }
public string? ErrorCode { get; }
public string ResponseBody { get; }
}
public sealed record EndSessionResponse(
[property: JsonPropertyName("session_id")] string SessionId,
[property: JsonPropertyName("duration_seconds")] int? DurationSeconds);