Harden SD storage detection and add TAP uploader
This commit is contained in:
1 parent
0ec027e31d
commit
6561da3903
5 files changed
+443
-7
No files matched your search
@@ -2,3 +2,4 @@
|
||||
.vscode/
|
||||
include/config.h
|
||||
*.log
|
||||
release/
|
||||
@@ -298,6 +298,24 @@ ueberschrieben (neuere Version gewinnt), und lokale `.tap`-Dateien, die
|
||||
nicht mehr in Nextcloud liegen, werden beim naechsten Boot-Sync automatisch
|
||||
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.
|
||||
|
||||
Erst nach der Erfolgsmeldung den ESP per Reset neu starten, waehrend der
|
||||
Plasmaschneider nicht auf den Stick zugreift. Der ESP synchronisiert beim Boot
|
||||
den Nextcloud-Ordner auf die SD-Karte. Der Uploader schreibt **nicht direkt**
|
||||
auf das USB-Laufwerk und startet den ESP nicht automatisch neu.
|
||||
|
||||
Das eingebettete Root-Zertifikat (`LETSENCRYPT_ROOT_CA`, ISRG Root X1) ist
|
||||
fuer alle per Let's Encrypt ausgestellten Zertifikate gueltig (bis 2035) und
|
||||
muss normalerweise nicht angepasst werden.
|
||||
|
||||
+26
-7
@@ -129,6 +129,11 @@ static const uint32_t USB_BEGIN_RETRY_MS = 5000;
|
||||
// fehlgeschlagener Zustandswechsel (z.B. sdcard_mount() schlaegt fehl) beim
|
||||
// naechsten Versuch nicht durch den g_state-Schnellausstieg uebersprungen wird.
|
||||
static bool g_fsMounted = false;
|
||||
// Erst wahr, wenn die Karte nicht nur einen Laufwerks-Slot erhalten hat,
|
||||
// sondern auch erfolgreich gemountet wurde und eine plausible MSC-Geometrie
|
||||
// liefert. sdcard_init() kann bereits einen pdrv zurueckgeben, obwohl die
|
||||
// anschliessende Karteninitialisierung in sdcard_mount() scheitert.
|
||||
static bool g_storageReady = false;
|
||||
|
||||
static uint8_t g_pdrv = 0xFF;
|
||||
static uint32_t g_sectorSize = 512;
|
||||
@@ -162,7 +167,7 @@ static void invalidateCache() {
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static int32_t onMscRead(uint32_t lba, uint32_t offset, void *buffer, uint32_t bufsize) {
|
||||
if (g_state != BridgeState::USB_EXPOSED || g_pdrv == 0xFF) return -1;
|
||||
if (g_state != BridgeState::USB_EXPOSED || !g_storageReady || g_pdrv == 0xFF) return -1;
|
||||
if (offset >= 512) return -1;
|
||||
uint64_t firstByte = (uint64_t)lba * 512 + offset;
|
||||
uint64_t diskBytes = (uint64_t)g_sectorCount * 512;
|
||||
@@ -197,7 +202,7 @@ static int32_t onMscRead(uint32_t lba, uint32_t offset, void *buffer, uint32_t b
|
||||
}
|
||||
|
||||
static int32_t onMscWrite(uint32_t lba, uint32_t offset, uint8_t *buffer, uint32_t bufsize) {
|
||||
if (g_state != BridgeState::USB_EXPOSED || g_pdrv == 0xFF) return -1;
|
||||
if (g_state != BridgeState::USB_EXPOSED || !g_storageReady || g_pdrv == 0xFF) return -1;
|
||||
if (offset >= 512) return -1;
|
||||
uint64_t firstByte = (uint64_t)lba * 512 + offset;
|
||||
uint64_t diskBytes = (uint64_t)g_sectorCount * 512;
|
||||
@@ -253,6 +258,11 @@ static bool enterNetworkSyncState() {
|
||||
g_mediaReannounceRequested = false;
|
||||
g_mediaReannounceInProgress = false;
|
||||
MSC.mediaPresent(false);
|
||||
if (!g_storageReady || g_pdrv == 0xFF) {
|
||||
Serial.println("FEHLER: Kein betriebsbereiter SD-Speicher vorhanden");
|
||||
g_fsMounted = false;
|
||||
return false;
|
||||
}
|
||||
if (!sdcard_mount(g_pdrv, BASE_PATH, 5, false)) {
|
||||
Serial.println("FEHLER: SD-Karte konnte nicht (wieder) gemountet werden");
|
||||
g_fsMounted = false;
|
||||
@@ -297,8 +307,8 @@ static bool enterUsbExposedState() {
|
||||
// Nur als vorhanden melden, wenn ueberhaupt eine Karte erkannt wurde -
|
||||
// sonst wuerde der Cutter einen Stick sehen, der auf jeden Zugriff mit
|
||||
// Fehler antwortet.
|
||||
MSC.mediaPresent(g_pdrv != 0xFF);
|
||||
return true;
|
||||
MSC.mediaPresent(g_storageReady);
|
||||
return g_storageReady;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
@@ -383,7 +393,7 @@ static void processUsbRecovery() {
|
||||
uint32_t now = millis();
|
||||
if (g_mediaReannounceInProgress) {
|
||||
if ((int32_t)(now - g_mediaRestoreAtMs) >= 0) {
|
||||
MSC.mediaPresent(g_state == BridgeState::USB_EXPOSED && g_pdrv != 0xFF);
|
||||
MSC.mediaPresent(g_state == BridgeState::USB_EXPOSED && g_storageReady);
|
||||
g_mediaReannounceInProgress = false;
|
||||
Serial.println("USB-Medium erneut angemeldet");
|
||||
}
|
||||
@@ -674,6 +684,7 @@ static void handleStatus() {
|
||||
j += "\"usb_event_count\":" + String(g_usbEventCount) + ",";
|
||||
j += "\"usb_last_event_id\":" + String(g_lastUsbEventId) + ",";
|
||||
j += "\"usb_reannounce_count\":" + String(g_mediaReannounceCount) + ",";
|
||||
j += "\"storage_ready\":" + String(g_storageReady ? "true" : "false") + ",";
|
||||
j += "\"sector_size\":" + String(g_sectorSize) + ",";
|
||||
j += "\"sector_count\":" + String(g_sectorCount);
|
||||
j += "}";
|
||||
@@ -887,10 +898,14 @@ void setup() {
|
||||
} else {
|
||||
g_sectorSize = sdcard_sector_size(g_pdrv);
|
||||
g_sectorCount = sdcard_num_sectors(g_pdrv);
|
||||
if (g_sectorSize != sizeof(g_cacheBuf) || g_sectorCount == 0) {
|
||||
Serial.printf("FATAL: Ungueltige SD-Geometrie: %u Sektoren mit %u Byte\n",
|
||||
g_sectorCount, g_sectorSize);
|
||||
g_fsMounted = false;
|
||||
} else {
|
||||
g_storageReady = true;
|
||||
g_state = BridgeState::NETWORK_SYNC;
|
||||
g_fsMounted = true;
|
||||
if (g_sectorSize != sizeof(g_cacheBuf)) {
|
||||
Serial.printf("WARNUNG: unerwartete Sektorgroesse %u (Cache ist auf 512 ausgelegt)\n", g_sectorSize);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -923,7 +938,11 @@ void setup() {
|
||||
// Frische Dateien von Nextcloud holen, bevor der Stick fuer den
|
||||
// Plasmaschneider sichtbar wird (typischerweise bei jedem Einschalten,
|
||||
// da der ESP32 ueber den USB/OTG-Port vom Cutter mitversorgt wird).
|
||||
if (g_storageReady) {
|
||||
syncFromNextcloud();
|
||||
} else {
|
||||
Serial.println("Nextcloud-Sync uebersprungen: SD-Speicher nicht bereit");
|
||||
}
|
||||
enterUsbExposedState();
|
||||
startUsbMassStorage();
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
$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"
|
||||
@@ -0,0 +1,385 @@
|
||||
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<int> 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<string> files = new List<string>();
|
||||
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<string>(files));
|
||||
}
|
||||
|
||||
private void UploadWork(object sender, DoWorkEventArgs e)
|
||||
{
|
||||
var paths = (List<string>)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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user