using System.Net; using System.Net.Http.Headers; using collAnon.Client.Services; using decePubClient.Extensions; using decePubClient.Models; using decePubClient.Models.Mastodon; using PrivaPub.ClientModels; namespace decePubClient.Services { /// Uploads a picked file to PrivaPub (/api/v2/media, multipart) before the post that uses it. public class MediaService(IHttpService httpService, CoalescingStringLocalizer localizer) { /// The uploaded attachment as Data; its id goes in the post's media_ids. public async Task Upload(UploadMedia media, CancellationToken cancellationToken = default) { using var response = await httpService.Post(APIs.Mastodon.POST_Media, (Func)(() => { var file = new ByteArrayContent(media.Blob); file.Headers.ContentType = MediaTypeHeaderValue.Parse(media.ContentType); var content = new MultipartFormDataContent { { file, "file", media.FileName } }; if (media.AltText is { Length: > 0 } description) content.Add(new StringContent(description), "description"); return content; }), cancellationToken: cancellationToken); if (!response.IsSuccessStatusCode) return await response.Content.ReadWebResult(response.StatusCode, localizer, cancellationToken); var attachment = await response.MastodonReadFromJsonAsync(cancellationToken); return attachment?.Id is null ? new WebResult().Invalidate(localizer["The server sent an invalid response."], (int)HttpStatusCode.BadGateway) : new WebResult { Data = attachment }; } } }