diff options
| author | Jake Mannens <jake@asger.xyz> | 2026-04-29 23:26:18 +1000 |
|---|---|---|
| committer | Jake Mannens <jake@asger.xyz> | 2026-05-06 04:24:37 +1000 |
| commit | 4d3e88b9f54e893a6de49724538cd73c9dc6ea5f (patch) | |
| tree | 624575e4d948f7a01f16fa8680e346ba1716ae05 /Media.cs | |
v0.13av0.13a
Diffstat (limited to 'Media.cs')
| -rw-r--r-- | Media.cs | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/Media.cs b/Media.cs new file mode 100644 index 0000000..794e5f2 --- /dev/null +++ b/Media.cs @@ -0,0 +1,72 @@ +using HyperBooru.ApiModels; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Security.Cryptography; +using System.Text.Json; + +namespace HyperBooru.ApiClient; + +public class Media { + private HBSession session; + + internal Media(HBSession session) => + this.session = session; + + public async Task<ApiModels.Media> GetAsync(Guid mediaId) => + (await session.HttpClient.GetFromJsonAsync<ApiModels.Media>($"/api/media/{mediaId}"))!; + + public async Task<ApiModels.UploadedFile[]> GetUploadedFilesAsync(Guid mediaId) => + (await session.HttpClient.GetFromJsonAsync<ApiModels.UploadedFile[]>($"/api/media/{mediaId}/files"))!; + + public async Task<ApiModels.Media> UploadAsync( + string path, + Guid[]? tagIds, + bool isIngest = true) { + + var formData = new MultipartFormDataContent(); + + FileInfo fileInfo = new FileInfo(path); + + Stream fileData = File.OpenRead(path); + + var hash = BitConverter + .ToString(MD5.Create().ComputeHash(fileData)) + .Replace("-", "") + .ToLower(); + fileData.Seek(0, SeekOrigin.Begin); + + var fileContent = new StreamContent(fileData) { + Headers = { + ContentLength = fileData.Length, + ContentType = new MediaTypeHeaderValue("image/png") + } + }; + + var metadata = new MediaUploadRequest() { + Checksum = hash, + LastAccessTime = fileInfo.LastAccessTimeUtc, + LastWriteTime = fileInfo.LastWriteTimeUtc, + CreateTime = fileInfo.CreationTimeUtc, + Path = fileInfo.Directory?.FullName, + PathType = fileInfo.Directory is null ? null : Util.CurrentOSPathType, + Tags = tagIds, + IsIngest = isIngest + }; + + fileContent.Headers.Add("X-HyperBooru-Metadata", JsonSerializer.Serialize(metadata)); + + formData.Add( + fileContent, + "file", + Path.GetFileName(path)); + + Guid mediaId = Guid.Empty; + + var response = await session.HttpClient.PostAsync("/api/media", formData); + var responseContent = await response.Content.ReadFromJsonAsync<ApiModels.Media>(); + + fileData.Close(); + + return responseContent!; + } +} |
