[#60] Services: Encrypt zip files for backup and upload
Test / Run tests (push) Successful in 2m12s
Test / Run tests (push) Successful in 2m12s
This commit is contained in:
1 parent
f388ddbe41
commit
4bb13dbb06
10 files changed
+116
-73
No files matched your search
+2
-2
@@ -352,10 +352,10 @@ namespace Elwig {
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task ReplaceDatabase(string filename) {
|
||||
public static async Task ReplaceDatabase(string filename, IEnumerable<ReadOnlyMemory<char>>? keys = null) {
|
||||
try {
|
||||
await Task.Run(async () => {
|
||||
await Database.Import(filename);
|
||||
await Database.Import(filename, keys);
|
||||
});
|
||||
InteractionService.ShowInformation("Datenbank ersetzen", "Das Ersetzen war erfolgreich!\n\nBitte starten Sie Elwig neu!");
|
||||
ShutdownNow();
|
||||
|
||||
+17
-6
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace Elwig.Helpers {
|
||||
@@ -55,24 +56,32 @@ namespace Elwig.Helpers {
|
||||
public int BackupRetainDays = 8;
|
||||
public int BackupRetainWeeks = 6;
|
||||
public int BackupRetainMonths = 18;
|
||||
private string[] _backupKeys = [];
|
||||
public ReadOnlyMemory<char>[] BackupDecryptionKeys => [.. _backupKeys.Select(k => k.AsMemory())];
|
||||
public ReadOnlyMemory<char> BackupEncryptionKey => _backupKeys.Length == 0 ? null : _backupKeys[0].AsMemory();
|
||||
|
||||
public string? UpdateUrl = null;
|
||||
public bool UpdateAuto = false;
|
||||
|
||||
public string? SyncUrl = null;
|
||||
public string SyncUsername = "";
|
||||
public string SyncPassword = "";
|
||||
private string _syncPassword = "";
|
||||
public ReadOnlyMemory<char> SyncPassword => _syncPassword.AsMemory();
|
||||
public bool SyncMain = false;
|
||||
private string[] _syncKeys = [];
|
||||
public ReadOnlyMemory<char>[] SyncDecryptionKeys => [.. _syncKeys.Select(k => k.AsMemory())];
|
||||
public ReadOnlyMemory<char> SyncEncryptionKey => _syncKeys.Length == 0 ? null : _syncKeys[0].AsMemory();
|
||||
|
||||
public string? SmtpHost = null;
|
||||
public int? SmtpPort = null;
|
||||
public string? SmtpMode = null;
|
||||
public string? SmtpUsername = null;
|
||||
public string? SmtpPassword = null;
|
||||
private string? _smtpPassword = null;
|
||||
public ReadOnlyMemory<char> SmtpPassword => _smtpPassword.AsMemory();
|
||||
public string? SmtpFrom = null;
|
||||
public double SmtpWait = 0;
|
||||
public (string Host, int Port, string Mode, string Username, string Password, string From, double Wait)? Smtp =>
|
||||
SmtpHost == null || SmtpPort == null || SmtpMode == null || SmtpUsername == null || SmtpPassword == null || SmtpFrom == null ?
|
||||
public (string Host, int Port, string Mode, string Username, ReadOnlyMemory<char> Password, string From, double Wait)? Smtp =>
|
||||
SmtpHost == null || SmtpPort == null || SmtpMode == null || SmtpUsername == null || !SmtpPassword.IsEmpty || SmtpFrom == null ?
|
||||
null : (SmtpHost, (int)SmtpPort, SmtpMode, SmtpUsername, SmtpPassword, SmtpFrom, SmtpWait);
|
||||
|
||||
public IList<ScaleConfig> Scales;
|
||||
@@ -101,20 +110,22 @@ namespace Elwig.Helpers {
|
||||
BackupRetainDays = int.TryParse(config["backup:retain_days"], out var days) ? days : 8;
|
||||
BackupRetainWeeks = int.TryParse(config["backup:retain_weeks"], out var weeks) ? weeks : 6;
|
||||
BackupRetainMonths = int.TryParse(config["backup:retain_months"], out var months) ? months : 18;
|
||||
_backupKeys = config["backup:key"]?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
|
||||
|
||||
UpdateUrl = config["update:url"];
|
||||
UpdateAuto = TrueValues.Contains(config["update:auto"]?.ToLower());
|
||||
|
||||
SyncUrl = config["sync:url"];
|
||||
SyncUsername = config["sync:username"] ?? "";
|
||||
SyncPassword = config["sync:password"] ?? "";
|
||||
_syncPassword = config["sync:password"] ?? "";
|
||||
SyncMain = TrueValues.Contains(config["sync:main"]?.ToLower());
|
||||
_syncKeys = config["sync:key"]?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
|
||||
|
||||
SmtpHost = config["smtp:host"];
|
||||
SmtpPort = config["smtp:port"]?.All(char.IsAsciiDigit) == true && config["smtp:port"]?.Length > 0 ? int.Parse(config["smtp:port"]!) : null;
|
||||
SmtpMode = config["smtp:mode"];
|
||||
SmtpUsername = config["smtp:username"];
|
||||
SmtpPassword = config["smtp:password"];
|
||||
_smtpPassword = config["smtp:password"];
|
||||
SmtpFrom = config["smtp:from"];
|
||||
SmtpWait = double.TryParse(config["smtp:wait"], out var res) ? res : 0;
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace Elwig.Helpers.Export {
|
||||
return (applId, userVers != null ? $"{userVers >> 24}.{(userVers >> 16) & 0xFF}.{(userVers >> 8) & 0xFF}.{userVers & 0xFF}" : null, schemaVers, size);
|
||||
}
|
||||
|
||||
public static async Task ExportSqlite(string filename, bool zipFile) {
|
||||
public static async Task ExportSqlite(string filename, bool zipFile, ReadOnlyMemory<char> password = default) {
|
||||
var tmp = filename + ".tmp";
|
||||
try {
|
||||
File.Delete(tmp);
|
||||
@@ -46,7 +46,9 @@ namespace Elwig.Helpers.Export {
|
||||
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
|
||||
}
|
||||
|
||||
var db = zip.CreateEntryFromFile(App.Config.DatabaseFile, "database.sqlite3", CompressionLevel.SmallestSize);
|
||||
var db = password.IsEmpty ?
|
||||
zip.CreateEntryFromFile(App.Config.DatabaseFile, "database.sqlite3", CompressionLevel.SmallestSize) :
|
||||
zip.CreateEntryFromFile(App.Config.DatabaseFile, "database.sqlite3", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
||||
} else {
|
||||
File.Copy(App.Config.DatabaseFile, tmp);
|
||||
}
|
||||
@@ -56,7 +58,7 @@ namespace Elwig.Helpers.Export {
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task ExportSql(string filename, bool zipFile) {
|
||||
public static async Task ExportSql(string filename, bool zipFile, ReadOnlyMemory<char> password = default) {
|
||||
var tmp = filename + ".tmp";
|
||||
try {
|
||||
File.Delete(tmp);
|
||||
@@ -85,7 +87,9 @@ namespace Elwig.Helpers.Export {
|
||||
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
|
||||
}
|
||||
|
||||
var sql = zip.CreateEntry("database.sql", CompressionLevel.SmallestSize);
|
||||
var sql = password.IsEmpty ?
|
||||
zip.CreateEntry("database.sql", CompressionLevel.SmallestSize) :
|
||||
zip.CreateEntry("database.sql", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
||||
using (var writer = new StreamWriter(sql.Open(), Utils.UTF8)) {
|
||||
await ExportSql(writer);
|
||||
}
|
||||
@@ -178,27 +182,27 @@ namespace Elwig.Helpers.Export {
|
||||
await writer.WriteLineAsync("VACUUM;");
|
||||
}
|
||||
|
||||
public static async Task Import(string filename) {
|
||||
public static async Task Import(string filename, IEnumerable<ReadOnlyMemory<char>>? passwords = null) {
|
||||
if (filename.EndsWith(".sql")) {
|
||||
await ImportSql(filename, false);
|
||||
} else if (filename.EndsWith(".sql.zip")) {
|
||||
await ImportSql(filename, true);
|
||||
await ImportSql(filename, true, passwords);
|
||||
} else if (filename.EndsWith(".sqlite3")) {
|
||||
await ImportSqlite(filename, false);
|
||||
} else if (filename.EndsWith(".sqlite3.zip")) {
|
||||
await ImportSqlite(filename, true);
|
||||
await ImportSqlite(filename, true, passwords);
|
||||
} else {
|
||||
throw new ArgumentException($"Unknown file extension for importing: '{filename}'");
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task ImportSql(string filename, bool zipFile = false) {
|
||||
public static async Task ImportSql(string filename, bool zipFile = false, IEnumerable<ReadOnlyMemory<char>>? passwords = null) {
|
||||
if (zipFile) {
|
||||
using var zip = ZipFile.Open(filename, ZipArchiveMode.Read);
|
||||
await zip.CheckIntegrity();
|
||||
var password = await zip.CheckIntegrity(passwords ?? []);
|
||||
foreach (var entry in zip.Entries) {
|
||||
if (entry.Name.EndsWith(".sql")) {
|
||||
using var stream = entry.Open();
|
||||
using var stream = entry.Open(password.Span);
|
||||
using var reader = new StreamReader(stream, Utils.UTF8);
|
||||
await ImportSql(reader);
|
||||
return;
|
||||
@@ -212,15 +216,15 @@ namespace Elwig.Helpers.Export {
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task ImportSqlite(string filename, bool zipFile = false, bool keepSource = true) {
|
||||
public static async Task ImportSqlite(string filename, bool zipFile = false, IEnumerable<ReadOnlyMemory<char>>? passwords = null, bool keepSource = true) {
|
||||
if (zipFile) {
|
||||
var newName = Path.ChangeExtension(App.Config.DatabaseFile, ".new.sqlite3");
|
||||
try {
|
||||
using var zip = ZipFile.Open(filename, ZipArchiveMode.Read);
|
||||
await zip.CheckIntegrity();
|
||||
var password = await zip.CheckIntegrity(passwords ?? []);
|
||||
foreach (var entry in zip.Entries) {
|
||||
if (entry.Name.EndsWith(".sqlite3")) {
|
||||
entry.ExtractToFile(newName);
|
||||
entry.ExtractToFile(newName, new ZipExtractionOptions { Password = password });
|
||||
await ImportSqlite(newName, keepSource: false);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ namespace Elwig.Helpers.Export {
|
||||
|
||||
public static Task Import(string filename, ImportMode mode) => Import([filename], mode);
|
||||
|
||||
public static async Task Import(IEnumerable<string> filenames, ImportMode mode) {
|
||||
public static async Task Import(IEnumerable<string> filenames, ImportMode mode, IEnumerable<ReadOnlyMemory<char>>? passwords = null) {
|
||||
try {
|
||||
Dictionary<string, Branch> branches;
|
||||
Dictionary<int, AT_Kg> kgs;
|
||||
@@ -89,9 +89,8 @@ namespace Elwig.Helpers.Export {
|
||||
})));
|
||||
var r = data[^1];
|
||||
|
||||
// TODO read encrypted files
|
||||
using var zip = ZipFile.Open(filename, ZipArchiveMode.Read);
|
||||
await zip.CheckIntegrity();
|
||||
var password = await zip.CheckIntegrity(passwords ?? []);
|
||||
|
||||
string[] acceptableVersions = ["1", "2"];
|
||||
var version = zip.GetEntry("version");
|
||||
@@ -117,7 +116,7 @@ namespace Elwig.Helpers.Export {
|
||||
|
||||
var wbKgsJson = zip.GetEntry("wb_kgs.json");
|
||||
if (wbKgsJson != null) {
|
||||
using var reader = new StreamReader(wbKgsJson.Open(), Utils.UTF8);
|
||||
using var reader = new StreamReader(wbKgsJson.Open(password.Span), Utils.UTF8);
|
||||
string? line;
|
||||
while ((line = await reader.ReadLineAsync()) != null) {
|
||||
var obj = JsonNode.Parse(line)!.AsObject();
|
||||
@@ -133,7 +132,7 @@ namespace Elwig.Helpers.Export {
|
||||
|
||||
var membersJson = zip.GetEntry("members.json");
|
||||
if (membersJson != null) {
|
||||
using var reader = new StreamReader(membersJson.Open(), Utils.UTF8);
|
||||
using var reader = new StreamReader(membersJson.Open(password.Span), Utils.UTF8);
|
||||
string? line;
|
||||
while ((line = await reader.ReadLineAsync()) != null) {
|
||||
var obj = JsonNode.Parse(line)!.AsObject();
|
||||
@@ -149,7 +148,7 @@ namespace Elwig.Helpers.Export {
|
||||
|
||||
var historyJson = zip.GetEntry("member_history.json");
|
||||
if (historyJson != null) {
|
||||
using var reader = new StreamReader(historyJson.Open(), Utils.UTF8);
|
||||
using var reader = new StreamReader(historyJson.Open(password.Span), Utils.UTF8);
|
||||
string? line;
|
||||
while ((line = await reader.ReadLineAsync()) != null) {
|
||||
var obj = JsonNode.Parse(line)!.AsObject();
|
||||
@@ -161,7 +160,7 @@ namespace Elwig.Helpers.Export {
|
||||
// legacy area commitments
|
||||
var areaCmtsJson = zip.GetEntry("area_commitments.json");
|
||||
if (areaCmtsJson != null) {
|
||||
using var reader = new StreamReader(areaCmtsJson.Open(), Utils.UTF8);
|
||||
using var reader = new StreamReader(areaCmtsJson.Open(password.Span), Utils.UTF8);
|
||||
string? line;
|
||||
while ((line = await reader.ReadLineAsync()) != null) {
|
||||
var obj = JsonNode.Parse(line)!.AsObject();
|
||||
@@ -180,7 +179,7 @@ namespace Elwig.Helpers.Export {
|
||||
|
||||
var contractsJson = zip.GetEntry("area_commitment_contracts.json");
|
||||
if (contractsJson != null) {
|
||||
using var reader = new StreamReader(contractsJson.Open(), Utils.UTF8);
|
||||
using var reader = new StreamReader(contractsJson.Open(password.Span), Utils.UTF8);
|
||||
string? line;
|
||||
while ((line = await reader.ReadLineAsync()) != null) {
|
||||
var obj = JsonNode.Parse(line)!.AsObject();
|
||||
@@ -201,7 +200,7 @@ namespace Elwig.Helpers.Export {
|
||||
|
||||
var deliveriesJson = zip.GetEntry("deliveries.json");
|
||||
if (deliveriesJson != null) {
|
||||
using var reader = new StreamReader(deliveriesJson.Open(), Utils.UTF8);
|
||||
using var reader = new StreamReader(deliveriesJson.Open(password.Span), Utils.UTF8);
|
||||
string? line;
|
||||
while ((line = await reader.ReadLineAsync()) != null) {
|
||||
var obj = JsonNode.Parse(line)!.AsObject();
|
||||
@@ -473,28 +472,28 @@ namespace Elwig.Helpers.Export {
|
||||
$"{branch} (Gerät {device}) {(duplicate ? "überschrieben" : "importiert")} werden?", true);
|
||||
}
|
||||
|
||||
public static Task Export(string filename, IEnumerable<Member> members, IEnumerable<MemberHistory> history, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters) {
|
||||
public static Task Export(string filename, IEnumerable<Member> members, IEnumerable<MemberHistory> history, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters, ReadOnlyMemory<char> password = default) {
|
||||
return new ElwigExport {
|
||||
Members = (members, filters),
|
||||
History = (history, ["von exportierten Mitgliedern"]),
|
||||
WbKgs = (wbKgs, ["von exportierten Mitgliedern"]),
|
||||
}.Export(filename);
|
||||
}.Export(filename, password);
|
||||
}
|
||||
|
||||
public static Task Export(string filename, IEnumerable<Member> members, IEnumerable<MemberHistory> history, IEnumerable<AreaCmtContract> areaCmts, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters) {
|
||||
public static Task Export(string filename, IEnumerable<Member> members, IEnumerable<MemberHistory> history, IEnumerable<AreaCmtContract> areaCmts, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters, ReadOnlyMemory<char> password = default) {
|
||||
return new ElwigExport {
|
||||
Members = (members, filters),
|
||||
History = (history, ["von exportierten Mitgliedern"]),
|
||||
AreaCmts = (areaCmts, ["von exportierten Mitgliedern"]),
|
||||
WbKgs = (wbKgs, ["von exportierten Mitgliedern und Flächenbindungen"]),
|
||||
}.Export(filename);
|
||||
}.Export(filename, password);
|
||||
}
|
||||
|
||||
public static Task Export(string filename, IEnumerable<Delivery> deliveries, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters) {
|
||||
public static Task Export(string filename, IEnumerable<Delivery> deliveries, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters, ReadOnlyMemory<char> password = default) {
|
||||
return new ElwigExport {
|
||||
Deliveries = (deliveries, filters),
|
||||
WbKgs = (wbKgs, ["von exportierten Lieferungen"]),
|
||||
}.Export(filename);
|
||||
}.Export(filename, password);
|
||||
}
|
||||
|
||||
public class ElwigExport {
|
||||
@@ -504,7 +503,7 @@ namespace Elwig.Helpers.Export {
|
||||
public (IEnumerable<AreaCmtContract> AreaCmts, IEnumerable<string> Filters)? AreaCmts { get; set; }
|
||||
public (IEnumerable<Delivery> Deliveries, IEnumerable<string> Filters)? Deliveries { get; set; }
|
||||
|
||||
public async Task Export(string filename) {
|
||||
public async Task Export(string filename, ReadOnlyMemory<char> password = default) {
|
||||
File.Delete(filename);
|
||||
using var zip = ZipFile.Open(filename, ZipArchiveMode.Create);
|
||||
|
||||
@@ -550,37 +549,46 @@ namespace Elwig.Helpers.Export {
|
||||
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
|
||||
}
|
||||
|
||||
// TODO encrypt files
|
||||
if (WbKgs != null) {
|
||||
var json = zip.CreateEntry("wb_kgs.json", CompressionLevel.SmallestSize);
|
||||
var json = password.IsEmpty ?
|
||||
zip.CreateEntry("wb_kgs.json", CompressionLevel.SmallestSize) :
|
||||
zip.CreateEntry("wb_kgs.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
||||
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
|
||||
foreach (var k in WbKgs.Value.WbKgs) {
|
||||
await writer.WriteLineAsync(k.ToJson().ToJsonString(Utils.JsonOpts));
|
||||
}
|
||||
}
|
||||
if (Members != null) {
|
||||
var json = zip.CreateEntry("members.json", CompressionLevel.SmallestSize);
|
||||
var json = password.IsEmpty ?
|
||||
zip.CreateEntry("members.json", CompressionLevel.SmallestSize) :
|
||||
zip.CreateEntry("members.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
||||
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
|
||||
foreach (var m in Members.Value.Members) {
|
||||
await writer.WriteLineAsync(m.ToJson().ToJsonString(Utils.JsonOpts));
|
||||
}
|
||||
}
|
||||
if (History != null) {
|
||||
var json = zip.CreateEntry("member_history.json", CompressionLevel.SmallestSize);
|
||||
var json = password.IsEmpty ?
|
||||
zip.CreateEntry("member_history.json", CompressionLevel.SmallestSize) :
|
||||
zip.CreateEntry("member_history.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
||||
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
|
||||
foreach (var h in History.Value.History) {
|
||||
await writer.WriteLineAsync(h.ToJson().ToJsonString(Utils.JsonOpts));
|
||||
}
|
||||
}
|
||||
if (AreaCmts != null) {
|
||||
var json = zip.CreateEntry("area_commitment_contracts.json", CompressionLevel.SmallestSize);
|
||||
var json = password.IsEmpty ?
|
||||
zip.CreateEntry("area_commitment_contracts.json", CompressionLevel.SmallestSize) :
|
||||
zip.CreateEntry("area_commitment_contracts.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
||||
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
|
||||
foreach (var c in AreaCmts.Value.AreaCmts) {
|
||||
await writer.WriteLineAsync(c.ToJson().ToJsonString(Utils.JsonOpts));
|
||||
}
|
||||
}
|
||||
if (Deliveries != null) {
|
||||
var json = zip.CreateEntry("deliveries.json", CompressionLevel.SmallestSize);
|
||||
var json = password.IsEmpty ?
|
||||
zip.CreateEntry("deliveries.json", CompressionLevel.SmallestSize) :
|
||||
zip.CreateEntry("deliveries.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
||||
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
|
||||
foreach (var d in Deliveries.Value.Deliveries) {
|
||||
await writer.WriteLineAsync(d.ToJson().ToJsonString(Utils.JsonOpts));
|
||||
|
||||
@@ -106,14 +106,30 @@ namespace Elwig.Helpers {
|
||||
progress.Report(100.0);
|
||||
}
|
||||
|
||||
public static async Task CheckIntegrity(this ZipArchive zip) {
|
||||
var crc = new Crc32();
|
||||
public static async Task<ReadOnlyMemory<char>> FindPassword(this ZipArchive zip, IEnumerable<ReadOnlyMemory<char>> passwords) {
|
||||
foreach (var pwd in passwords) {
|
||||
try {
|
||||
await zip.CheckIntegrity(pwd);
|
||||
return pwd;
|
||||
} catch { }
|
||||
}
|
||||
throw new InvalidDataException("No matching password found");
|
||||
}
|
||||
|
||||
public static async Task<ReadOnlyMemory<char>> CheckIntegrity(this ZipArchive zip, IEnumerable<ReadOnlyMemory<char>> passwords) {
|
||||
if (zip.Entries.Any(e => e.IsEncrypted)) {
|
||||
return await zip.FindPassword(passwords);
|
||||
} else {
|
||||
await zip.CheckIntegrity();
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task CheckIntegrity(this ZipArchive zip, ReadOnlyMemory<char> password = default) {
|
||||
byte[] buffer = new byte[8192];
|
||||
foreach (var entry in zip.Entries) {
|
||||
crc.Reset();
|
||||
using var stream = entry.Open();
|
||||
await crc.AppendAsync(stream);
|
||||
if (crc.GetCurrentHashAsUInt32() != entry.Crc32)
|
||||
throw new InvalidDataException($"CRC-32 mismatch in '{entry.FullName}'");
|
||||
using var stream = entry.Open(password.Span);
|
||||
while (stream.Read(buffer) > 0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -489,7 +489,7 @@ namespace Elwig.Helpers {
|
||||
.Replace("ß", "ss").Replace("ẞ", "SS");
|
||||
}
|
||||
|
||||
public static HttpClient GetHttpClient(string? username = null, string? password = null, string? accept = null) {
|
||||
public static HttpClient GetHttpClient(string? username = null, ReadOnlyMemory<char> password = default, string? accept = null) {
|
||||
var client = new HttpClient() {
|
||||
Timeout = TimeSpan.FromSeconds(5),
|
||||
};
|
||||
@@ -498,7 +498,7 @@ namespace Elwig.Helpers {
|
||||
client.DefaultRequestHeaders.Accept.Clear();
|
||||
if (accept != null)
|
||||
client.DefaultRequestHeaders.Accept.Add(new(accept));
|
||||
if (username != null || password != null)
|
||||
if (username != null || !password.IsEmpty)
|
||||
client.DefaultRequestHeaders.Authorization = new("Basic", Convert.ToBase64String(Utils.UTF8.GetBytes($"{username}:{password}")));
|
||||
return client;
|
||||
}
|
||||
@@ -512,7 +512,7 @@ namespace Elwig.Helpers {
|
||||
return ((string)data["version"]!, (string)data["url"]!, (long)data["size"]!);
|
||||
}
|
||||
|
||||
public static async Task UploadExportData(string zip, string url, string username, string password) {
|
||||
public static async Task UploadExportData(string zip, string url, string username, ReadOnlyMemory<char> password) {
|
||||
if (url.StartsWith("https://elwig.at/clients/"))
|
||||
url = "https://sync.elwig.at/" + url[25..];
|
||||
if (!url.EndsWith('/')) url += "/";
|
||||
@@ -523,7 +523,7 @@ namespace Elwig.Helpers {
|
||||
res.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
public static async Task<JsonArray> GetExportMetaData(string url, string username, string password) {
|
||||
public static async Task<JsonArray> GetExportMetaData(string url, string username, ReadOnlyMemory<char> password) {
|
||||
if (url.StartsWith("https://elwig.at/clients/"))
|
||||
url = "https://sync.elwig.at/" + url[25..];
|
||||
using var client = GetHttpClient(username, password, accept: "application/json");
|
||||
@@ -551,7 +551,7 @@ namespace Elwig.Helpers {
|
||||
var (host, port, mode, username, password, _, _) = App.Config.Smtp.Value;
|
||||
var client = new SmtpClient();
|
||||
await client.ConnectAsync(host, port, mode == "starttls" ? SecureSocketOptions.StartTls : SecureSocketOptions.None);
|
||||
await client.AuthenticateAsync(username, password);
|
||||
await client.AuthenticateAsync(username, password.ToString());
|
||||
return client;
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ namespace Elwig.Services {
|
||||
}
|
||||
|
||||
public static async Task BackupDatabase() {
|
||||
await Database.ExportSql(Path.Combine(App.Config.BackupPath, $"{File.GetLastWriteTime(App.Config.DatabaseFile):yyyy-MM-dd_HH-mm-ss}.sql.zip"), true);
|
||||
await Database.ExportSql(Path.Combine(App.Config.BackupPath, $"{File.GetLastWriteTime(App.Config.DatabaseFile):yyyy-MM-dd_HH-mm-ss}.sql.zip"), true, App.Config.BackupEncryptionKey);
|
||||
}
|
||||
|
||||
public static void PruneBackups() {
|
||||
@@ -122,7 +122,7 @@ namespace Elwig.Services {
|
||||
if (!InteractionService.AskContinue("Datenbank wiederherstellen", "Soll die Datenbank wirklich unwiederruflich durch die wiederhergestellte Version ersetzt werden?"))
|
||||
return;
|
||||
Mouse.OverrideCursor = Cursors.Wait;
|
||||
await App.ReplaceDatabase(d.FileName);
|
||||
await App.ReplaceDatabase(d.FileName, App.Config.BackupDecryptionKeys);
|
||||
}
|
||||
} catch (Exception exc) {
|
||||
InteractionService.ShowException(exc);
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace Elwig.Services {
|
||||
public static readonly Expression<Func<AreaCmtContract, bool>> ChangedAreaCmtContracts = (c) => ((c.XTime == null && c.MTime > 1751328000) || c.MTime > c.XTime) && (c.ITime == null || c.MTime > c.ITime);
|
||||
public static readonly Expression<Func<Delivery, bool>> ChangedDeliveries = (d) => ((d.XTime == null && d.MTime > 1751328000) || d.MTime > d.XTime) && (d.ITime == null || d.MTime > d.ITime);
|
||||
|
||||
public static async Task Upload(string url, string username, string password, IQueryable<Member> query, IEnumerable<string> filterNames) {
|
||||
public static async Task Upload(string url, string username, ReadOnlyMemory<char> password, IQueryable<Member> query, IEnumerable<string> filterNames) {
|
||||
try {
|
||||
var filename = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{App.ZwstId}.elwig.zip";
|
||||
var path = Path.Combine(App.TempPath, filename);
|
||||
@@ -54,7 +54,7 @@ namespace Elwig.Services {
|
||||
InteractionService.ShowError("Mitglieder hochladen", "Es wurden keine Mitglieder zum Hochladen ausgewählt!");
|
||||
} else {
|
||||
var exportedAt = DateTime.Now;
|
||||
await ElwigData.Export(path, members, history, areaCmts, wbKgs, filterNames);
|
||||
await ElwigData.Export(path, members, history, areaCmts, wbKgs, filterNames, App.Config.SyncEncryptionKey);
|
||||
await Utils.UploadExportData(path, url, username, password);
|
||||
await UpdateExportedAt(members, areaCmts, [], exportedAt);
|
||||
InteractionService.ShowInformation("Mitglieder hochgeladen", $"Hochladen von {members.Count:N0} Mitgliedern erfolgreich!");
|
||||
@@ -68,7 +68,7 @@ namespace Elwig.Services {
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task Upload(string url, string username, string password, IQueryable<DeliveryPart> query, IEnumerable<string> filterNames) {
|
||||
public static async Task Upload(string url, string username, ReadOnlyMemory<char> password, IQueryable<DeliveryPart> query, IEnumerable<string> filterNames) {
|
||||
try {
|
||||
var filename = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{App.ZwstId}.elwig.zip";
|
||||
var path = Path.Combine(App.TempPath, filename);
|
||||
@@ -88,7 +88,7 @@ namespace Elwig.Services {
|
||||
InteractionService.ShowError("Lieferungen hochladen", "Es wurden keine Lieferungen zum Hochladen ausgewählt!");
|
||||
} else {
|
||||
var exportedAt = DateTime.Now;
|
||||
await ElwigData.Export(path, list, wbKgs, filterNames);
|
||||
await ElwigData.Export(path, list, wbKgs, filterNames, App.Config.SyncEncryptionKey);
|
||||
await Utils.UploadExportData(path, url, username, password);
|
||||
await UpdateExportedAt([], [], list, exportedAt);
|
||||
InteractionService.ShowInformation("Lieferungen hochgeladen", $"Hochladen von {list.Count:N0} Lieferungen erfolgreich!");
|
||||
@@ -102,7 +102,7 @@ namespace Elwig.Services {
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task UploadModified(string url, string username, string password) {
|
||||
public static async Task UploadModified(string url, string username, ReadOnlyMemory<char> password) {
|
||||
try {
|
||||
var path = Path.Combine(App.TempPath, $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{App.ZwstId}.elwig.zip");
|
||||
List<Member> members;
|
||||
@@ -145,7 +145,7 @@ namespace Elwig.Services {
|
||||
AreaCmts = (areaCmts, ["geändert seit letztem Export"]),
|
||||
Deliveries = (deliveries, ["geändert seit letzem Export"]),
|
||||
WbKgs = (wbKgs, ["von exportierten Mitgliedern, Flächenbindungen und Lieferungen"]),
|
||||
}).Export(path);
|
||||
}).Export(path, App.Config.SyncEncryptionKey);
|
||||
await Utils.UploadExportData(path, url, username, password);
|
||||
await UpdateExportedAt(members, areaCmts, deliveries, exportedAt);
|
||||
InteractionService.ShowInformation("Mitglieder und Lieferungen hochladen", $"Hochladen von {members.Count:N0} Mitgliedern, {areaCmts.Count:N0} Flächenbindungsverträgen, und {deliveries.Count:N0} Lieferungen erfolgreich!");
|
||||
@@ -159,7 +159,7 @@ namespace Elwig.Services {
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task UploadBranchDeliveries(string url, string username, string password, int? year = null) {
|
||||
public static async Task UploadBranchDeliveries(string url, string username, ReadOnlyMemory<char> password, int? year = null) {
|
||||
try {
|
||||
year ??= Utils.CurrentLastSeason;
|
||||
var path = Path.Combine(App.TempPath, $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{App.ZwstId}.elwig.zip");
|
||||
@@ -179,7 +179,7 @@ namespace Elwig.Services {
|
||||
InteractionService.ShowError("Lieferungen hochladen", "Es gibt keine Lieferungen, die hochgeladen werden können!");
|
||||
} else {
|
||||
var exportedAt = DateTime.Now;
|
||||
await ElwigData.Export(path, deliveries, wbKgs, [$"{year}", $"Zweigstelle {App.BranchName}"]);
|
||||
await ElwigData.Export(path, deliveries, wbKgs, [$"{year}", $"Zweigstelle {App.BranchName}"], App.Config.SyncEncryptionKey);
|
||||
await Utils.UploadExportData(path, url, username, password);
|
||||
await UpdateExportedAt([], [], deliveries, exportedAt);
|
||||
InteractionService.ShowInformation("Lieferungen hochladen", $"Hochladen von {deliveries.Count:N0} Lieferungen erfolgreich!");
|
||||
@@ -193,7 +193,7 @@ namespace Elwig.Services {
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<List<(string Name, string Url)>> GetFilesToImport(string url, string username, string password) {
|
||||
public static async Task<List<(string Name, string Url)>> GetFilesToImport(string url, string username, ReadOnlyMemory<char> password) {
|
||||
var data = await Utils.GetExportMetaData(url, username, password);
|
||||
var files = data
|
||||
.Select(f => new {
|
||||
@@ -214,7 +214,7 @@ namespace Elwig.Services {
|
||||
];
|
||||
}
|
||||
|
||||
public static async Task Download(string url, string username, string password, bool confirmImports) {
|
||||
public static async Task Download(string url, string username, ReadOnlyMemory<char> password, bool confirmImports) {
|
||||
try {
|
||||
var import = await GetFilesToImport(url, username, password);
|
||||
var paths = new List<string>();
|
||||
@@ -226,7 +226,7 @@ namespace Elwig.Services {
|
||||
paths.Add(filename);
|
||||
}
|
||||
}
|
||||
await ElwigData.Import(paths, confirmImports ? ElwigData.ImportMode.Interactively : ElwigData.ImportMode.FromBranches);
|
||||
await ElwigData.Import(paths, confirmImports ? ElwigData.ImportMode.Interactively : ElwigData.ImportMode.FromBranches, App.Config.SyncDecryptionKeys);
|
||||
} catch (HttpRequestException exc) {
|
||||
InteractionService.ShowException("Daten herunterladen", "Eventuell Internetverbindung prüfen!", exc);
|
||||
} catch (TaskCanceledException exc) {
|
||||
@@ -257,7 +257,7 @@ namespace Elwig.Services {
|
||||
App.HintContextChange();
|
||||
}
|
||||
|
||||
public static async Task<bool> ChangesAvailable(AppDbContext ctx, string url, string username, string password) {
|
||||
public static async Task<bool> ChangesAvailable(AppDbContext ctx, string url, string username, ReadOnlyMemory<char> password) {
|
||||
try {
|
||||
return await ctx.Members.Where(ChangedMembers).AnyAsync() || await ctx.AreaCommitmentContracts.Where(ChangedAreaCmtContracts).AnyAsync() || await ctx.Deliveries.Where(ChangedDeliveries).AnyAsync() || (Utils.HasInternetConnectivity() && (await GetFilesToImport(url, username, password)).Count > 0);
|
||||
} catch {
|
||||
@@ -265,7 +265,7 @@ namespace Elwig.Services {
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<bool> ChangesAvailable(AppDbContext ctx, string url, string username, string password, int? year = null) {
|
||||
public static async Task<bool> ChangesAvailable(AppDbContext ctx, string url, string username, ReadOnlyMemory<char> password, int? year = null) {
|
||||
try {
|
||||
year ??= Utils.CurrentLastSeason;
|
||||
return await ctx.Deliveries.Where(d => d.ZwstId == App.ZwstId && d.Year == year).Where(ChangedDeliveries).AnyAsync() || (Utils.HasInternetConnectivity() && (await GetFilesToImport(url, username, password)).Count > 0);
|
||||
|
||||
@@ -274,7 +274,7 @@ namespace Elwig.Windows {
|
||||
return;
|
||||
|
||||
await App.Current.Dispatcher.BeginInvoke(async () => {
|
||||
await App.ReplaceDatabase(filename);
|
||||
await App.ReplaceDatabase(filename, App.Config.SyncDecryptionKeys);
|
||||
});
|
||||
} catch (HttpRequestException exc) {
|
||||
InteractionService.ShowException("Datenbank herunterladen", "Eventuell Internetverbindung prüfen!", exc);
|
||||
@@ -292,7 +292,7 @@ namespace Elwig.Windows {
|
||||
return;
|
||||
|
||||
if (!App.Config.SyncMain) {
|
||||
InteractionService.ShowInformation("Datenbank hochladen", "Hochladen nicht möglich: Dieses Gerät ist nicht das Hauptgerät!");
|
||||
InteractionService.ShowInformation("Datenbank hochladen", "Hochladen nicht möglich:\nDieses Gerät ist nicht das Hauptgerät!");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -303,7 +303,7 @@ namespace Elwig.Windows {
|
||||
await Task.Run(async () => {
|
||||
try {
|
||||
var path = Path.Combine(App.TempPath, "database.sql.zip");
|
||||
await Database.ExportSql(path, true);
|
||||
await Database.ExportSql(path, true, App.Config.SyncEncryptionKey);
|
||||
await Utils.UploadExportData(path, App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
|
||||
InteractionService.ShowInformation("Datenbank hochladen", $"Hochladen der gesamten Datenbank erfolgreich!");
|
||||
} catch (HttpRequestException exc) {
|
||||
|
||||
@@ -18,6 +18,8 @@ file = database.sqlite3
|
||||
;retain_days = 8
|
||||
;retain_weeks = 6
|
||||
;retain_months = 18
|
||||
; keys may not contain ","! Do NOT quote the strings (""), spaces before/after the string are trimmed!
|
||||
;key = current encryption key, old decryption key, another old key
|
||||
|
||||
[update]
|
||||
url = https://elwig.at/files/elwig/latest
|
||||
@@ -27,6 +29,8 @@ auto = true
|
||||
;url = https://elwig.at/clients/WGX/
|
||||
;username = ""
|
||||
;password = ""
|
||||
; keys may not contain ","! Do NOT quote the strings (""), spaces before/after the string are trimmed!
|
||||
;key = current encryption key, old decryption key, another old key
|
||||
|
||||
[smtp]
|
||||
;host =
|
||||
|
||||
Reference in new issue
Block a user