-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.cs
More file actions
232 lines (219 loc) · 7.12 KB
/
API.cs
File metadata and controls
232 lines (219 loc) · 7.12 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
224
225
226
227
228
229
230
231
232
using System.Diagnostics;
namespace AutoLogout
{
public class API
{
// Constants
#if DEBUG
private string Url = "http://localhost:8787/api/";
#else
private string Url = "https://autologout.yiays.com/api/";
#endif
private readonly string SupportedAPIVersion = "2";
private bool UpdateWarned = false;
private readonly HttpClient httpClient = new()
{
Timeout = TimeSpan.FromSeconds(10),
DefaultRequestHeaders =
{
{ "User-Agent", "AutoLogoutClient/1.0" },
{ "Accept", "application/json" }
}
};
// Response models
private struct ApiResult<T>
{
public bool success { get; set; }
public HttpResponseMessage response { get; set; }
public T? result { get; set; }
}
private struct SyncResult
{
public bool accepted { get; set; }
public string? error { get; set; }
public Delta? delta { get; set; }
}
private struct DeauthResult
{
public bool success { get; set; }
public string? error { get; set; }
}
public struct Delta
{
// State as it appears when returned from the server
public Guid? authKey { get; set; }
public Guid? uuid { get; set; }
public string? hashedPassword { get; set; }
public int? dailyTimeLimit { get; set; }
public int? todayTimeLimit { get; set; }
public int? usedTime { get; set; }
public DateOnly? usageDate { get; set; }
public TimeOnly? bedtime { get; set; }
public TimeOnly? waketime { get; set; }
public bool? graceGiven { get; set; }
public Guid? syncAuthor { get; set; }
// syncAuthor tracks the last client that modified the state
// This should be null whenever this client is modifying the state
}
private async Task<ApiResult<T>> ApiCall<T>(
string endpoint, HttpMethod method, StringContent? content, Guid? authKey
)
{
if (authKey is not null && authKey != Guid.Empty)
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authKey.ToString());
}
else
{
httpClient.DefaultRequestHeaders.Remove("Authorization");
}
HttpResponseMessage response;
try
{
response = await httpClient.SendAsync(
new HttpRequestMessage(method, Url + endpoint)
{
Content = content
}
);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to call {endpoint}: {ex.Message}");
throw;
}
if (response.Headers.TryGetValues("X-Api-Version", out var apiVersionHeaders))
{
string apiVersion = apiVersionHeaders.FirstOrDefault() ?? "";
if (apiVersion != SupportedAPIVersion)
{
if (!UpdateWarned)
{
Console.WriteLine($"It appears this client is out of date. Expected API version: {SupportedAPIVersion}, got: {apiVersion}");
UpdateWarned = true;
_ = Task.Run(() =>
{
MessageBox.Show(
"Please update to the latest version to ensure online features work.",
"AutoLogout is out of date",
MessageBoxButtons.OK,
MessageBoxIcon.Warning
);
});
}
}
}
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"API call '{endpoint}' failed: {response.ReasonPhrase}");
if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.Write(responseBody);
}
return new ApiResult<T> { success = false, response = response, result = default };
}
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
T? result = System.Text.Json.JsonSerializer.Deserialize<T>(responseBody);
if (result == null)
{
Console.WriteLine("Failed to deserialize api result.");
return new ApiResult<T> { success = false, response = response, result = default };
}
return new ApiResult<T> { success = true, response = response, result = result };
}
return new ApiResult<T> { success = false, response = response, result = default };
}
public async Task Sync(State state)
{
// Convert state to JSON and share with online service
string timezone = TimeZoneInfo.Local.BaseUtcOffset.ToString(@"hh\:mm");
timezone = (TimeZoneInfo.Local.BaseUtcOffset < TimeSpan.Zero ? "-" : "+") + timezone;
string usageDate = state.usageDate.ToString(@"yyyy\-MM\-dd") + ' ' + timezone;
string json = System.Text.Json.JsonSerializer.Serialize(new
{
state.hashedPassword,
state.dailyTimeLimit,
state.todayTimeLimit,
state.usedTime,
usageDate,
state.bedtime,
state.waketime,
state.graceGiven,
state.syncAuthor
});
// Clear syncAuthor as we only need to acknowledge serverside changes once
state.syncAuthor = null;
var apiResponse = await ApiCall<SyncResult>(
"sync/" + state.uuid.ToString(), HttpMethod.Post,
new StringContent(json, System.Text.Encoding.UTF8, "application/json"),
state.authKey
);
if (apiResponse.success)
{
if (apiResponse.result.accepted)
{
// Sync was successful, no changes needed
if (apiResponse.result.delta != null)
{
// Server must have provided us with an authKey
state.authKey = apiResponse.result.delta?.authKey ?? state.authKey;
state.SaveToRegistry();
Console.WriteLine("Recieved new authKey");
}
}
else
{
// Sync was rejected
if (apiResponse.result.error != null)
{
Console.WriteLine($"Sync failed: {apiResponse.result.error}");
}
else if (apiResponse.result.delta != null)
{
Console.WriteLine("Accepting alternative state from server");
state.AcceptDelta(apiResponse.result.delta ?? new Delta());
state.TriggerStateChanged();
}
}
}
# if DEBUG
else
{
Console.WriteLine(json);
}
# endif
}
public async Task<bool> Deauth(State state)
{
// Request the server deletes all client data
var apiResult = await ApiCall<DeauthResult>(
"deauth/" + state.uuid.ToString(), HttpMethod.Delete, null, state.authKey
);
if (apiResult.success)
{
state.authKey = Guid.Empty;
state.SaveToRegistry();
MessageBox.Show(
"All devices which control this computer have been signed out.",
"Success",
MessageBoxButtons.OK,
MessageBoxIcon.Information
);
return true;
}
else
{
MessageBox.Show(
"Failed to sign all users out. Please try again later.",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
return false;
}
}
}
}