using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Security.Cryptography; using Chronos.Protocol; using Chronos.Testing; namespace Chronos.Server.Tests; /// Raw-HTTP upload helpers (the protocol client is exercised separately). internal static class Uploads { public static byte[] Photo(int size, int seed) { var bytes = new byte[size]; new Random(seed).NextBytes(bytes); return bytes; } public static string Sha(byte[] data) => Convert.ToHexStringLower(SHA256.HashData(data)); /// The capture time the client sends; null: 2026-09-28 18:02:11. public static async Task StartAsync(HttpClient client, byte[] data, string fileName = "IMG_0001.CR3", Guid? sequenceId = null, string? sessionKey = null, HttpStatusCode expected = HttpStatusCode.Created, DateTime? capturedAt = null) { using var response = await client.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(sequenceId, fileName, data.Length, Sha(data), capturedAt ?? new DateTime(2026, 9, 28, 18, 2, 11), sessionKey), ProtocolJson.Default.StartUploadRequest); await response.ExpectAsync(expected); return await response.ReadAsync(ProtocolJson.Default.StartUploadResponse); } public static async Task PutChunkAsync(HttpClient client, Guid uploadId, int index, ReadOnlyMemory data) { var content = new ByteArrayContent(data.ToArray()); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return await client.PutAsync($"/api/v1/uploads/{uploadId}/chunks/{index}", content); } public static ReadOnlyMemory Chunk(byte[] data, int chunkSize, int index) => data.AsMemory(index * chunkSize, Math.Min(chunkSize, data.Length - index * chunkSize)); /// Start, every chunk, complete; returns the committed frame. public static async Task UploadAsync(HttpClient client, byte[] data, string fileName = "IMG_0001.CR3", Guid? sequenceId = null, string? sessionKey = null, DateTime? capturedAt = null) { var start = await StartAsync(client, data, fileName, sequenceId, sessionKey, capturedAt: capturedAt); var id = Assert.NotNull(start.UploadId); var chunks = (data.Length + start.ChunkSize - 1) / start.ChunkSize; for (var i = 0; i < chunks; i++) { using var put = await PutChunkAsync(client, id, i, Chunk(data, start.ChunkSize, i)); await put.ExpectAsync(HttpStatusCode.OK); } using var complete = await client.PostAsync($"/api/v1/uploads/{id}/complete", null); await complete.ExpectAsync(HttpStatusCode.OK); return await complete.ReadAsync(ProtocolJson.Default.CompleteUploadResponse); } }