-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommon.cs
More file actions
303 lines (269 loc) · 8.87 KB
/
Common.cs
File metadata and controls
303 lines (269 loc) · 8.87 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
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
using System.Diagnostics;
using Microsoft.Win32;
using Microsoft.Toolkit.Uwp.Notifications;
using BC = BCrypt.Net;
namespace AutoLogout
{
public static class Common
{
public static string exePath
{
get
{
return Process.GetCurrentProcess().MainModule?.FileName
?? throw new Exception("Unable to get current executable name.");
}
}
public static void Relaunch(string args)
{
var startInfo = new ProcessStartInfo(exePath)
{
UseShellExecute = true,
Arguments = args
};
try
{
Process.Start(startInfo);
}
catch
{
// User cancelled UAC
}
}
public static void RelaunchAsAdmin(string args)
{
var startInfo = new ProcessStartInfo(exePath)
{
UseShellExecute = true,
Verb = "runas",
Arguments = args
};
try
{
Process.Start(startInfo);
}
catch
{
// User cancelled UAC
}
}
public static void RegisterStartup(bool enable)
{
string appName = "AutoLogout";
using RegistryKey? key = Registry.LocalMachine.OpenSubKey(
@"Software\Microsoft\Windows\CurrentVersion\Run", true
);
if (key is null) throw new Exception("System startup registry doesn't exist!");
if (enable)
{
key.SetValue(appName, $"\"{exePath}\" --service");
new ToastContentBuilder()
.AddText("AutoLogout Setup")
.AddText("AutoLogout has been configured to start on login.")
.Show();
}
else
{
key.DeleteValue(appName, false);
new ToastContentBuilder()
.AddText("AutoLogout Setup")
.AddText("AutoLogout will no longer start on login.")
.Show();
}
}
}
public class State
{
#if DEBUG
public static string REGKEY = "Software\\Yiays\\AutoLogout-Preview";
#else
public static string REGKEY = "Software\\Yiays\\AutoLogout";
#endif
public bool OnlineMode = false;
public bool ExitIntent = false;
public bool Paused = false;
public Guid authKey = Guid.Empty;
public Guid uuid = Guid.Empty;
public string hashedPassword = "";
public int dailyTimeLimit = -1;
public int todayTimeLimit = -1;
public int tempTimeLimit = -1; // This stores temporary overrides to the time limit. Takes priority over bedtime
public int bedtimeTimeLimit = -1; // This stores bedtime-related overrides to the time limit
private int realTimeLimit { get => tempTimeLimit != -1 ? tempTimeLimit : bedtimeTimeLimit != -1 && bedtimeTimeLimit < todayTimeLimit ? bedtimeTimeLimit : todayTimeLimit; }
public int remainingTime { get => realTimeLimit == -1 ? -1 : Math.Max(realTimeLimit - usedTime, 0); }
public int usedTime = 0;
public DateOnly usageDate = DateOnly.FromDateTime(DateTime.Today);
public TimeOnly bedtime = new TimeOnly(0, 0);
public TimeOnly waketime = new TimeOnly(0, 0);
public bool graceGiven = false;
public Guid? syncAuthor = null;
public event Action? Changed;
public API api = new();
public void NewGuid()
{
uuid = Guid.NewGuid();
}
public void TriggerStateChanged()
{
Changed?.Invoke();
}
public int FromRegistry()
{
RegistryKey? key = Registry.CurrentUser.CreateSubKey(REGKEY, true);
if (key == null)
{
MessageBox.Show("Unable to access settings.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return -1;
}
// Load current app state from registry
OnlineMode = bool.Parse((string)key.GetValue("OnlineMode", "false"));
string? rawAuthKey = (string?)key.GetValue("authKey", null);
authKey = rawAuthKey is null ? Guid.Empty : new Guid(rawAuthKey);
string? rawGuid = (string?)key.GetValue("guid", null);
uuid = rawGuid is null ? Guid.Empty : new Guid(rawGuid);
hashedPassword = (string)key.GetValue("password", "");
string bedtimeRaw = (string)key.GetValue("bedtime", "0:00");
bedtime = TimeOnly.Parse(bedtimeRaw);
string waketimeRaw = (string)key.GetValue("waketime", "0:00");
waketime = TimeOnly.Parse(waketimeRaw);
dailyTimeLimit = (int)key.GetValue("dailyTimeLimit", -1);
usageDate = DateOnly.Parse((string)key.GetValue("usageDate", "1/01/0001"));
todayTimeLimit = (int)key.GetValue("todayTimeLimit", -1);
usedTime = (int)key.GetValue("usedTime", 0);
return 0;
}
public int SaveToRegistry()
{
RegistryKey? key = Registry.CurrentUser.CreateSubKey(REGKEY);
if (key == null)
{
MessageBox.Show("Unable to save settings.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
ExitIntent = true;
return -1;
}
key.SetValue("OnlineMode", OnlineMode);
key.SetValue("authKey", authKey);
key.SetValue("guid", uuid);
key.SetValue("password", hashedPassword);
key.SetValue("usageDate", DateOnly.FromDateTime(DateTime.Today));
key.SetValue("dailyTimeLimit", dailyTimeLimit);
key.SetValue("todayTimeLimit", todayTimeLimit);
key.SetValue("usedTime", usedTime);
key.SetValue("bedtime", bedtime);
key.SetValue("waketime", waketime);
return 0;
}
public static void ClearRegistry()
{
Registry.CurrentUser.DeleteSubKeyTree(REGKEY);
}
public void AcceptDelta(API.Delta delta)
{
// Update local state with server response
dailyTimeLimit = delta.dailyTimeLimit ?? dailyTimeLimit;
todayTimeLimit = delta.todayTimeLimit ?? todayTimeLimit;
usedTime = delta.usedTime ?? usedTime;
usageDate = delta.usageDate ?? usageDate;
bedtime = delta.bedtime ?? bedtime;
waketime = delta.waketime ?? waketime;
graceGiven = delta.graceGiven ?? graceGiven;
syncAuthor = delta.syncAuthor;
}
public bool NewPassword()
{
string? newPassword = Prompt.ShowDialog("Enter a new parent password.", "AutoLogout", true);
if (newPassword == null)
{
return false;
}
hashedPassword = BC.BCrypt.HashPassword(newPassword);
SaveToRegistry();
return true;
}
public bool CheckPassword()
{
string? password = Prompt.ShowDialog("Enter the parent password to continue.", "AutoLogout Settings", true);
if (password == null) return false;
if (BC.BCrypt.Verify(password, hashedPassword)) return true;
else
{
MessageBox.Show("The password was incorrect", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
// API methods
public async Task Sync()
{
if (OnlineMode)
{
await api.Sync(this);
}
}
public async Task Deauth()
{
OnlineMode = false;
if (!await api.Deauth(this))
{
OnlineMode = true;
}
else
{
Changed?.Invoke();
}
SaveToRegistry();
}
}
public static class Prompt
{
private partial class PromptForm : Form
{
public TextBox textBox;
public PromptForm(string text, string caption, bool sensitive = false)
{
FormBorderStyle = FormBorderStyle.FixedDialog;
Text = caption;
Icon = new Icon("Resources/icon-light.ico");
StartPosition = FormStartPosition.CenterScreen;
MinimizeBox = false;
MaximizeBox = false;
BackColor = Color.White;
Width = 350;
Height = 200;
AutoScaleMode = AutoScaleMode.Dpi;
AutoScaleDimensions = new(96F, 96F);
FlowLayoutPanel mainPanel = new()
{
Dock = DockStyle.Top,
FlowDirection = FlowDirection.TopDown,
Padding = new Padding(12),
};
FlowLayoutPanel buttonPanel = new()
{
Dock = DockStyle.Bottom,
AutoSize = true,
BackColor = SystemColors.Control,
Padding = new Padding(8),
};
Label textLabel = new() { MaximumSize = new Size(576, 100), AutoSize = true, Text = text, Padding = new() { Bottom = 10 } };
textBox = new() { Width = 300 };
if (sensitive) textBox.PasswordChar = '*';
mainPanel.Controls.Add(textLabel);
mainPanel.Controls.Add(textBox);
Button confirmation = new() { Text = "Ok", AutoSize = true, DialogResult = DialogResult.OK };
Button cancel = new() { Text = "Cancel", AutoSize = true, DialogResult = DialogResult.Cancel };
confirmation.Click += (sender, e) => { Close(); };
buttonPanel.Controls.Add(confirmation);
buttonPanel.Controls.Add(cancel);
Controls.Add(mainPanel);
Controls.Add(buttonPanel);
AcceptButton = confirmation;
CancelButton = cancel;
}
}
public static string? ShowDialog(string text, string caption, bool sensitive = false)
{
PromptForm prompt = new(text, caption, sensitive);
return prompt.ShowDialog() == DialogResult.OK ? prompt.textBox.Text : null;
}
}
}