using System.Diagnostics; using System.IO.Compression; using System.Reflection; using System.Security.Cryptography; using System.Text.Json; using Microsoft.Web.WebView2.Core; using Microsoft.Web.WebView2.WinForms; namespace ProjectDashboard; static class Program { [STAThread] static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new MainForm()); } } // One window: makes sure the Node server runs, then shows // http://127.0.0.1:4848 in WebView2. A server that is already running // (second window, start-dashboard.bat) is reused and left alone. // // Two modes: // source - server.js lies next to the exe (Michi's _Tools\ProjectDashboard): // system Node, data in the app's .cache folder. // portable - the exe carries everything as embedded payload.zip (node.exe + // dashboard files) and unpacks it once to %LOCALAPPDATA%\ProjectDashboard\app\. sealed class MainForm : Form { // DASHBOARD_PORT (also read by server.js) allows a second instance, e.g. for tests static readonly int Port = int.TryParse(Environment.GetEnvironmentVariable("DASHBOARD_PORT"), out var p) ? p : 4848; static readonly string BaseUrl = $"http://127.0.0.1:{Port}/"; // DASHBOARD_HOME moves everything (window state, WebView2, unpacked app, data) - used for tests static readonly string DataDir = Environment.GetEnvironmentVariable("DASHBOARD_HOME") is { Length: > 0 } home ? Path.GetFullPath(home) : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ProjectDashboard"); const string WebView2Download = "https://go.microsoft.com/fwlink/p/?LinkId=2124703"; string appDir = AppContext.BaseDirectory; bool portable; readonly WebView2 web = new() { Dock = DockStyle.Fill, Visible = false }; readonly Label status = new() { Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleCenter, Font = new Font("Segoe UI", 12f), ForeColor = Color.FromArgb(107, 113, 131), }; Process? server; // only set when this window started the server StreamWriter? serverLog; public MainForm() { Text = "Projekte"; Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); MinimumSize = new Size(900, 560); RestoreWindow(); FormClosing += (_, e) => { if (server != null && BackupRunning() && MessageBox.Show(this, "Das Backup läuft noch.\n\nBeim Schließen wird es abgebrochen (bereits kopierte Dateien bleiben). Trotzdem schließen?", "Projekte", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) { e.Cancel = true; return; } SaveWindow(); }; BackColor = Color.FromArgb(245, 246, 250); status.Text = "Starte Dashboard …"; Controls.Add(web); Controls.Add(status); Shown += async (_, _) => await StartAsync(); FormClosed += (_, _) => StopServer(); } async Task StartAsync() { try { Directory.CreateDirectory(DataDir); if (!await IsServerUp()) { string node; if (File.Exists(Path.Combine(appDir, "server.js"))) { node = FindNode() ?? throw new Exception("Node.js nicht gefunden. Bitte von nodejs.org installieren."); if (!Directory.Exists(Path.Combine(appDir, "node_modules"))) { status.Text = "Installiere einmalig die Abhängigkeiten (npm install) …"; await RunHidden("cmd.exe", "/c npm install --no-audit --no-fund", Path.GetDirectoryName(node)!); } } else { status.Text = "Richte das Dashboard ein …"; appDir = await Task.Run(UnpackPayload); portable = true; node = Path.Combine(appDir, "node", "node.exe"); } StartServer(node); status.Text = "Starte Server …"; var until = DateTime.Now.AddSeconds(25); while (!await IsServerUp()) { if (server is { HasExited: true }) throw new Exception($"Server ist abgestürzt. Details:\n{Path.Combine(DataDir, "server.log")}"); if (DateTime.Now > until) throw new Exception($"Server antwortet nicht (Port {Port} belegt?)."); await Task.Delay(300); } } var env = await CoreWebView2Environment.CreateAsync(null, Path.Combine(DataDir, "WebView2")); await web.EnsureCoreWebView2Async(env); var core = web.CoreWebView2; core.Settings.IsStatusBarEnabled = false; core.Settings.AreDevToolsEnabled = true; // Anything outside the dashboard opens in the normal browser. core.NewWindowRequested += (_, e) => { e.Handled = true; OpenExternal(e.Uri); }; core.NavigationStarting += (_, e) => { if (!e.Uri.StartsWith(BaseUrl, StringComparison.OrdinalIgnoreCase)) { e.Cancel = true; OpenExternal(e.Uri); } }; core.DocumentTitleChanged += (_, _) => Text = core.DocumentTitle; core.WebMessageReceived += OnWebMessage; if (savedZoom is > 0.3 and < 3) web.ZoomFactor = savedZoom; web.Source = new Uri(BaseUrl); web.Visible = true; status.Visible = false; } catch (WebView2RuntimeNotFoundException) { ShowError("Für das Fenster fehlt die „Microsoft Edge WebView2 Runtime“.\n\nHier klicken, um sie herunterzuladen und zu installieren,\ndanach das Dashboard neu starten."); status.Cursor = Cursors.Hand; status.Click += (_, _) => OpenExternal(WebView2Download); } catch (Exception ex) { ShowError("Dashboard konnte nicht starten:\n\n" + ex.Message); } } void ShowError(string text) { status.Text = text; status.ForeColor = Color.FromArgb(220, 38, 38); status.Visible = true; web.Visible = false; } // The page asks for a folder dialog ("Durchsuchen…" in the settings): // { type: "pickFolder", id, title, initial } → { type: "folderPicked", id, path } // or for a file dialog (program to start in "Aktionen"): // { type: "pickFile", id, title, initial } → { type: "filePicked", id, path } void OnWebMessage(object? sender, CoreWebView2WebMessageReceivedEventArgs e) { if (!e.Source.StartsWith(BaseUrl, StringComparison.OrdinalIgnoreCase)) return; try { using var doc = JsonDocument.Parse(e.WebMessageAsJson); var m = doc.RootElement; if (m.ValueKind != JsonValueKind.Object) return; var type = m.GetProperty("type").GetString(); if (type != "pickFolder" && type != "pickFile") return; var id = m.GetProperty("id").GetString() ?? ""; var title = m.TryGetProperty("title", out var t) ? t.GetString() : null; var initial = m.TryGetProperty("initial", out var i) ? i.GetString() : null; if (type == "pickFile") { BeginInvoke(() => { using var fd = new OpenFileDialog { Title = title ?? "Datei wählen", Filter = "Programme und Seiten (*.exe;*.html;*.htm;*.bat;*.cmd;*.lnk)|*.exe;*.html;*.htm;*.bat;*.cmd;*.lnk|Alle Dateien (*.*)|*.*", CheckFileExists = true, DereferenceLinks = false, }; if (!string.IsNullOrWhiteSpace(initial) && Directory.Exists(initial)) fd.InitialDirectory = initial; var file = fd.ShowDialog(this) == DialogResult.OK ? fd.FileName : ""; web.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(new { type = "filePicked", id, path = file })); }); return; } BeginInvoke(() => { using var dlg = new FolderBrowserDialog { Description = title ?? "Ordner wählen", UseDescriptionForTitle = true, ShowNewFolderButton = true, }; if (!string.IsNullOrWhiteSpace(initial) && Directory.Exists(initial)) dlg.InitialDirectory = initial; var path = dlg.ShowDialog(this) == DialogResult.OK ? dlg.SelectedPath : ""; web.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(new { type = "folderPicked", id, path })); }); } catch { } } // Unpacks the embedded payload.zip once per version to \app\ // and removes older versions. Returns the app folder. string UnpackPayload() { var asm = Assembly.GetExecutingAssembly(); using var res = asm.GetManifestResourceStream("payload.zip") ?? throw new Exception("Diese exe enthält kein Dashboard-Paket (server.js fehlt daneben)."); string hash; using (var sha = SHA256.Create()) hash = Convert.ToHexString(sha.ComputeHash(res))[..12].ToLowerInvariant(); var appsRoot = Path.Combine(DataDir, "app"); var target = Path.Combine(appsRoot, hash); if (File.Exists(Path.Combine(target, ".ok"))) return target; Directory.CreateDirectory(appsRoot); var tmp = target + ".tmp"; if (Directory.Exists(tmp)) Directory.Delete(tmp, true); res.Position = 0; using (var zip = new ZipArchive(res, ZipArchiveMode.Read)) zip.ExtractToDirectory(tmp); File.WriteAllText(Path.Combine(tmp, ".ok"), DateTime.Now.ToString("s")); if (Directory.Exists(target)) Directory.Delete(target, true); Directory.Move(tmp, target); foreach (var old in Directory.GetDirectories(appsRoot)) { if (!string.Equals(old, target, StringComparison.OrdinalIgnoreCase)) try { Directory.Delete(old, true); } catch { } // may be in use by another window } return target; } // Window size/position/zoom are remembered in %LOCALAPPDATA%\ProjectDashboard\window.txt // ("x y w h maximized zoom"). First start: maximized. static readonly string WindowFile = Path.Combine(DataDir, "window.txt"); double savedZoom = 1.0; void RestoreWindow() { StartPosition = FormStartPosition.CenterScreen; Size = new Size(1500, 950); WindowState = FormWindowState.Maximized; try { var v = File.ReadAllText(WindowFile).Split(' '); var inv = System.Globalization.CultureInfo.InvariantCulture; var rect = new Rectangle(int.Parse(v[0]), int.Parse(v[1]), int.Parse(v[2]), int.Parse(v[3])); savedZoom = double.Parse(v[5], inv); // only restore a position that is still on a connected screen if (Screen.AllScreens.Any(s => s.WorkingArea.IntersectsWith(rect)) && rect.Width >= MinimumSize.Width) { StartPosition = FormStartPosition.Manual; Bounds = rect; } WindowState = v[4] == "1" ? FormWindowState.Maximized : FormWindowState.Normal; } catch { } } void SaveWindow() { try { var b = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds; var zoom = web.CoreWebView2 != null ? web.ZoomFactor : savedZoom; Directory.CreateDirectory(DataDir); File.WriteAllText(WindowFile, string.Join(' ', b.X, b.Y, b.Width, b.Height, WindowState == FormWindowState.Maximized ? "1" : "0", zoom.ToString(System.Globalization.CultureInfo.InvariantCulture))); } catch { } } static bool BackupRunning() { try { using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(1) }; var json = http.GetStringAsync(BaseUrl + "api/backup").GetAwaiter().GetResult(); return json.Contains("\"phase\":\"copying\"") || json.Contains("\"phase\":\"checking\""); } catch { return false; } } static async Task IsServerUp() { try { using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(1.5) }; var res = await http.GetAsync(BaseUrl + "api/scan"); return res.IsSuccessStatusCode; } catch { return false; } } string? FindNode() { foreach (var dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries)) { try { var p = Path.Combine(dir.Trim('"'), "node.exe"); if (File.Exists(p)) return p; } catch { } } var std = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "nodejs", "node.exe"); return File.Exists(std) ? std : null; } void StartServer(string node) { serverLog = new StreamWriter(Path.Combine(DataDir, "server.log"), append: false) { AutoFlush = true }; var psi = new ProcessStartInfo(node, "server.js") { WorkingDirectory = appDir, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, }; // npm/git/code started by the server must be found psi.Environment["PATH"] = Path.GetDirectoryName(node) + ";" + Environment.GetEnvironmentVariable("PATH"); // portable: settings, cache and logs live next to the window state, not in the unpacked app if (portable) psi.Environment["DASHBOARD_DATA"] = Path.Combine(DataDir, "data"); server = Process.Start(psi) ?? throw new Exception("Node konnte nicht gestartet werden."); server.OutputDataReceived += (_, e) => { if (e.Data != null) lock (serverLog) serverLog.WriteLine(e.Data); }; server.ErrorDataReceived += (_, e) => { if (e.Data != null) lock (serverLog) serverLog.WriteLine("ERR " + e.Data); }; server.BeginOutputReadLine(); server.BeginErrorReadLine(); } async Task RunHidden(string exe, string args, string extraPath) { var psi = new ProcessStartInfo(exe, args) { WorkingDirectory = appDir, UseShellExecute = false, CreateNoWindow = true }; psi.Environment["PATH"] = extraPath + ";" + Environment.GetEnvironmentVariable("PATH"); using var p = Process.Start(psi)!; await p.WaitForExitAsync(); if (p.ExitCode != 0) throw new Exception("npm install ist fehlgeschlagen."); } // Only node itself is stopped: programs it launched (Unity, consoles, ...) // were started detached and keep running. void StopServer() { if (server is { HasExited: false }) { // a running backup (robocopy, child of node) is stopped cleanly first try { using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(2) }; using var req = new HttpRequestMessage(HttpMethod.Post, BaseUrl + "api/backup/cancel"); req.Headers.Add("Origin", BaseUrl.TrimEnd('/')); http.Send(req); } catch { } } try { if (server is { HasExited: false }) server.Kill(entireProcessTree: false); } catch { } serverLog?.Dispose(); } static void OpenExternal(string uri) { try { Process.Start(new ProcessStartInfo(uri) { UseShellExecute = true }); } catch { } } }