Files
LehrerApp/LehrerApp.Sync/AttachmentSyncer.cs

39 lines
1.5 KiB
C#

using LehrerApp.Data;
using LehrerApp.Sync.Crypto;
namespace LehrerApp.Sync;
/// <summary>
/// Lädt ausstehende Datei-Anhänge (siehe <see cref="EventQueue.GetPendingAttachmentUploads"/>)
/// als eigenen, verschlüsselten Binärtransfer hoch — getrennt vom JSON-Ereigniskanal, damit
/// Fotos/Scans ihn nicht aufblähen. Gegenstück zum Download in <see cref="EventApplier"/>.
/// </summary>
public class AttachmentSyncer(LiteDbContext db, HttpClient http, byte[] syncKey)
{
public async Task UploadPendingAsync(EventQueue queue)
{
foreach (var storageId in queue.GetPendingAttachmentUploads())
{
if (!db.Attachments.Exists(storageId))
{
// Lokal inzwischen wieder gelöscht (z.B. HardDelete vor dem eigentlichen Upload) -
// nichts hochzuladen, Warteliste trotzdem bereinigen.
queue.MarkAttachmentUploaded(storageId);
continue;
}
using var raw = db.Attachments.OpenRead(storageId);
using var buffer = new MemoryStream();
await raw.CopyToAsync(buffer);
var encrypted = SyncCrypto.Encrypt(buffer.ToArray(), syncKey);
using var request = SyncProtocol.CreateRequest(HttpMethod.Post,
$"/api/sync/attachments/{storageId}");
request.Content = new ByteArrayContent(encrypted);
using var resp = await http.SendAsync(request);
await SyncProtocol.EnsureCompatibleSuccessAsync(resp);
queue.MarkAttachmentUploaded(storageId);
}
}
}