-
Notifications
You must be signed in to change notification settings - Fork 1
/
AppTray.cs
556 lines (490 loc) · 21.8 KB
/
AppTray.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
using AudiobookshelfTray.Properties;
using Microsoft.Win32;
using NLog;
using Octokit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AudiobookshelfTray
{
public class AppTray : ApplicationContext
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly Logger _serverLogger = LogManager.GetLogger("Server");
private readonly string _appName = "Audiobookshelf";
private readonly string _serverFilename = "audiobookshelf.exe";
private readonly string _trayAppName = "AudiobookshelfTray";
private readonly string _repoOwner = "mikiher";
private readonly string _repoName = "audiobookshelf-windows";
private readonly string _appVersion;
private readonly System.Timers.Timer _dailyTimer = new();
private Process _serverProcess = null;
private ServerLogs _serverLogsForm = null;
private bool _shouldExit = false;
private bool _runInstall = false;
private string _installerPath;
private readonly NotifyIcon _trayIcon;
private readonly ToolStripMenuItem _stopServerMenuItem;
private readonly ToolStripMenuItem _startServerMenuItem;
private readonly ToolStripMenuItem _openServerMenuItem;
private readonly ToolStripMenuItem _serverLogsMenuItem;
private readonly ToolStripMenuItem _aboutMenuItem;
private readonly ToolStripMenuItem _startAtLoginCheckboxMenuItem;
private readonly ToolStripMenuItem _autoCheckForUpdatesCheckboxMenuItem;
private readonly ToolStripMenuItem _settingsMenuItem;
private readonly ToolStripMenuItem _checkForUpdatesMenuItem;
private readonly List<string> _serverLogsList = [];
private DismissableMessageBox _newVersionAvailableDialog = null;
public AppTray()
{
_appVersion = GetAppVersion();
_stopServerMenuItem = new ToolStripMenuItem("Stop Server", null, StopServerClicked) { Enabled = false };
_startServerMenuItem = new ToolStripMenuItem("Start Server", null, StartServerClicked) { Enabled = false };
_serverLogsMenuItem = new ToolStripMenuItem("Server Logs", null, ShowServerLogsClicked) { Enabled = false };
_openServerMenuItem = new ToolStripMenuItem("Open Audiobookshelf...", null, OpenClicked) { Enabled = false };
_openServerMenuItem.Font = new Font(_openServerMenuItem.Font.Name, _openServerMenuItem.Font.Size, FontStyle.Bold);
_aboutMenuItem = new ToolStripMenuItem("About Audiobookshelf Server", null, AboutClicked);
_startAtLoginCheckboxMenuItem = new ToolStripMenuItem("Start Audiobookshelf at Login") { CheckOnClick = true };
_startAtLoginCheckboxMenuItem.CheckedChanged += StartAtLoginCheckedChanged;
_startAtLoginCheckboxMenuItem.Checked = Settings.Default.StartAtLogin;
_autoCheckForUpdatesCheckboxMenuItem = new ToolStripMenuItem("Automatically Check for Updates") { CheckOnClick = true };
_autoCheckForUpdatesCheckboxMenuItem.CheckedChanged += AutoCheckForUpdatesChanged;
_autoCheckForUpdatesCheckboxMenuItem.Checked = Settings.Default.AutoCheckForUpdates;
_settingsMenuItem = new ToolStripMenuItem("Settings", null, SettingsClicked);
_checkForUpdatesMenuItem = new ToolStripMenuItem("Check for Updates", null, CheckForUpdates);
_dailyTimer.Interval = 24 * 60 * 60 * 1000; // 24 hours
_dailyTimer.Elapsed += CheckForUpdates;
_trayIcon = new NotifyIcon()
{
Icon = Resources.AppIcon,
ContextMenuStrip = new ContextMenuStrip()
{
Items = {
_openServerMenuItem,
_startAtLoginCheckboxMenuItem,
_autoCheckForUpdatesCheckboxMenuItem,
_settingsMenuItem,
new ToolStripSeparator(),
_stopServerMenuItem,
_startServerMenuItem,
_serverLogsMenuItem,
new ToolStripSeparator(),
_aboutMenuItem,
_checkForUpdatesMenuItem,
new ToolStripSeparator(),
new ToolStripMenuItem("Exit", null, ExitClicked)
},
//Font = new Font("Segoe UI", 8.25f, System.Drawing.FontStyle.Regular)
},
Visible = true,
Text = _appName
};
// Check if we need to upgrade settings from previous version
if (Settings.Default.UpgradeRequired)
{
Settings.Default.Upgrade();
Settings.Default.UpgradeRequired = false;
Settings.Default.Save();
}
//_serverBinDir = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Audiobookshelf", "InstallDir",
// Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", _appName)) as string;
// Create a hidden window to handle WM_CLOSE messages
MainForm = new Form
{
Text = _trayAppName,
ShowInTaskbar = false,
WindowState = FormWindowState.Minimized,
FormBorderStyle = FormBorderStyle.FixedToolWindow,
Opacity = 0,
};
MainForm.Load += (sender, e) => { if (_shouldExit) ExitClicked(sender, e); };
Init();
}
private void AutoCheckForUpdatesChanged(object sender, EventArgs e)
{
_logger.Debug("AutoCheckForUpdatesChanged");
Settings.Default.AutoCheckForUpdates = _autoCheckForUpdatesCheckboxMenuItem.Checked;
Settings.Default.Save();
if (Settings.Default.AutoCheckForUpdates)
{
CheckForUpdates(sender, e);
_dailyTimer.Start();
}
else
{
_dailyTimer.Stop();
}
}
public string GetServerDataDir()
{
string serverDataDir = Settings.Default.DataDir;
string registryServerDataDir = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Audiobookshelf", "DataDir", null) as string;
if (string.IsNullOrEmpty(serverDataDir))
{
string defaultDataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), _appName);
serverDataDir = registryServerDataDir ?? defaultDataDir;
}
if (!Directory.Exists(serverDataDir))
{
try
{
Directory.CreateDirectory(serverDataDir);
}
catch (Exception e)
{
_logger.Error(e.ToString());
MessageBox.Show("Failed to create server data directory at " + serverDataDir, "Audiobookshelf", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
if (serverDataDir != registryServerDataDir || serverDataDir != Settings.Default.DataDir)
SaveServerDataDir(serverDataDir);
return serverDataDir;
}
public void SaveServerDataDir(string serverDataDir)
{
Settings.Default.DataDir = serverDataDir;
Settings.Default.Save();
Registry.SetValue(@"HKEY_CURRENT_USER\Software\Audiobookshelf", "DataDir", serverDataDir);
}
public string GetAppVersion()
{
string appVersion = Settings.Default.AppVersion;
string registryAppVersion = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Audiobookshelf", "AppVersion", null) as string;
if (registryAppVersion != null && registryAppVersion != appVersion)
SaveAppVersion(registryAppVersion);
return registryAppVersion ?? appVersion;
}
public void SaveAppVersion(string appVersion)
{
Settings.Default.AppVersion = appVersion;
Settings.Default.Save();
}
public string GetServerPort()
{
return Settings.Default.ServerPort;
}
public void SaveServerPort(string serverPort)
{
Settings.Default.ServerPort = serverPort;
Settings.Default.Save();
}
private void SettingsClicked(object sender, EventArgs e)
{
SettingsDialog settingsDialog = new(this);
settingsDialog.ShowDialog();
}
private void Init()
{
// Start server
if (!StartServer())
_shouldExit = true;
_openServerMenuItem.Enabled = true;
_serverLogsMenuItem.Enabled = true;
_trayIcon.DoubleClick += OpenClicked;
_trayIcon.BalloonTipClicked += BalloonTipClicked;
System.Windows.Forms.Application.ApplicationExit += ApplicationExited;
}
private void StartAtLoginCheckedChanged(object sender, EventArgs e)
{
RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (_startAtLoginCheckboxMenuItem.Checked)
{
_logger.Debug("Adding to startup");
rk.SetValue("Audiobookshelf", System.Windows.Forms.Application.ExecutablePath);
Settings.Default.StartAtLogin = true;
}
else
{
_logger.Debug("Removing from startup");
rk.DeleteValue("Audiobookshelf", false);
Settings.Default.StartAtLogin = false;
}
Settings.Default.Save();
}
private void AboutClicked(object sender, EventArgs e)
{
AboutBox aboutBox = new();
aboutBox.ShowDialog();
}
private void ApplicationExited(object sender, EventArgs e)
{
_logger.Debug("About to exit...");
StopServer();
if (_runInstall)
{
Process installerProcess = new()
{
StartInfo = new ProcessStartInfo()
{
Arguments = "/SILENT",
FileName = _installerPath,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = false
},
EnableRaisingEvents = true
};
installerProcess.Start();
}
}
public void ExitClicked(object sender, EventArgs e)
{
_trayIcon.Visible = false;
System.Windows.Forms.Application.Exit();
}
public void StopServerClicked(object sender, EventArgs e)
{
StopServer();
}
public void StartServerClicked(object sender, EventArgs e)
{
StartServer();
}
public void OpenClicked(object sender, EventArgs e)
{
// Server already started,
if (_serverProcess != null)
{
// just open the browser.
OpenBrowser();
}
// Server not started,
else
{
// ask master if we should start it.
if (MessageBox.Show("Server not started, start server?", "Audiobookshelf", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
// Lets do what our master told us to do.
StartServer();
};
}
}
public void ShowServerLogsClicked(object sender, EventArgs e)
{
_serverLogsForm = new ServerLogs();
_serverLogsForm.Show();
_serverLogsForm.SetLogs(_serverLogsList);
}
public void BalloonTipClicked(object sender, EventArgs e)
{
OpenBrowser();
}
private void StopServer()
{
if (_serverProcess != null)
{
_logger.Debug("Stopping server...");
ProcessUtils.StopProcess(_serverProcess);
_serverProcess = null;
_logger.Debug("Server stopped");
}
}
private bool StartServer()
{
if (_serverProcess != null)
{
_logger.Debug("Server already started");
return false;
}
string serverBinDir = System.Windows.Forms.Application.StartupPath;
_logger.Debug("Server binary dir: " + serverBinDir);
string serverBinPath = Path.Combine(serverBinDir, _serverFilename);
_logger.Debug("Server binary path: " + serverBinPath);
// Check if server binary exists
if (!File.Exists(serverBinPath))
{
_logger.Error("Server binary not found at " + serverBinPath);
MessageBox.Show("Server binary not found at " + serverBinPath, "Audiobookshelf", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
string serverDataDir = GetServerDataDir();
if (serverDataDir == null)
return false;
string configPath = Path.Combine(serverDataDir, "config");
string metadataPath = Path.Combine(serverDataDir, "metadata");
string serverPort = Settings.Default.ServerPort;
_logger.Debug("Starting service");
_serverProcess = new Process
{
StartInfo = new ProcessStartInfo()
{
Arguments = " -p " + serverPort + " --config \"" + configPath + "\" --metadata \"" + metadataPath + "\" --source windows",
FileName = serverBinPath,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
CreateNoWindow = true,
UseShellExecute = false
},
EnableRaisingEvents = true
};
_serverProcess.OutputDataReceived += HandleServerOutput;
_serverProcess.ErrorDataReceived += HandleServerOutput;
_serverProcess.Exited += ServerExited;
// Start the ABS Server process.
_serverProcess.Start();
_serverProcess.BeginOutputReadLine();
_serverProcess.BeginErrorReadLine();
// Show an alert that we started the server.
_trayIcon.ShowBalloonTip(500, "Audiobookshelf", "Server started", ToolTipIcon.Info);
// Fix up the context menu stuff
_startServerMenuItem.Enabled = false;
_stopServerMenuItem.Enabled = true;
return true;
}
private void ServerExited(object sender, EventArgs e)
{
// check if this is happening in the UI thread
if (_trayIcon.ContextMenuStrip.InvokeRequired)
{
_trayIcon.ContextMenuStrip.Invoke(new MethodInvoker(delegate
{
ServerExited(sender, e);
}));
return;
}
Process process = sender as Process;
_logger.Debug("sender exit code: " + process.ExitCode);
// check if server exited with error
if (process.ExitCode != 0)
{
_logger.Error("Server exited with error code " + process.ExitCode);
_trayIcon.ShowBalloonTip(500, "Audiobookshelf", "Server exited with error code " + process.ExitCode, ToolTipIcon.Error);
}
else
{
_logger.Debug("Server exited");
_trayIcon.ShowBalloonTip(500, "Audiobookshelf", "Server exited", ToolTipIcon.Info);
}
// Fix up the context menu stuff
_startServerMenuItem.Enabled = true;
_stopServerMenuItem.Enabled = false;
}
private void OpenBrowser()
{
if (_serverProcess == null) return;
Process.Start("http://localhost:" + Settings.Default.ServerPort);
}
// Why??
private void HandleServerOutput(object sendingProcess, DataReceivedEventArgs outLine)
{
if (outLine.Data == null || outLine.Data == "")
{
return;
}
if (outLine.Data.Contains("[Server] Init"))
{
// Extract server version from init log line
System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(outLine.Data, @"v\d+\.\d+\.\d+$");
if (match.Success)
{
Settings.Default.ServerVersion = match.Value;
Settings.Default.Save();
}
else
{
_logger.Error("Failed to parse server version from init log line " + outLine.Data);
}
}
_serverLogger.Debug(outLine.Data);
_serverLogsList.Add(outLine.Data);
if (_serverLogsForm != null && !_serverLogsForm.IsDisposed)
{
// Server logs form is open add line
_serverLogsForm.AddLogLine(outLine.Data);
}
}
private async void CheckForUpdates(object sender, EventArgs e)
{
// Find latest release on GitHub
GitHubClient client = new(new ProductHeaderValue(_trayAppName));
IReadOnlyList<Release> releases = await client.Repository.Release.GetAll(_repoOwner, _repoName);
Release latestRelease = releases[0];
_logger.Debug("Latest release: " + latestRelease.TagName);
_logger.Debug("Current release: " + _appVersion);
if(_newVersionAvailableDialog != null)
{
_newVersionAvailableDialog.Dismiss();
}
if (latestRelease.TagName != _appVersion)
{
// Find installer asset
ReleaseAsset exeAsset = latestRelease.Assets.First(asset => asset.Name.EndsWith(".exe"));
if (exeAsset == null)
{
_logger.Error("No exe asset found");
MessageBox.Show("Failed to find installer for the latest release.", "Audiobookshelf", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Ask user if they want to download and install the new version
_newVersionAvailableDialog = new DismissableMessageBox("Audiobookshelf Update");
DialogResult result = _newVersionAvailableDialog.Show("A New version " + latestRelease.TagName + " is available.\nDownload and install it?", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
_newVersionAvailableDialog = null;
if (result == DialogResult.Yes)
{
// Download the new installer to a temp directory and run it
string tempDir = Path.Combine(Path.GetTempPath(), "Audiobookshelf");
if (!Directory.Exists(tempDir))
{
Directory.CreateDirectory(tempDir);
}
_installerPath = Path.Combine(tempDir, exeAsset.Name);
if (await DownloadInstaller(exeAsset.BrowserDownloadUrl))
{
MessageBox.Show("About to install new version. Audiobookshelf will exit now.", "Audiobookshelf", MessageBoxButtons.OK, MessageBoxIcon.Information);
_runInstall = true;
ExitClicked(sender, e);
}
else
{
_logger.Error("Failed to download installer");
MessageBox.Show("Failed to download installer", "Audiobookshelf", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
else
{
// silent if called from timer or autoCheckForUpdates checkbox
if (sender == _checkForUpdatesMenuItem)
{
MessageBox.Show("No updates available", "Audiobookshelf", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
private async Task<bool> DownloadInstaller(string downloadUrl)
{
_logger.Debug("Downloading installer to " + _installerPath);
System.Net.Http.HttpClient httpClient = new();
System.Net.Http.HttpResponseMessage response = await httpClient.GetAsync(downloadUrl);
if (response.IsSuccessStatusCode)
{
try
{
using Stream stream = await response.Content.ReadAsStreamAsync();
using FileStream fileStream = new(_installerPath, System.IO.FileMode.Create, FileAccess.Write);
await stream.CopyToAsync(fileStream);
_logger.Debug("Downloaded installer to " + _installerPath);
fileStream.Close();
return true;
}
catch (Exception ex)
{
_logger.Error("Failed to download installer: " + ex.ToString());
return false;
}
}
else
{
_logger.Error("Failed to download installer: " + response.StatusCode);
return false;
}
}
}
}