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; using System.Xml; 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 sealed class RemoteProgram { public string Name; public long Size; public DateTime? Modified; } 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 List ListPrograms(CloudConfig config) { var request = Request(config, config.BaseUrl, "PROPFIND"); request.Headers["Depth"] = "1"; request.ContentType = "application/xml; charset=utf-8"; byte[] body = Encoding.UTF8.GetBytes(""); request.ContentLength = body.Length; using (var stream = request.GetRequestStream()) stream.Write(body, 0, body.Length); using (var response = (HttpWebResponse)request.GetResponse()) { if ((int)response.StatusCode != 207) throw new InvalidOperationException("Nextcloud antwortet auf die Ordnerliste mit HTTP " + (int)response.StatusCode + "."); var document = new XmlDocument { XmlResolver = null }; using (var reader = XmlReader.Create(response.GetResponseStream(), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 20000000 })) document.Load(reader); var ns = new XmlNamespaceManager(document.NameTable); ns.AddNamespace("d", "DAV:"); var result = new List(); Uri baseUri = new Uri(config.BaseUrl); string folderPath = Uri.UnescapeDataString(baseUri.AbsolutePath); foreach (XmlNode node in document.SelectNodes("/d:multistatus/d:response", ns)) { XmlNode href = node.SelectSingleNode("d:href", ns); if (href == null) continue; Uri itemUri; if (!Uri.TryCreate(baseUri, href.InnerText, out itemUri) || !String.Equals(itemUri.Host, baseUri.Host, StringComparison.OrdinalIgnoreCase) || itemUri.Port != baseUri.Port) continue; string path = Uri.UnescapeDataString(itemUri.AbsolutePath); if (!path.StartsWith(folderPath, StringComparison.Ordinal)) continue; string name = path.Substring(folderPath.Length); if (name.Length == 0 || name.IndexOf('/') >= 0 || !name.EndsWith(".tap", StringComparison.OrdinalIgnoreCase)) continue; XmlNode prop = node.SelectSingleNode("d:propstat[d:status[contains(., ' 200 ')]]/d:prop", ns); if (prop == null || prop.SelectSingleNode("d:resourcetype/d:collection", ns) != null) continue; long size = 0; DateTime modified; XmlNode sizeNode = prop.SelectSingleNode("d:getcontentlength", ns); XmlNode dateNode = prop.SelectSingleNode("d:getlastmodified", ns); if (sizeNode != null) long.TryParse(sizeNode.InnerText, out size); DateTime? lastModified = dateNode != null && DateTime.TryParse(dateNode.InnerText, out modified) ? (DateTime?)modified.ToLocalTime() : null; result.Add(new RemoteProgram { Name = name, Size = size, Modified = lastModified }); } result.Sort(delegate(RemoteProgram a, RemoteProgram b) { return StringComparer.CurrentCultureIgnoreCase.Compare(a.Name, b.Name); }); return result; } } 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 Label hintLabel = new Label(); 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(); private readonly Label remoteHeading = new Label(); private readonly ListView remoteList = new ListView(); private readonly Button refreshButton = new Button(); private readonly Label remoteStatus = new Label(); private readonly BackgroundWorker listWorker = new BackgroundWorker(); public MainForm(CloudConfig config) { this.config = config; Text = "Plasma TAP-Uploader"; Font = new Font("Segoe UI", 9); ClientSize = new Size(650, 650); StartPosition = FormStartPosition.CenterScreen; FormBorderStyle = FormBorderStyle.Sizable; MaximizeBox = true; 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) }; hintLabel.Text = "Ziel: Nextcloud " + config.Folder + " | Gleiche Dateinamen werden ersetzt."; hintLabel.Location = new Point(22, 53); hintLabel.Size = new Size(605, 22); hintLabel.AutoEllipsis = true; fileList.Location = new Point(22, 82); fileList.Size = new Size(605, 140); fileList.IntegralHeight = false; fileList.AllowDrop = true; chooseButton.Text = "Dateien auswaehlen..."; chooseButton.Location = new Point(22, 234); chooseButton.Size = new Size(150, 30); clearButton.Text = "Liste leeren"; clearButton.Location = new Point(180, 234); clearButton.Size = new Size(105, 30); uploadButton.Text = "Nach Nextcloud hochladen"; uploadButton.Location = new Point(420, 234); uploadButton.Size = new Size(207, 30); progressBar.Location = new Point(22, 277); progressBar.Size = new Size(605, 15); statusLabel.Text = "Bereit. Nach erfolgreichem Upload den ESP per Reset neu starten."; statusLabel.Location = new Point(22, 302); statusLabel.Size = new Size(605, 28); statusLabel.AutoEllipsis = true; remoteHeading.Text = "Programme in Nextcloud"; remoteHeading.Font = new Font("Segoe UI", 12, FontStyle.Bold); remoteHeading.AutoSize = true; remoteHeading.Location = new Point(22, 344); refreshButton.Text = "Aktualisieren"; refreshButton.Location = new Point(522, 342); refreshButton.Size = new Size(105, 29); remoteList.Location = new Point(22, 379); remoteList.Size = new Size(605, 224); remoteList.View = View.Details; remoteList.FullRowSelect = true; remoteList.GridLines = true; remoteList.Columns.Add("Programm", 355); remoteList.Columns.Add("Groesse", 95); remoteList.Columns.Add("Geaendert", 130); remoteStatus.Text = "Lade Programmliste..."; remoteStatus.Location = new Point(22, 612); remoteStatus.Size = new Size(605, 25); remoteStatus.AutoEllipsis = true; Controls.AddRange(new Control[] { heading, hintLabel, fileList, chooseButton, clearButton, uploadButton, progressBar, statusLabel, remoteHeading, refreshButton, remoteList, remoteStatus }); MinimumSize = Size; ClientSizeChanged += delegate { LayoutControls(); }; LayoutControls(); 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(); }; refreshButton.Click += delegate { RefreshPrograms(); }; Shown += delegate { RefreshPrograms(); }; FormClosing += delegate(object sender, FormClosingEventArgs e) { if (worker.IsBusy || listWorker.IsBusy) e.Cancel = true; }; listWorker.DoWork += delegate(object sender, DoWorkEventArgs e) { e.Result = WebDav.ListPrograms(config); }; listWorker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) { refreshButton.Enabled = true; if (e.Error != null) { remoteStatus.Text = "Programmliste konnte nicht geladen werden: " + WebDav.FriendlyError(e.Error); return; } var programs = (List)e.Result; remoteList.BeginUpdate(); try { remoteList.Items.Clear(); foreach (var program in programs) { var item = new ListViewItem(program.Name); item.SubItems.Add(program.Size.ToString("N0") + " B"); item.SubItems.Add(program.Modified.HasValue ? program.Modified.Value.ToString("dd.MM.yyyy HH:mm") : "-"); remoteList.Items.Add(item); } } finally { remoteList.EndUpdate(); } remoteStatus.Text = programs.Count + " .tap-Programm(e) im Nextcloud-Ordner."; }; 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 LayoutControls() { int contentWidth = ClientSize.Width - 45; int extraHeight = Math.Max(0, ClientSize.Height - 650); hintLabel.Width = contentWidth; fileList.SetBounds(22, 82, contentWidth, 140); chooseButton.Top = clearButton.Top = uploadButton.Top = 234; uploadButton.Left = ClientSize.Width - 23 - uploadButton.Width; progressBar.SetBounds(22, 277, contentWidth, 15); statusLabel.SetBounds(22, 302, contentWidth, 28); refreshButton.SetBounds(ClientSize.Width - 23 - refreshButton.Width, 342, 105, 29); remoteHeading.Top = 344; remoteList.SetBounds(22, 379, contentWidth, 224 + extraHeight); remoteList.Columns[0].Width = Math.Max(355, contentWidth - 250); remoteStatus.SetBounds(22, 612 + extraHeight, contentWidth, 25); } private void RefreshPrograms() { if (listWorker.IsBusy) return; refreshButton.Enabled = false; remoteStatus.Text = "Lade Programmliste..."; listWorker.RunWorkerAsync(); } 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); RefreshPrograms(); 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); RefreshPrograms(); } 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] == "--list") { Console.WriteLine("Programme im Nextcloud-Ordner: " + WebDav.ListPrograms(config).Count); 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; } } } }