diff --git a/README.md b/README.md index 3410bd2..52bbe6f 100644 --- a/README.md +++ b/README.md @@ -308,16 +308,11 @@ entfernt - auch dann, wenn der Nextcloud-Ordner komplett leer ist. ### Kleiner Windows-Uploader -`release/TAP-Uploader.exe` per Doppelklick starten. `.tap`-Dateien ins Fenster -ziehen oder ueber **Dateien auswaehlen** hinzufuegen und dann **Nach Nextcloud -hochladen** klicken. Die App liest Host, Benutzer, Ordner und Passwort zur -Laufzeit aus der lokalen, ignorierten `include/config.h` eine Ebene ueber dem -`release`-Ordner; sie enthaelt keine fest eingebauten Zugangsdaten und -benoetigt keine zusaetzlichen Pakete. Die EXE ist eine kleine native -Windows-Anwendung; zum Neu-Bauen `uploader/Build.ps1` ausfuehren. Es -werden nur nichtleere `.tap`-Dateien mit einfachen ASCII-Dateinamen akzeptiert, -damit die Namen auf dem ESP unveraendert ankommen. Bereits vorhandene Dateien -mit demselben Namen in Nextcloud werden ersetzt. +Der Windows-Uploader wird separat im Repository +[Nextcloud-Uploader](https://git.dominicspringer.de/Emporex/Nextcloud-Uploader) +gepflegt. Dort liegen die gebaute `release/TAP-Uploader.exe`, der Quellcode und +die Anleitung zur lokalen Nextcloud-Konfiguration. Zugangsdaten bleiben lokal +und werden nicht im Git-Repository gespeichert. Erst nach der Erfolgsmeldung den ESP per Reset neu starten, waehrend der Plasmaschneider nicht auf den Stick zugreift. Der ESP synchronisiert beim Boot diff --git a/uploader/Build.ps1 b/uploader/Build.ps1 deleted file mode 100644 index 5b78b7f..0000000 --- a/uploader/Build.ps1 +++ /dev/null @@ -1,13 +0,0 @@ -$ErrorActionPreference = 'Stop' -$projectRoot = Split-Path $PSScriptRoot -Parent -$releaseDir = Join-Path $projectRoot 'release' -$compiler = Join-Path $env:WINDIR 'Microsoft.NET\Framework64\v4.0.30319\csc.exe' -if (-not (Test-Path -LiteralPath $compiler)) { - throw 'Der C#-Compiler fuer .NET Framework 4.x wurde nicht gefunden.' -} -New-Item -ItemType Directory -Path $releaseDir -Force | Out-Null -$source = Join-Path $PSScriptRoot 'TapUploader.cs' -$output = Join-Path $releaseDir 'TAP-Uploader.exe' -& $compiler /nologo /target:winexe /optimize+ /out:$output /reference:System.Windows.Forms.dll /reference:System.Drawing.dll $source -if ($LASTEXITCODE -ne 0) { throw 'Der EXE-Build ist fehlgeschlagen.' } -Write-Output "Erstellt: $output" diff --git a/uploader/TapUploader.cs b/uploader/TapUploader.cs deleted file mode 100644 index 48257ae..0000000 --- a/uploader/TapUploader.cs +++ /dev/null @@ -1,385 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.IO; -using System.Net; -using System.Text; -using System.Text.RegularExpressions; -using System.Windows.Forms; - -namespace PlasmaTapUploader -{ - internal sealed class CloudConfig - { - public string BaseUrl; - public string Authorization; - public string Folder; - - public static CloudConfig Load() - { - string appDir = AppDomain.CurrentDomain.BaseDirectory; - string configPath = Path.GetFullPath(Path.Combine(appDir, "..", "include", "config.h")); - if (!File.Exists(configPath)) - throw new InvalidOperationException("include/config.h fehlt neben dem release-Ordner. Die EXE bitte im Projektordner belassen."); - - string source = File.ReadAllText(configPath); - string host = ReadValue(source, "NEXTCLOUD_HOST"); - string user = ReadValue(source, "NEXTCLOUD_USER"); - string password = ReadValue(source, "NEXTCLOUD_APP_PASSWORD"); - string folder = ReadValue(source, "NEXTCLOUD_FOLDER"); - - if (!Regex.IsMatch(host, @"^[A-Za-z0-9.-]+(:[0-9]{1,5})?$") || - String.IsNullOrWhiteSpace(user) || String.IsNullOrWhiteSpace(password) || - password.StartsWith("CHANGE_ME", StringComparison.OrdinalIgnoreCase) || - !folder.StartsWith("/", StringComparison.Ordinal)) - throw new InvalidOperationException("Die Nextcloud-Konfiguration in include/config.h ist unvollstaendig oder ungueltig."); - - string[] parts = folder.Trim('/').Split('/'); - if (parts.Length == 0) throw new InvalidOperationException("NEXTCLOUD_FOLDER ist leer."); - for (int i = 0; i < parts.Length; i++) - { - if (parts[i].Length == 0 || parts[i] == "." || parts[i] == "..") - throw new InvalidOperationException("NEXTCLOUD_FOLDER enthaelt einen ungueltigen Pfadteil."); - parts[i] = Uri.EscapeDataString(parts[i]); - } - - return new CloudConfig { - BaseUrl = "https://" + host + "/remote.php/dav/files/" + - Uri.EscapeDataString(user) + "/" + String.Join("/", parts) + "/", - Authorization = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(user + ":" + password)), - Folder = folder - }; - } - - private static string ReadValue(string source, string name) - { - string pattern = @"^\s*(?:static\s+)?const\s+char\s*\*\s*" + Regex.Escape(name) + - @"\s*=\s*""((?:\\.|[^""\\])*)""\s*;"; - Match match = Regex.Match(source, pattern, RegexOptions.Multiline); - if (!match.Success) throw new InvalidOperationException("Konfigurationswert " + name + " fehlt in include/config.h."); - return match.Groups[1].Value.Replace("\\\"", "\"").Replace("\\\\", "\\"); - } - } - - internal static class WebDav - { - public static HttpWebRequest Request(CloudConfig config, string url, string method) - { - var request = (HttpWebRequest)WebRequest.Create(url); - request.Method = method; - request.AllowAutoRedirect = false; // Authentifizierung nie an einen Redirect senden. - request.Timeout = 30000; - request.ReadWriteTimeout = 30000; - request.KeepAlive = false; - request.Headers[HttpRequestHeader.Authorization] = config.Authorization; - return request; - } - - public static void CheckFolder(CloudConfig config) - { - var request = Request(config, config.BaseUrl, "PROPFIND"); - request.Headers["Depth"] = "0"; - request.ContentLength = 0; - using (var response = (HttpWebResponse)request.GetResponse()) - { - int code = (int)response.StatusCode; - if (code != 200 && code != 207) throw new InvalidOperationException("Nextcloud antwortet mit HTTP " + code + "."); - } - } - - public static void Upload(CloudConfig config, string path, Action progress) - { - FileInfo file = new FileInfo(path); - string url = config.BaseUrl + Uri.EscapeDataString(file.Name); - var request = Request(config, url, "PUT"); - request.ContentType = "application/octet-stream"; - request.ContentLength = file.Length; - using (var input = file.OpenRead()) - using (var output = request.GetRequestStream()) - { - byte[] buffer = new byte[65536]; - int count; - while ((count = input.Read(buffer, 0, buffer.Length)) > 0) - { - output.Write(buffer, 0, count); - progress(count); - } - } - using (var response = (HttpWebResponse)request.GetResponse()) - { - int code = (int)response.StatusCode; - if (code != 200 && code != 201 && code != 204) - throw new InvalidOperationException("Upload fehlgeschlagen: HTTP " + code + "."); - } - } - - public static void WriteTest(CloudConfig config) - { - CheckFolder(config); - string url = config.BaseUrl + ".tap-uploader-check-" + Guid.NewGuid().ToString("N") + ".tmp"; - byte[] data = Encoding.ASCII.GetBytes("Plasma TAP-Uploader Schreibtest"); - try - { - var put = Request(config, url, "PUT"); - put.ContentType = "application/octet-stream"; - put.ContentLength = data.Length; - using (var stream = put.GetRequestStream()) stream.Write(data, 0, data.Length); - using (var response = (HttpWebResponse)put.GetResponse()) - { - int code = (int)response.StatusCode; - if (code != 200 && code != 201 && code != 204) - throw new InvalidOperationException("Test-Upload fehlgeschlagen: HTTP " + code + "."); - } - } - finally - { - // Ausschliesslich die gerade angelegte, eindeutig benannte Testdatei entfernen. - var delete = Request(config, url, "DELETE"); - try { using (var response = (HttpWebResponse)delete.GetResponse()) { } } - catch (WebException error) - { - var response = error.Response as HttpWebResponse; - if (response == null || response.StatusCode != HttpStatusCode.NotFound) throw; - response.Close(); - } - } - } - - public static string FriendlyError(Exception error) - { - while (error.InnerException != null) error = error.InnerException; - var webError = error as WebException; - if (webError != null && webError.Response != null) - { - int code = (int)((HttpWebResponse)webError.Response).StatusCode; - webError.Response.Close(); - if (code == 401) return "Zugangsdaten wurden von Nextcloud abgelehnt (HTTP 401)."; - if (code == 403) return "Keine Schreibberechtigung im Nextcloud-Ordner (HTTP 403)."; - if (code == 404) return "Nextcloud-Ordner nicht gefunden (HTTP 404)."; - if (code == 507) return "Nextcloud hat keinen freien Speicher (HTTP 507)."; - return "Nextcloud meldet HTTP " + code + "."; - } - return error.Message; - } - } - - internal sealed class MainForm : Form - { - private readonly CloudConfig config; - private readonly List files = new List(); - private readonly ListBox fileList = new ListBox(); - private readonly Button chooseButton = new Button(); - private readonly Button clearButton = new Button(); - private readonly Button uploadButton = new Button(); - private readonly ProgressBar progressBar = new ProgressBar(); - private readonly Label statusLabel = new Label(); - private readonly BackgroundWorker worker = new BackgroundWorker(); - - public MainForm(CloudConfig config) - { - this.config = config; - Text = "Plasma TAP-Uploader"; - Font = new Font("Segoe UI", 9); - ClientSize = new Size(650, 430); - StartPosition = FormStartPosition.CenterScreen; - FormBorderStyle = FormBorderStyle.FixedDialog; - MaximizeBox = false; - AllowDrop = true; - - var heading = new Label { Text = "TAP-Dateien hier hineinziehen", Font = new Font("Segoe UI", 15, FontStyle.Bold), - AutoSize = true, Location = new Point(20, 17) }; - var hint = new Label { Text = "Ziel: Nextcloud " + config.Folder + " | Gleiche Dateinamen werden ersetzt.", - AutoSize = true, Location = new Point(22, 53) }; - fileList.Location = new Point(22, 82); - fileList.Size = new Size(605, 228); - fileList.AllowDrop = true; - chooseButton.Text = "Dateien auswaehlen..."; - chooseButton.Location = new Point(22, 322); - chooseButton.Size = new Size(150, 30); - clearButton.Text = "Liste leeren"; - clearButton.Location = new Point(180, 322); - clearButton.Size = new Size(105, 30); - uploadButton.Text = "Nach Nextcloud hochladen"; - uploadButton.Location = new Point(420, 322); - uploadButton.Size = new Size(207, 30); - progressBar.Location = new Point(22, 365); - progressBar.Size = new Size(605, 15); - statusLabel.Text = "Bereit. Nach erfolgreichem Upload den ESP per Reset neu starten."; - statusLabel.Location = new Point(22, 390); - statusLabel.Size = new Size(605, 28); - statusLabel.AutoEllipsis = true; - Controls.AddRange(new Control[] { heading, hint, fileList, chooseButton, clearButton, uploadButton, progressBar, statusLabel }); - - DragEnter += OnDragEnter; - DragDrop += OnDragDrop; - fileList.DragEnter += OnDragEnter; - fileList.DragDrop += OnDragDrop; - chooseButton.Click += delegate { ChooseFiles(); }; - clearButton.Click += delegate { files.Clear(); fileList.Items.Clear(); progressBar.Value = 0; statusLabel.Text = "Liste geleert."; }; - uploadButton.Click += delegate { StartUpload(); }; - FormClosing += delegate(object sender, FormClosingEventArgs e) { if (worker.IsBusy) e.Cancel = true; }; - - worker.WorkerReportsProgress = true; - worker.DoWork += UploadWork; - worker.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e) { - progressBar.Value = Math.Max(0, Math.Min(100, e.ProgressPercentage)); - statusLabel.Text = (string)e.UserState; - }; - worker.RunWorkerCompleted += UploadCompleted; - } - - private void OnDragEnter(object sender, DragEventArgs e) - { - e.Effect = !worker.IsBusy && e.Data.GetDataPresent(DataFormats.FileDrop) - ? DragDropEffects.Copy : DragDropEffects.None; - } - - private void OnDragDrop(object sender, DragEventArgs e) - { - if (!worker.IsBusy) AddFiles((string[])e.Data.GetData(DataFormats.FileDrop)); - } - - private void ChooseFiles() - { - using (var dialog = new OpenFileDialog { Title = "TAP-Dateien waehlen", Filter = "TAP-Dateien (*.tap)|*.tap", Multiselect = true }) - { - if (dialog.ShowDialog(this) == DialogResult.OK) AddFiles(dialog.FileNames); - } - } - - private void AddFiles(string[] paths) - { - if (paths == null) return; - int skipped = 0; - foreach (string path in paths) - { - try - { - var file = new FileInfo(path); - if (!file.Exists || file.Length == 0 || - !Regex.IsMatch(file.Name, @"^[A-Za-z0-9_.-]+\.tap$", RegexOptions.IgnoreCase)) - { skipped++; continue; } - bool duplicate = false; - foreach (string existing in files) - if (String.Equals(Path.GetFileName(existing), file.Name, StringComparison.OrdinalIgnoreCase)) duplicate = true; - if (duplicate) { skipped++; continue; } - files.Add(file.FullName); - fileList.Items.Add(file.Name + " (" + file.Length + " Bytes)"); - } - catch (Exception) { skipped++; } - } - statusLabel.Text = skipped > 0 - ? skipped + " Datei(en) uebersprungen: nur nichtleere .tap-Dateien mit einfachen Namen; keine doppelten Namen." - : files.Count + " Datei(en) bereit."; - } - - private void StartUpload() - { - if (worker.IsBusy || files.Count == 0) return; - chooseButton.Enabled = clearButton.Enabled = uploadButton.Enabled = false; - progressBar.Value = 0; - worker.RunWorkerAsync(new List(files)); - } - - private void UploadWork(object sender, DoWorkEventArgs e) - { - var paths = (List)e.Argument; - long sent = 0; - int completed = 0; - try - { - long total = 0; - foreach (string path in paths) - { - var file = new FileInfo(path); - if (!file.Exists || file.Length == 0) - throw new InvalidOperationException("Eine ausgewaehlte Datei fehlt oder ist leer."); - total += file.Length; - } - WebDav.CheckFolder(config); - foreach (string path in paths) - { - string name = Path.GetFileName(path); - worker.ReportProgress((int)(100.0 * sent / total), "Lade hoch: " + name + " (" + (completed + 1) + "/" + paths.Count + ")"); - WebDav.Upload(config, path, delegate(int count) { - sent += count; - worker.ReportProgress((int)Math.Min(100, 100.0 * sent / total), - "Lade hoch: " + name + " (" + (completed + 1) + "/" + paths.Count + ")"); - }); - completed++; - } - e.Result = completed; - } - catch (Exception error) - { - e.Result = new UploadFailure { Completed = completed, Error = error }; - } - } - - private void UploadCompleted(object sender, RunWorkerCompletedEventArgs e) - { - chooseButton.Enabled = clearButton.Enabled = uploadButton.Enabled = true; - var failure = e.Error == null ? e.Result as UploadFailure : null; - if (e.Error != null || failure != null) - { - Exception error = e.Error ?? failure.Error; - int completed = failure == null ? 0 : failure.Completed; - statusLabel.Text = completed + " von " + files.Count + " Datei(en) hochgeladen. Fehler: " + WebDav.FriendlyError(error); - MessageBox.Show(this, statusLabel.Text, "Upload fehlgeschlagen", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - progressBar.Value = 100; - statusLabel.Text = e.Result + " Datei(en) in Nextcloud gespeichert. Jetzt den ESP per Reset neu starten."; - MessageBox.Show(this, statusLabel.Text, "Upload abgeschlossen", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - - private sealed class UploadFailure - { - public int Completed; - public Exception Error; - } - } - - internal static class Program - { - [STAThread] - private static int Main(string[] args) - { - try - { - // .NET Framework kann sonst je nach Windows-Konfiguration - // noch TLS 1.0 als Standard verwenden. - ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; - CloudConfig config = CloudConfig.Load(); - if (args.Length > 0 && args[0] == "--check") - { - WebDav.CheckFolder(config); - Console.WriteLine("Nextcloud-Ordner erreichbar: " + config.Folder); - return 0; - } - if (args.Length > 0 && args[0] == "--test-upload") - { - WebDav.WriteTest(config); - Console.WriteLine("Test-Upload erfolgreich und Testdatei entfernt."); - return 0; - } - if (args.Length > 0 && args[0] == "--smoke") - { - using (var form = new MainForm(config)) Console.WriteLine("Oberflaeche bereit: " + form.Controls.Count + " Steuerelemente."); - return 0; - } - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new MainForm(config)); - return 0; - } - catch (Exception error) - { - if (args.Length > 0) Console.Error.WriteLine(WebDav.FriendlyError(error)); - else MessageBox.Show(WebDav.FriendlyError(error), "TAP-Uploader", MessageBoxButtons.OK, MessageBoxIcon.Error); - return 1; - } - } - } -}