Winify – Blame information for rev 30

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 office 1 using System;
25 office 2 using System.Collections.Concurrent;
1 office 3 using System.ComponentModel;
30 office 4 using System.Drawing;
4 office 5 using System.IO;
30 office 6 using System.Reflection;
15 office 7 using System.Text;
19 office 8 using System.Threading;
4 office 9 using System.Threading.Tasks;
1 office 10 using System.Windows.Forms;
30 office 11 using NetSparkleUpdater;
12 using NetSparkleUpdater.Enums;
13 using NetSparkleUpdater.SignatureVerifiers;
14 using NetSparkleUpdater.UI.WinForms;
18 office 15 using Serilog;
15 office 16 using Servers;
29 office 17 using Toasts;
1 office 18 using Winify.Gotify;
25 office 19 using Winify.Settings;
15 office 20 using Winify.Utilities;
30 office 21 using Winify.Utilities.Serialization;
1 office 22  
23 namespace Winify
24 {
30 office 25 public partial class MainForm : Form
1 office 26 {
30 office 27 #region Public Enums, Properties and Fields
28  
29 public Configuration.Configuration Configuration { get; set; }
30  
31 public ScheduledContinuation ChangedConfigurationContinuation { get; set; }
32  
33 #endregion
34  
1 office 35 #region Private Delegates, Events, Enums, Properties, Indexers and Fields
36  
37 private AboutForm _aboutForm;
38  
25 office 39 private ConcurrentBag<GotifyConnection> _gotifyConnections;
1 office 40  
41 private SettingsForm _settingsForm;
42  
30 office 43 private readonly SparkleUpdater _sparkle;
44  
45 private readonly CancellationTokenSource _cancellationTokenSource;
46  
47 private readonly CancellationToken _cancellationToken;
48  
1 office 49 #endregion
50  
51 #region Constructors, Destructors and Finalizers
52  
30 office 53 public MainForm()
1 office 54 {
30 office 55 _cancellationTokenSource = new CancellationTokenSource();
56 _cancellationToken = _cancellationTokenSource.Token;
57  
58 ChangedConfigurationContinuation = new ScheduledContinuation();
59 }
60  
61 public MainForm(Mutex mutex) : this()
62 {
1 office 63 InitializeComponent();
64  
18 office 65 Log.Logger = new LoggerConfiguration()
66 .MinimumLevel.Debug()
67 .WriteTo.File(Path.Combine(Constants.UserApplicationDirectory, "Logs", $"{Constants.AssemblyName}.log"),
68 rollingInterval: RollingInterval.Day)
69 .CreateLogger();
70  
30 office 71 // Start application update.
72 var manifestModuleName = Assembly.GetEntryAssembly().ManifestModule.FullyQualifiedName;
73 var icon = Icon.ExtractAssociatedIcon(manifestModuleName);
19 office 74  
30 office 75 _sparkle = new SparkleUpdater("https://winify.grimore.org/update/appcast.xml",
76 new Ed25519Checker(SecurityMode.Strict, "LonrgxVjSF0GnY4hzwlRJnLkaxnDn2ikdmOifILzLJY="))
4 office 77 {
30 office 78 UIFactory = new UIFactory(icon),
79 RelaunchAfterUpdate = true
80 };
81 _sparkle.StartLoop(true, true);
1 office 82 }
83  
84 /// <summary>
85 /// Clean up any resources being used.
86 /// </summary>
87 /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
88 protected override void Dispose(bool disposing)
89 {
30 office 90 if (disposing && components != null) components.Dispose();
7 office 91  
1 office 92 base.Dispose(disposing);
93 }
94  
95 #endregion
96  
97 #region Event Handlers
98  
30 office 99 private async void MainForm_Load(object sender, EventArgs e)
21 office 100 {
30 office 101 Configuration = await LoadConfiguration();
21 office 102  
30 office 103 var servers = await LoadServers();
104 _gotifyConnections = new ConcurrentBag<GotifyConnection>();
105 foreach (var server in servers.Server)
106 {
107 var gotifyConnection = new GotifyConnection(server);
108 gotifyConnection.GotifyNotification += GotifyConnection_GotifyNotification;
109 gotifyConnection.Start();
110 _gotifyConnections.Add(gotifyConnection);
111 }
21 office 112 }
113  
25 office 114 private async void SettingsToolStripMenuItem_Click(object sender, EventArgs e)
11 office 115 {
30 office 116 if (_settingsForm == null)
117 {
118 var servers = await LoadServers();
119 var announcements = await LoadAnnouncements();
25 office 120  
30 office 121 _settingsForm = new SettingsForm(this, servers, announcements, _cancellationToken);
122 _settingsForm.Save += SettingsForm_Save;
123 _settingsForm.Closing += SettingsForm_Closing;
124 _settingsForm.Show();
125 }
25 office 126 }
127  
128 private async void SettingsForm_Save(object sender, SettingsSavedEventArgs e)
129 {
130 // Save the servers.
131 await Task.WhenAll(SaveServers(e.Servers), SaveAnnouncements(e.Announcements));
132  
133 // Update connections to gotify servers.
134 while (_gotifyConnections.TryTake(out var gotifyConnection))
135 {
136 gotifyConnection.GotifyNotification -= GotifyConnection_GotifyNotification;
137 gotifyConnection.Stop();
138 gotifyConnection.Dispose();
139 gotifyConnection = null;
140 }
141  
142 foreach (var server in e.Servers.Server)
143 {
144 var gotifyConnection = new GotifyConnection(server);
145 gotifyConnection.GotifyNotification += GotifyConnection_GotifyNotification;
146 gotifyConnection.Start();
147 _gotifyConnections.Add(gotifyConnection);
148 }
149 }
150  
30 office 151 private async void GotifyConnection_GotifyNotification(object sender, GotifyNotificationEventArgs e)
25 office 152 {
30 office 153 var announcements = await LoadAnnouncements();
25 office 154  
30 office 155 foreach (var announcement in announcements.Announcement)
156 if (announcement.AppId == e.Notification.AppId)
157 {
158 var configuredNotification = new ToastForm(
159 $"{e.Notification.Title} ({e.Notification.Server.Name}/{e.Notification.AppId})",
160 e.Notification.Message, announcement.LingerTime, e.Image);
24 office 161  
30 office 162 configuredNotification.Show();
24 office 163  
30 office 164 return;
165 }
24 office 166  
30 office 167 var notification = new ToastForm(
168 $"{e.Notification.Title} ({e.Notification.Server.Name}/{e.Notification.AppId})",
169 e.Notification.Message, 5000, e.Image);
24 office 170  
30 office 171 notification.Show();
11 office 172 }
173  
1 office 174 private void SettingsForm_Closing(object sender, CancelEventArgs e)
175 {
28 office 176 if (_settingsForm == null) return;
6 office 177  
25 office 178 _settingsForm.Save -= SettingsForm_Save;
1 office 179 _settingsForm.Closing -= SettingsForm_Closing;
180 _settingsForm.Dispose();
181 _settingsForm = null;
182 }
183  
184 private void AboutToolStripMenuItem_Click(object sender, EventArgs e)
185 {
28 office 186 if (_aboutForm != null) return;
1 office 187  
188 _aboutForm = new AboutForm();
189 _aboutForm.Closing += AboutForm_Closing;
190 _aboutForm.Show();
191 }
192  
193 private void AboutForm_Closing(object sender, CancelEventArgs e)
194 {
28 office 195 if (_aboutForm == null) return;
1 office 196  
197 _aboutForm.Closing -= AboutForm_Closing;
198 _aboutForm.Dispose();
199 _aboutForm = null;
200 }
201  
202 private void QuitToolStripMenuItem_Click(object sender, EventArgs e)
203 {
17 office 204 Close();
30 office 205 }
17 office 206  
30 office 207 private async void UpdateToolStripMenuItem_Click(object sender, EventArgs e)
208 {
209 // Manually check for updates, this will not show a ui
210 var result = await _sparkle.CheckForUpdatesQuietly();
211 if (result.Status == UpdateStatus.UpdateAvailable)
212 {
213 // if update(s) are found, then we have to trigger the UI to show it gracefully
214 _sparkle.ShowUpdateNeededUI();
215 return;
216 }
217  
218 MessageBox.Show("No updates available at this time.", "Horizon", MessageBoxButtons.OK,
219 MessageBoxIcon.Asterisk,
220 MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false);
1 office 221 }
222  
30 office 223 #endregion
224  
225 #region Public Methods
226  
227 public async Task SaveConfiguration()
9 office 228 {
30 office 229 if (!Directory.Exists(Constants.UserApplicationDirectory))
230 Directory.CreateDirectory(Constants.UserApplicationDirectory);
231  
232 switch (await Serialization.Serialize(Configuration, Constants.ConfigurationFile, "Configuration",
233 "<!ATTLIST Configuration xmlns:xsi CDATA #IMPLIED xsi:noNamespaceSchemaLocation CDATA #IMPLIED>",
234 CancellationToken.None))
235 {
236 case SerializationSuccess<Configuration.Configuration> _:
237 Log.Information("Serialized configuration.");
238 break;
239 case SerializationFailure serializationFailure:
240 Log.Warning(serializationFailure.Exception.Message, "Failed to serialize configuration.");
241 break;
242 }
9 office 243 }
244  
30 office 245 public static async Task<Configuration.Configuration> LoadConfiguration()
246 {
247 if (!Directory.Exists(Constants.UserApplicationDirectory))
248 Directory.CreateDirectory(Constants.UserApplicationDirectory);
249  
250 var deserializationResult =
251 await Serialization.Deserialize<Configuration.Configuration>(Constants.ConfigurationFile,
252 Constants.ConfigurationNamespace, Constants.ConfigurationXsd, CancellationToken.None);
253  
254 switch (deserializationResult)
255 {
256 case SerializationSuccess<Configuration.Configuration> serializationSuccess:
257 return serializationSuccess.Result;
258 case SerializationFailure serializationFailure:
259 Log.Warning(serializationFailure.Exception, "Failed to load configuration.");
260 return new Configuration.Configuration();
261 default:
262 return new Configuration.Configuration();
263 }
264 }
265  
1 office 266 #endregion
4 office 267  
268 #region Private Methods
269  
25 office 270 private static async Task SaveAnnouncements(Announcements.Announcements announcements)
21 office 271 {
30 office 272 switch (await Serialization.Serialize(announcements, Constants.AnnouncementsFile, "Announcements",
273 "<!ATTLIST Announcements xmlns:xsi CDATA #IMPLIED xsi:noNamespaceSchemaLocation CDATA #IMPLIED>",
274 CancellationToken.None))
21 office 275 {
276 case SerializationFailure serializationFailure:
277 Log.Warning(serializationFailure.Exception, "Unable to serialize announcements.");
278 break;
279 }
280 }
281  
30 office 282 private static async Task SaveServers(Servers.Servers servers)
21 office 283 {
284 // Encrypt password for all servers.
285 var deviceId = Miscellaneous.GetMachineGuid();
30 office 286 var @protected = new Servers.Servers
21 office 287 {
288 Server = new BindingListWithCollectionChanged<Server>()
289 };
25 office 290 foreach (var server in servers.Server)
21 office 291 {
292 var encrypted = AES.Encrypt(Encoding.UTF8.GetBytes(server.Password), deviceId);
293 var armored = Convert.ToBase64String(encrypted);
294  
295 @protected.Server.Add(new Server(server.Name, server.Url, server.Username, armored));
296 }
297  
30 office 298 switch (await Serialization.Serialize(@protected, Constants.ServersFile, "Servers",
299 "<!ATTLIST Servers xmlns:xsi CDATA #IMPLIED xsi:noNamespaceSchemaLocation CDATA #IMPLIED>",
300 CancellationToken.None))
21 office 301 {
302 case SerializationFailure serializationFailure:
303 Log.Warning(serializationFailure.Exception, "Unable to serialize servers.");
304 break;
305 }
306 }
307  
15 office 308 private static async Task<Announcements.Announcements> LoadAnnouncements()
309 {
310 if (!Directory.Exists(Constants.UserApplicationDirectory))
311 Directory.CreateDirectory(Constants.UserApplicationDirectory);
312  
313 var deserializationResult =
30 office 314 await Serialization.Deserialize<Announcements.Announcements>(Constants.AnnouncementsFile,
315 "urn:winify-announcements-schema", "Announcements.xsd", CancellationToken.None);
15 office 316  
317 switch (deserializationResult)
318 {
319 case SerializationSuccess<Announcements.Announcements> serializationSuccess:
320 return serializationSuccess.Result;
21 office 321 case SerializationFailure serializationFailure:
322 Log.Warning(serializationFailure.Exception, "Unable to load announcements.");
323 return new Announcements.Announcements();
15 office 324 default:
325 return new Announcements.Announcements();
326 }
327 }
328  
30 office 329 private static async Task<Servers.Servers> LoadServers()
4 office 330 {
331 if (!Directory.Exists(Constants.UserApplicationDirectory))
332 Directory.CreateDirectory(Constants.UserApplicationDirectory);
333  
15 office 334 var deserializationResult =
30 office 335 await Serialization.Deserialize<Servers.Servers>(Constants.ServersFile,
336 "urn:winify-servers-schema", "Servers.xsd", CancellationToken.None);
4 office 337  
338 switch (deserializationResult)
339 {
30 office 340 case SerializationSuccess<Servers.Servers> serializationSuccess:
15 office 341 // Decrypt password.
342 var deviceId = Miscellaneous.GetMachineGuid();
30 office 343 var @protected = new Servers.Servers
15 office 344 {
345 Server = new BindingListWithCollectionChanged<Server>()
346 };
347 foreach (var server in serializationSuccess.Result.Server)
348 {
349 var unarmored = Convert.FromBase64String(server.Password);
350 var decrypted = Encoding.UTF8.GetString(AES.Decrypt(unarmored, deviceId));
4 office 351  
15 office 352 @protected.Server.Add(new Server(server.Name, server.Url, server.Username, decrypted));
353 }
354  
355 return @protected;
356  
21 office 357 case SerializationFailure serializationFailure:
358 Log.Warning(serializationFailure.Exception, "Unable to load servers.");
30 office 359 return new Servers.Servers();
21 office 360  
4 office 361 default:
30 office 362 return new Servers.Servers();
4 office 363 }
364 }
365  
366 #endregion
1 office 367 }
368 }