From 12eaa5814ef20b0910e8d64a753378b6f6797989 Mon Sep 17 00:00:00 2001 From: Jake Mannens Date: Fri, 22 May 2026 00:52:16 +1000 Subject: Initial commit --- Server/Components/App.razor | 24 + Server/Components/Pages/Error.razor | 36 ++ Server/Components/_Imports.razor | 11 + Server/Controllers/ApiFeedController.cs | 23 + Server/Controllers/ApiMediaController.cs | 219 +++++++ Server/Controllers/ApiTagController.cs | 252 ++++++++ Server/Controllers/ApiUserController.cs | 109 ++++ Server/Controllers/MediaController.cs | 154 +++++ Server/Dockerfile | 16 + Server/ExceptionMiddleware.cs | 64 ++ Server/HBContext.cs | 84 +++ Server/HBObject.cs | 14 + Server/LICENSE.txt | 661 +++++++++++++++++++++ Server/Media.cs | 92 +++ .../20260131125650_InitialMigration.Designer.cs | 362 +++++++++++ .../Migrations/20260131125650_InitialMigration.cs | 319 ++++++++++ Server/Migrations/HBContextModelSnapshot.cs | 359 +++++++++++ Server/Program.cs | 73 +++ Server/Properties/launchSettings.json | 25 + Server/Server.csproj | 34 ++ Server/Services/ConfigService.cs | 72 +++ Server/Services/FeedService.cs | 212 +++++++ Server/Services/MediaService.cs | 400 +++++++++++++ Server/Services/OcrService.cs | 128 ++++ Server/Services/SourceService.cs | 20 + Server/Services/TagService.cs | 305 ++++++++++ Server/Services/UserService.cs | 76 +++ Server/Tag.cs | 37 ++ Server/Todo.md | 41 ++ Server/User.cs | 15 + Server/Util.cs | 120 ++++ Server/appsettings.Development.json | 8 + Server/appsettings.json | 12 + Server/dotnet-tools.json | 13 + Server/tessdata/eng.traineddata | Bin 0 -> 15400601 bytes Server/wwwroot/app.css | 60 ++ Server/wwwroot/css/site.css | 28 + Server/wwwroot/favicon.ico | Bin 0 -> 3262 bytes Server/wwwroot/icon-192.png | Bin 0 -> 31523 bytes Server/wwwroot/icon-512.png | Bin 0 -> 136487 bytes Server/wwwroot/images/book.svg | 7 + Server/wwwroot/images/checkmark.svg | 7 + Server/wwwroot/images/cross.svg | 7 + Server/wwwroot/images/edit.svg | 7 + Server/wwwroot/images/info.svg | 63 ++ Server/wwwroot/images/loginbg.webp | Bin 0 -> 2247672 bytes Server/wwwroot/images/photo.svg | 7 + Server/wwwroot/images/tag.svg | 7 + Server/wwwroot/images/trash.svg | 7 + Server/wwwroot/js/dialog.js | 78 +++ Server/wwwroot/js/keyboard.js | 57 ++ Server/wwwroot/js/mobile.js | 7 + Server/wwwroot/loginbg.webm | Bin 0 -> 390877 bytes Server/wwwroot/manifest.webmanifest | 6 + Server/wwwroot/styles/data-table.css | 21 + Server/wwwroot/styles/global.css | 214 +++++++ 56 files changed, 4973 insertions(+) create mode 100644 Server/Components/App.razor create mode 100644 Server/Components/Pages/Error.razor create mode 100644 Server/Components/_Imports.razor create mode 100644 Server/Controllers/ApiFeedController.cs create mode 100644 Server/Controllers/ApiMediaController.cs create mode 100644 Server/Controllers/ApiTagController.cs create mode 100644 Server/Controllers/ApiUserController.cs create mode 100644 Server/Controllers/MediaController.cs create mode 100644 Server/Dockerfile create mode 100644 Server/ExceptionMiddleware.cs create mode 100644 Server/HBContext.cs create mode 100644 Server/HBObject.cs create mode 100644 Server/LICENSE.txt create mode 100644 Server/Media.cs create mode 100644 Server/Migrations/20260131125650_InitialMigration.Designer.cs create mode 100644 Server/Migrations/20260131125650_InitialMigration.cs create mode 100644 Server/Migrations/HBContextModelSnapshot.cs create mode 100644 Server/Program.cs create mode 100644 Server/Properties/launchSettings.json create mode 100644 Server/Server.csproj create mode 100644 Server/Services/ConfigService.cs create mode 100644 Server/Services/FeedService.cs create mode 100644 Server/Services/MediaService.cs create mode 100644 Server/Services/OcrService.cs create mode 100644 Server/Services/SourceService.cs create mode 100644 Server/Services/TagService.cs create mode 100644 Server/Services/UserService.cs create mode 100644 Server/Tag.cs create mode 100644 Server/Todo.md create mode 100644 Server/User.cs create mode 100644 Server/Util.cs create mode 100644 Server/appsettings.Development.json create mode 100644 Server/appsettings.json create mode 100644 Server/dotnet-tools.json create mode 100644 Server/tessdata/eng.traineddata create mode 100644 Server/wwwroot/app.css create mode 100644 Server/wwwroot/css/site.css create mode 100644 Server/wwwroot/favicon.ico create mode 100644 Server/wwwroot/icon-192.png create mode 100644 Server/wwwroot/icon-512.png create mode 100644 Server/wwwroot/images/book.svg create mode 100644 Server/wwwroot/images/checkmark.svg create mode 100644 Server/wwwroot/images/cross.svg create mode 100644 Server/wwwroot/images/edit.svg create mode 100644 Server/wwwroot/images/info.svg create mode 100644 Server/wwwroot/images/loginbg.webp create mode 100644 Server/wwwroot/images/photo.svg create mode 100644 Server/wwwroot/images/tag.svg create mode 100644 Server/wwwroot/images/trash.svg create mode 100644 Server/wwwroot/js/dialog.js create mode 100644 Server/wwwroot/js/keyboard.js create mode 100644 Server/wwwroot/js/mobile.js create mode 100644 Server/wwwroot/loginbg.webm create mode 100644 Server/wwwroot/manifest.webmanifest create mode 100644 Server/wwwroot/styles/data-table.css create mode 100644 Server/wwwroot/styles/global.css (limited to 'Server') diff --git a/Server/Components/App.razor b/Server/Components/App.razor new file mode 100644 index 0000000..614372e --- /dev/null +++ b/Server/Components/App.razor @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Server/Components/Pages/Error.razor b/Server/Components/Pages/Error.razor new file mode 100644 index 0000000..576cc2d --- /dev/null +++ b/Server/Components/Pages/Error.razor @@ -0,0 +1,36 @@ +@page "/Error" +@using System.Diagnostics + +Error + +

Error.

+

An error occurred while processing your request.

+ +@if (ShowRequestId) +{ +

+ Request ID: @RequestId +

+} + +

Development Mode

+

+ Swapping to Development environment will display more detailed information about the error that occurred. +

+

+ The Development environment shouldn't be enabled for deployed applications. + It can result in displaying sensitive information from exceptions to end users. + For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development + and restarting the app. +

+ +@code{ + [CascadingParameter] + private HttpContext? HttpContext { get; set; } + + private string? RequestId { get; set; } + private bool ShowRequestId => !string.IsNullOrEmpty(RequestId); + + protected override void OnInitialized() => + RequestId = Activity.Current?.Id ?? HttpContext?.TraceIdentifier; +} diff --git a/Server/Components/_Imports.razor b/Server/Components/_Imports.razor new file mode 100644 index 0000000..2986fa6 --- /dev/null +++ b/Server/Components/_Imports.razor @@ -0,0 +1,11 @@ +@using System.Net.Http +@using System.Net.Http.Json +@using Microsoft.AspNetCore.Components.Forms +@using Microsoft.AspNetCore.Components.Routing +@using Microsoft.AspNetCore.Components.Web +@using static Microsoft.AspNetCore.Components.Web.RenderMode +@using Microsoft.AspNetCore.Components.Web.Virtualization +@using Microsoft.JSInterop +@using HyperBooru.Server +@using HyperBooru.Client +@using HyperBooru.Server.Components diff --git a/Server/Controllers/ApiFeedController.cs b/Server/Controllers/ApiFeedController.cs new file mode 100644 index 0000000..fb260e6 --- /dev/null +++ b/Server/Controllers/ApiFeedController.cs @@ -0,0 +1,23 @@ +using HyperBooru.ApiModels; +using HyperBooru.Services; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru.Controllers; + +[ApiController] +[Route("/api/feed")] +public class ApiFeedController : Controller { + private IFeedService feedService; + + public ApiFeedController(IDbContextFactory dbFactory, IFeedService feedService) => + this.feedService = feedService; + + [HttpPost] + public IActionResult FetchChunkAsync([FromBody] FeedRequest feedRequest) { + if(feedRequest.Count > 1000) + return BadRequest("Total number of requested items exceeds maximum"); + + return Ok(feedService.LoadChunk(feedRequest).Select(m => m.Guid).ToArray()); + } +} diff --git a/Server/Controllers/ApiMediaController.cs b/Server/Controllers/ApiMediaController.cs new file mode 100644 index 0000000..5a8ef21 --- /dev/null +++ b/Server/Controllers/ApiMediaController.cs @@ -0,0 +1,219 @@ +using HyperBooru.ApiModels; +using HyperBooru.Services; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System.Text.Json; + +namespace HyperBooru.Controllers; + +[ApiController] +[Route("/api/media")] +public class ApiMediaController : Controller { + private IDbContextFactory dbFactory; + private IMediaService mediaService; + + public ApiMediaController(IDbContextFactory dbFactory, IMediaService mediaService) { + this.dbFactory = dbFactory; + this.mediaService = mediaService; + } + + [HttpGet("{mediaId}")] + public async Task Get([FromRoute] Guid mediaId) { + using var db = dbFactory.CreateDbContext(); + + var media = await db.Media.FirstOrDefaultAsync(m => m.Guid == mediaId); + + if(media is null) + throw new ObjectNotFoundException(mediaId); + + return Ok((ApiModels.Media) media); + } + + [HttpGet("{mediaId}/files")] + public async Task GetUploadedFiles([FromRoute] Guid mediaId) { + using var db = dbFactory.CreateDbContext(); + + var media = await db.Media + .Include(m => m.UploadedFiles) + .FirstOrDefaultAsync(m => m.Guid == mediaId); + + if(media is null) + throw new ObjectNotFoundException(mediaId); + + return Ok(media.UploadedFiles.Select(uf => (ApiModels.UploadedFile) uf).ToArray()); + } + + [HttpPatch] + public async Task UpdateMedia([FromBody] ApiModels.Media updatedMedia) { + using var db = dbFactory.CreateDbContext(); + using var transaction = await db.Database.BeginTransactionAsync(); + + var media = await db.Media.FirstOrDefaultAsync(m => m.Guid == updatedMedia.MediaId); + if(media is null) + return NotFound(); + + media.ShortDescription = updatedMedia.ShortDescription; + media.LongDescription = updatedMedia.LongDescription; + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok(); + } + + [HttpPost] + public IActionResult Upload() { + if(Request.Form.Files.Count == 0) + return BadRequest("No files"); + if(Request.Form.Files.Count > 1) + return BadRequest("More than one file supplied"); + + var metadataString = Request.Form.Files + .First() + .Headers["X-HyperBooru-Metadata"] + .ElementAtOrDefault(0); + + MediaUploadRequest? metadata = metadataString is null ? null : + JsonSerializer.Deserialize(metadataString); + + var formFile = Request.Form.Files.First(); + + var media = mediaService.Create( + formFile.OpenReadStream(), + formFile.FileName, + metadata?.Checksum, + metadata?.LastAccessTime, + metadata?.LastWriteTime, + metadata?.CreateTime, + metadata?.Path, + metadata?.PathType, + metadata?.Tags); + + return Ok((ApiModels.Media) media); + } + + [HttpDelete("{mediaId}")] + public void Delete([FromRoute] Guid mediaId) => + mediaService.Delete(mediaId); + + [HttpGet("{mediaId}/tags")] + public async Task GetMediaTagsAsync([FromRoute] Guid mediaId) { + using var db = dbFactory.CreateDbContext(); + + var media = await db.Media + .Include(m => m.Tags) + .ThenInclude(t => t.TagDefinition) + .ThenInclude(td => td.ImplicitTags) + .FirstOrDefaultAsync(m => m.Guid == mediaId); + if(media is null) + return NotFound(); + + return Ok(media.Tags.Select(t => (ApiModels.TagDefinition) t.TagDefinition).ToArray()); + } + + [HttpPatch("{mediaId}/tags")] + public async Task AddTagsToMediaAsync( + [FromRoute] Guid mediaId, + [FromBody] Guid[] tagIds) { + + using var db = dbFactory.CreateDbContext(); + using var transaction = await db.Database.BeginTransactionAsync(); + + var media = await db.Media + .Include(m => m.Tags) + .ThenInclude(t => t.TagDefinition) + .ThenInclude(td => td.ImplicitTags) + .FirstOrDefaultAsync(m => m.Guid == mediaId); + if(media is null) + return NotFound(); + + tagIds = tagIds.Distinct().ToArray(); + + var tags = await db.TagDefinitions + .Where(td => tagIds.Contains(td.Guid)) + .ToArrayAsync(); + + if(tags.Count() < tagIds.Count()) + return NotFound("Invalid tag IDs specified"); + + media.Tags.AddRange(tags + .Where(td => !media.Tags.Select(t => t.TagDefinition.Guid).Contains(td.Guid)) + .Select(td => new Tag() { TagDefinition = td })); + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok(media.Tags.Select(t => (ApiModels.TagDefinition) t.TagDefinition).ToArray()); + } + + [HttpPut("{mediaId}/tags")] + public async Task ReplaceMediaTagsAsync( + [FromRoute] Guid mediaId, + [FromBody] Guid[] tagIds) { + + using var db = dbFactory.CreateDbContext(); + using var transaction = await db.Database.BeginTransactionAsync(); + + var media = await db.Media + .Include(m => m.Tags) + .ThenInclude(t => t.TagDefinition) + .ThenInclude(td => td.ImplicitTags) + .FirstOrDefaultAsync(m => m.Guid == mediaId); + if(media is null) + return NotFound(); + + tagIds = tagIds.Distinct().Order().ToArray(); + var tags = await db.TagDefinitions + .Where(td => tagIds.Contains(td.Guid)) + .ToArrayAsync(); + + var missingTags = tagIds.Except(tags.Select(td => td.Guid)); + var missingTagsString = string.Join(", ", missingTags.Select(t => t.ToString())); + if(missingTags.Any()) + return BadRequest($"Invalid tag IDs specified: {missingTagsString}"); + + media.Tags.AddRange(tags + .Where(td => !media.Tags.Select(t => t.TagDefinition.Guid).Contains(td.Guid)) + .Select(td => new Tag() { TagDefinition = td })); + + db.Tags.RemoveRange( + media.Tags.Where(t => !tagIds.Contains(t.TagDefinition.Guid))); + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok(media.Tags.Select(t => (ApiModels.TagDefinition) t.TagDefinition).ToArray()); + } + + [HttpPatch("{mediaId}/tags/delete")] + public async Task DeleteTagsFromMediaAsync( + [FromRoute] Guid mediaId, + [FromBody] Guid[] tagIds) { + + using var db = dbFactory.CreateDbContext(); + using var transaction = await db.Database.BeginTransactionAsync(); + + var media = await db.Media + .Include(m => m.Tags) + .ThenInclude(t => t.TagDefinition) + .ThenInclude(td => td.ImplicitTags) + .FirstOrDefaultAsync(m => m.Guid == mediaId); + if(media is null) + return NotFound(); + + tagIds = tagIds.Distinct().Order().ToArray(); + + var missingTags = tagIds.Except(media.Tags.Select(t => t.TagDefinition.Guid)); + var missingTagsString = string.Join(", ", missingTags.Select(t => t.ToString())); + if(missingTags.Any()) + return BadRequest($"Media does not contain the following tags: {missingTagsString}"); + + db.Tags.RemoveRange( + media.Tags.Where(t => tagIds.Contains(t.TagDefinition.Guid))); + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok(media.Tags.Select(t => (ApiModels.TagDefinition) t.TagDefinition).ToArray()); + } +} diff --git a/Server/Controllers/ApiTagController.cs b/Server/Controllers/ApiTagController.cs new file mode 100644 index 0000000..e8417d2 --- /dev/null +++ b/Server/Controllers/ApiTagController.cs @@ -0,0 +1,252 @@ +using HyperBooru.ApiModels; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru.Controllers; + +[ApiController] +[Route("/api/tag")] +public class ApiTagController : Controller { + private IDbContextFactory dbFactory; + + public ApiTagController(IDbContextFactory dbFactory) => + this.dbFactory = dbFactory; + + [HttpGet("definition")] + public async Task GetAllTagDefinitionsAsync() { + using var db = dbFactory.CreateDbContext(); + + var definitions = await db.TagDefinitions + .Include(td => td.ImplicitTags) + .Select(td => (ApiModels.TagDefinition)td) + .ToArrayAsync(); + + return Ok(definitions); + } + + [HttpGet("definition/{tagDefinitionId}")] + public async Task GetTagDefinitionAsync([FromRoute] Guid tagDefinitionId) { + using var db = dbFactory.CreateDbContext(); + + var tagDefinition = await db.TagDefinitions + .Include(td => td.ImplicitTags) + .FirstOrDefaultAsync(td => td.Guid == tagDefinitionId); + + return tagDefinition is not null ? Ok(tagDefinition) : NotFound(); + } + + [HttpPost("definition")] + public async Task CreateTagDefinitionAsync([FromBody] TagCreateRequest request) { + using var db = dbFactory.CreateDbContext(); + using var transaction = await db.Database.BeginTransactionAsync(); + + if(db.TagDefinitions.Any(td => td.Name == request.Name)) + return BadRequest("Name already exists"); + + if(request.Alias is not null) + if(db.TagDefinitions.Any(td => td.Alias == request.Alias)) + return BadRequest("Alias already exists"); + + List implicitTags = new(); + if(request.ImplicitTags is not null) { + implicitTags = await db.TagDefinitions + .Where(td => request.ImplicitTags.Distinct().Contains(td.Guid)) + .ToListAsync(); + } + + var tagDefinition = new TagDefinition { + Source = TagSource.UserTag, + Namespace = request.Namespace, + Name = request.Name, + Alias = request.Alias, + ImplicitTags = implicitTags + }; + + db.TagDefinitions.Add(tagDefinition); + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok((ApiModels.TagDefinition) tagDefinition); + } + + [HttpDelete("definition/{tagDefinitionId}")] + public async Task DeleteTagDefinitionAsync([FromRoute] Guid tagDefinitionId) { + using var db = dbFactory.CreateDbContext(); + using var transaction = await db.Database.BeginTransactionAsync(); + + var tagDefinition = await db.TagDefinitions + .FirstOrDefaultAsync(td => td.Guid == tagDefinitionId); + + if(tagDefinition is null) + return NotFound("Tag definition not found"); + + if(tagDefinition.ObjectId < 0) + return BadRequest("Cannot delete built-in tag definition"); + + db.TagDefinitions.Remove(tagDefinition); + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok(); + } + + [HttpPatch("definition/{tagDefinitionId}")] + public async Task UpdateTagDefinitionAsync( + [FromRoute] Guid tagDefinitionId, + [FromBody] TagUpdateRequest request) { + + using var db = dbFactory.CreateDbContext(); + using var transaction = await db.Database.BeginTransactionAsync(); + + var tagDefinition = await db.TagDefinitions + .FirstOrDefaultAsync(td => td.Guid == tagDefinitionId); + + if(tagDefinition is null) + return NotFound("Tag definition not found"); + + if(tagDefinition.ObjectId < 0) + return BadRequest("Cannot update built-in tag definition"); + + if(request.Name is not null) + if(db.TagDefinitions.Any(td => td.Name == request.Name)) + return BadRequest("Name already exists"); + + if(request.Alias is not null) + if(db.TagDefinitions.Any(td => td.Alias == request.Alias)) + return BadRequest("Alias already exists"); + + tagDefinition.Namespace = request.Namespace ?? tagDefinition.Namespace; + tagDefinition.Name = request.Name ?? tagDefinition.Name; + tagDefinition.Alias = request.Alias ?? tagDefinition.Alias; + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok((ApiModels.TagDefinition) tagDefinition); + } + + [HttpPatch("definition/{tagDefinitionId}/implicit")] + public async Task AddImplicitTagsAsync( + [FromRoute] Guid tagDefinitionId, + [FromBody] Guid[] implicitTagIds) { + + using var db = dbFactory.CreateDbContext(); + using var transaction = await db.Database.BeginTransactionAsync(); + + var tagDefinition = await db.TagDefinitions + .Include(td => td.ImplicitTags) + .FirstOrDefaultAsync(td => td.Guid == tagDefinitionId); + + if(tagDefinition is null) + return NotFound("Tag definition not found"); + + if(tagDefinition.ObjectId < 0) + return BadRequest("Cannot update built-in tag definition"); + + implicitTagIds = implicitTagIds.Distinct().ToArray(); + + var implicitTags = db.TagDefinitions + .Where(td => implicitTagIds.Contains(td.Guid)) + .ToArray(); + + var missingTags = implicitTagIds.Except(implicitTags.Select(td => td.Guid)); + var missingTagsString = string.Join(", ", missingTags.Select(td => td.ToString())); + if(missingTags.Any()) + return BadRequest($"Invalid tag IDs specified: {missingTagsString}"); + + tagDefinition.ImplicitTags.AddRange( + implicitTags.ExceptBy(tagDefinition.ImplicitTags.Select(td => td.Guid), td => td.Guid)); + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok(); + } + + [HttpPut("definition/{tagDefinitionId}/implicit")] + public async Task ReplaceImplicitTagsAsync( + [FromRoute] Guid tagDefinitionId, + [FromBody] Guid[] implicitTagIds) { + + using var db = dbFactory.CreateDbContext(); + using var transaction = await db.Database.BeginTransactionAsync(); + + var tagDefinition = await db.TagDefinitions + .Include(td => td.ImplicitTags) + .FirstOrDefaultAsync(td => td.Guid == tagDefinitionId); + + if(tagDefinition is null) + return NotFound("Tag definition not found"); + + if(tagDefinition.ObjectId < 0) + return BadRequest("Cannot update built-in tag definition"); + + implicitTagIds = implicitTagIds.Distinct().ToArray(); + + var implicitTags = db.TagDefinitions + .Where(td => implicitTagIds.Contains(td.Guid)) + .ToArray(); + + var missingTags = implicitTagIds.Except(implicitTags.Select(td => td.Guid)); + var missingTagsString = string.Join(", ", missingTags.Select(td => td.ToString())); + if(missingTags.Any()) + return BadRequest($"Invalid tag IDs specified: {missingTagsString}"); + + tagDefinition.ImplicitTags.AddRange( + implicitTags.ExceptBy(tagDefinition.ImplicitTags.Select(td => td.Guid), td => td.Guid)); + + var toRemove = tagDefinition.ImplicitTags + .Where(td => !implicitTags.Select(td => td.Guid).Contains(td.Guid)) + .ToArray(); + + foreach(var td in toRemove) + tagDefinition.ImplicitTags.Remove(td); + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok(); + } + + [HttpPost("definition/{tagDefinitionId}/implicit/delete")] + public async Task DeleteImplicitTagAsync( + [FromRoute] Guid tagDefinitionId, + [FromBody] Guid[] implicitTagIds) { + + using var db = dbFactory.CreateDbContext(); + using var transaction = await db.Database.BeginTransactionAsync(); + + var tagDefinition = await db.TagDefinitions + .Include(td => td.ImplicitTags) + .FirstOrDefaultAsync(td => td.Guid == tagDefinitionId); + + if(tagDefinition is null) + return NotFound("Tag definition not found"); + + if(tagDefinition.ObjectId < 0) + return BadRequest("Cannot update built-in tag definition"); + + implicitTagIds = implicitTagIds.Distinct().ToArray(); + + var missingTagIds = implicitTagIds + .Except(tagDefinition.ImplicitTags.Select(td => td.Guid)); + var missingTagsString = string.Join(", ", missingTagIds.Select(td => td.ToString())); + if(missingTagIds.Any()) + return BadRequest($"Invalid tag IDs specified: {missingTagsString}"); + + var toRemove = tagDefinition.ImplicitTags + .Where(td => !implicitTagIds.Contains(td.Guid)) + .ToArray(); + + foreach(var td in toRemove) + tagDefinition.ImplicitTags.Remove(td); + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok(); + } +} diff --git a/Server/Controllers/ApiUserController.cs b/Server/Controllers/ApiUserController.cs new file mode 100644 index 0000000..d678287 --- /dev/null +++ b/Server/Controllers/ApiUserController.cs @@ -0,0 +1,109 @@ +using HyperBooru.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru.Controllers; + +[ApiController] +[Authorize] +[Route("/api/user")] +public class ApiUserController : Controller { + private IDbContextFactory dbFactory; + + public ApiUserController(IDbContextFactory dbFactory) => + this.dbFactory = dbFactory; + + [HttpGet] + public async Task GetAllUsersAsync() { + using var db = dbFactory.CreateDbContext(); + + return Ok(await db.Users + .Select(u => (ApiModels.User) u) + .ToArrayAsync()); + } + + [HttpGet("{userId}")] + public async Task GetUserAsync([FromRoute] Guid userId) { + using var db = dbFactory.CreateDbContext(); + + var user = await db.Users + .FirstOrDefaultAsync(u => u.Guid == userId); + + return user is null ? NotFound() : Ok((ApiModels.User) user); + } + + [HttpPost] + public async Task CreateUserAsync([FromBody] ApiModels.UserCreateRequest request) { + using var db = dbFactory.CreateDbContext(); + + using var transaction = await db.Database.BeginTransactionAsync(); + + if(await db.Users.AnyAsync(u => u.Username == request.Username)) + return BadRequest("Username already exists"); + + var user = new User() { + Username = request.Username, + PasswordHash = UserService.HashPassword(request.Password) + }; + + db.Users.Add(user); + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok((ApiModels.User) user); + } + + [HttpPatch("{userId}")] + public async Task UpdateUserAsync( + [FromRoute] Guid userId, + [FromBody] ApiModels.UserUpdateRequest request) { + + using var db = dbFactory.CreateDbContext(); + + using var transaction = await db.Database.BeginTransactionAsync(); + + var user = await db.Users.FirstOrDefaultAsync(u => u.Guid == userId); + if(user is null) + return NotFound(); + + if(request.Username is not null) { + if(string.IsNullOrWhiteSpace(request.Username)) + return BadRequest("Username cannot be empty"); + user.Username = request.Username; + } + + if(request.Password is not null) { + if(string.IsNullOrWhiteSpace(request.Password)) + return BadRequest("Password cannot be empty"); + user.PasswordHash = UserService.HashPassword(request.Password); + } + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok((ApiModels.User) user); + } + + [HttpDelete("{userId}")] + public async Task DeleteUserAsync([FromRoute] Guid userId) { + if(userId == HBContext.AdminUser) + return BadRequest("Cannot delete the admin user"); + + using var db = dbFactory.CreateDbContext(); + + using var transaction = await db.Database.BeginTransactionAsync(); + + var user = await db.Users.FirstOrDefaultAsync(u => u.Guid == userId); + if(user is null) + return NotFound(); + + db.Users.Remove(user); + + await db.SaveChangesAsync(); + await transaction.CommitAsync(); + + return Ok((ApiModels.User) user); + } +} diff --git a/Server/Controllers/MediaController.cs b/Server/Controllers/MediaController.cs new file mode 100644 index 0000000..27c3cbd --- /dev/null +++ b/Server/Controllers/MediaController.cs @@ -0,0 +1,154 @@ +using HyperBooru.ApiModels; +using HyperBooru.Services; +using HyperBooru.Util; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru.Controllers; + +[ApiController] +[Route("/media")] +public class MediaController : Controller { + private IHttpContextAccessor httpContextAccessor; + private IMediaService mediaService; + private IConfigService config; + private HBContext db; + + private readonly string[] FormatPriority = [ + "image/webp", + "image/png" + ]; + + public MediaController( + IHttpContextAccessor httpContextAccessor, + IMediaService mediaService, + IConfigService config, + HBContext db) { + + this.httpContextAccessor = httpContextAccessor; + this.mediaService = mediaService; + this.config = config; + this.db = db; + } + + [HttpGet("{mediaId}")] + public IActionResult Fetch([FromRoute] Guid mediaId) { + var media = db.Media + .Include(m => m.CurrentUploadedFile) + .First(m => m.Guid == mediaId); + if(media is null) + return NotFound(); + + // Check if the requested media item is a HEIC image and if it is, convert it + // otherwise, return the original file content, unaltered + if(media.CurrentUploadedFile!.MimeType == "image/heic") { + // If the media needs to be converted, check the HTTP request for allowed + // media formats, and convert to the best available format or WebP otherwise + var allowedTypes = httpContextAccessor + .HttpContext? + .Request + .GetTypedHeaders().Accept.Select(h => h.MediaType.ToString()) ?? Array.Empty(); + + var format = FormatPriority.FirstOrDefault(f => allowedTypes.Contains(f)) ?? "image/webp"; + + var fs = mediaService.GetConverted(media, format); + + return new FileStreamResult(fs, format); + } else { + var fs = System.IO.File.OpenRead(mediaService.GetPath(media)); + return new FileStreamResult(fs, media.CurrentUploadedFile!.MimeType); + } + } + + [HttpGet("thumb/{mediaId}")] + public IActionResult Thumbnail( + [FromRoute] Guid mediaId, + [FromQuery(Name = "w")] int? width, + [FromQuery(Name = "h")] int? height) { + + try { + var thumb = mediaService.GetThumbnail(mediaId, width, height); + return new FileStreamResult(thumb, "image/jpeg"); + } catch(ThumbnailException e) { + return BadRequest(e.Message); + } catch(ObjectNotFoundException e) { + return NotFound(e.Message); + } + } + + [HttpDelete("{mediaId}")] + public void Delete([FromRoute] Guid mediaId) { + mediaService.Delete(mediaId); + } + + [HttpPost] + public IActionResult Upload() { + if(Request.Form.Files.Count == 0) + return BadRequest("No files"); + + Media media = new(); + + foreach(var formFile in Request.Form.Files) { + try { + // Parse timestamps from headers + DateTime? lastAccessTime = + formFile.Headers["X-HyperBooru-LastAccessTime"] + .ElementAtOrDefault(0)? + .TryParseDateTimeUtc(); + DateTime? lastWriteTime = + formFile.Headers["X-HyperBooru-LastWriteTime"] + .ElementAtOrDefault(0)? + .TryParseDateTimeUtc(); + DateTime? createTime = + formFile.Headers["X-HyperBooru-CreateTime"] + .ElementAtOrDefault(0)? + .TryParseDateTimeUtc(); + + // Parse original path from headers + string? path = + formFile.Headers["X-HyperBooru-Path"] + .ElementAtOrDefault(0); + + object? pathType = null; + string? pathTypeString = + formFile.Headers["X-HyperBooru-PathType"] + .ElementAtOrDefault(0); + Enum.TryParse(typeof(PathType), pathTypeString, true, out pathType); + + // Parse tag IDs from headers + Guid[]? tagIds = formFile.Headers["X-HyperBooru-Tags"] + .ElementAtOrDefault(0)? + .Split(',') + .Select(t => Guid.Parse(t)) + .ToArray(); + + media = mediaService.Create( + formFile.OpenReadStream(), + formFile.FileName, + formFile.Headers["X-HyperBooru-Checksum"] + .ElementAtOrDefault(0), + lastAccessTime, + lastWriteTime, + createTime, + path, + (PathType?) pathType, + tagIds); + + // Return the GUID of the new media object if requested + bool returnMetadataParsed = bool.TryParse( + formFile.Headers["X-HyperBooru-ReturnMediaId"], out var returnMetadata); + + if(returnMetadataParsed && returnMetadata) + return Content(media.Guid.ToString()); + } catch(MediaCreateException e) { + return BadRequest(e.Message); + } + } + + if(Request.Form.Files.Count == 1) + return Redirect($"/ViewMedia?m={media.Guid}"); + else + return Redirect($"/Gallery"); + } +} \ No newline at end of file diff --git a/Server/Dockerfile b/Server/Dockerfile new file mode 100644 index 0000000..7769bf4 --- /dev/null +++ b/Server/Dockerfile @@ -0,0 +1,16 @@ +FROM mcr.microsoft.com/dotnet/sdk:10.0@sha256:f061e5a7532b36fa1d1b684857fe1f504ba92115b9934f154643266613c44c62 AS build +WORKDIR /App/Server + +COPY Server /App/Server +COPY ApiModels /App/ApiModels +RUN dotnet restore +RUN dotnet publish -o out + +FROM mcr.microsoft.com/dotnet/aspnet:10.0@sha256:ccdca44cd4f256d50187f920dc8ccc2a9ea7a8a4597ac1d51e08fddb2e3b3205 +RUN apt update +RUN apt install -y imagemagick tesseract-ocr tesseract-ocr-eng +RUN apt clean +RUN rm -rf /var/lib/apt/lists/* +WORKDIR /App +COPY --from=build /App/Server/out . +ENTRYPOINT [ "dotnet", "HyperBooru.dll" ] diff --git a/Server/ExceptionMiddleware.cs b/Server/ExceptionMiddleware.cs new file mode 100644 index 0000000..29d0e10 --- /dev/null +++ b/Server/ExceptionMiddleware.cs @@ -0,0 +1,64 @@ +using HyperBooru.ApiModels; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; + +namespace HyperBooru; + +// Middleware class to intercept API controller exceptions and +// return said exceptions to API clients as serialized JSON objects +public sealed class ExceptionMiddleware { + private RequestDelegate next; + + public ExceptionMiddleware(RequestDelegate next) => + this.next = next; + + public async Task Invoke(HttpContext context) { + try { + await next(context); + } catch(HBException e) { + context.Response.ContentType = "application/json"; + context.Response.StatusCode = + e.GetType().GetCustomAttribute()?.StatusCode ?? + StatusCodes.Status500InternalServerError; + + await context.Response.WriteAsJsonAsync(e); + + var x = 1; + } catch(Exception) { + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + context.Response.ContentType = "application/json"; + + context.Response.Clear(); + + await context.Response.WriteAsync(string.Empty); + } + } +} + +// This class is needed as the JSON serializer often fails to serialize +// members of the native 'Exception' class +public sealed class ExceptionJsonResolver : DefaultJsonTypeInfoResolver { + public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options) { + var info = base.GetTypeInfo(type, options); + + if(!typeof(Exception).IsAssignableFrom(type)) + return info; + + string[] excludedProps = [ + "data", + "hResult", + "helpLink", + "innerException", + "source", + "stackTrace", + "targetSite" + ]; + + foreach(var p in info.Properties.Where(p => excludedProps.Contains(p.Name))) + p.ShouldSerialize = (_, _) => false; + + return info; + } +} diff --git a/Server/HBContext.cs b/Server/HBContext.cs new file mode 100644 index 0000000..b684a51 --- /dev/null +++ b/Server/HBContext.cs @@ -0,0 +1,84 @@ +using HyperBooru.Services; +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru; + +enum HBObjectId { + NsfwTag = -1, + IngestTag = -2, + AdminUser = -3 +} + +public class HBContext : DbContext { + public static readonly Guid NsfwTag = new("EBDAD4F8-455A-4351-8017-1D4854D6FA38"); + public static readonly Guid IngestTag = new("EA212801-5BCC-4C0E-814F-FB9D30DB58BC"); + public static readonly Guid AdminUser = new("4FA948F4-7C45-4F81-BB6B-E417491E6C96"); + + public DbSet Objects { get; set; } + public DbSet Users { get; set; } + public DbSet TagDefinitions { get; set; } + public DbSet Tags { get; set; } + public DbSet Media { get; set; } + public DbSet UploadedFiles { get; set; } + public DbSet OcrData { get; set; } + + private IConfigService config; + + public HBContext(DbContextOptions options, IConfigService config) : base(options) => + this.config = config; + + protected override void OnConfiguring(DbContextOptionsBuilder options) { + options.UseNpgsql(config.DbConnectionString); + + #if DEBUG + options.EnableSensitiveDataLogging(); + #endif + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) { + // Don't use shared tables for inherited types + modelBuilder.Entity().ToTable("Objects"); + modelBuilder.Entity().ToTable("TagDefinitions"); + modelBuilder.Entity().ToTable("Tags"); + modelBuilder.Entity().ToTable("Media"); + modelBuilder.Entity().ToTable("UploadedFiles"); + + // Seed internal tag definitions + // These should NEVER change + modelBuilder.Entity().HasData(new TagDefinition[] { + new() { + ObjectId = (int) HBObjectId.NsfwTag, + Guid = NsfwTag, + Source = TagSource.Internal, + Name = "nsfw" + }, + new() { + ObjectId = (int) HBObjectId.IngestTag, + Guid = IngestTag, + Source = TagSource.Internal, + Name = "ingest" + } + }); + + // Seed initial admin user + modelBuilder.Entity().HasData(new User[] { + new() { + ObjectId = (int) HBObjectId.AdminUser, + Guid = AdminUser, + Username = "admin", + PasswordHash = UserService.HashPassword("admin") + } + }); + + // Some complex relationships cannot be inferred and require + // additional configuration, as seen below. + modelBuilder.Entity() + .HasMany(e => e.ImplicitTags) + .WithMany(); + + modelBuilder.Entity() + .HasOne(m => m.CurrentUploadedFile) + .WithOne() + .HasForeignKey("CurrentUploadedFileId"); + } +} \ No newline at end of file diff --git a/Server/HBObject.cs b/Server/HBObject.cs new file mode 100644 index 0000000..8001ea3 --- /dev/null +++ b/Server/HBObject.cs @@ -0,0 +1,14 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace HyperBooru; + +[Index(nameof(Guid))] +public class HBObject { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int ObjectId { get; set; } + public Guid Guid { get; set; } = Guid.NewGuid(); + public virtual List Tags { get; set; } = new(); +} \ No newline at end of file diff --git a/Server/LICENSE.txt b/Server/LICENSE.txt new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/Server/LICENSE.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/Server/Media.cs b/Server/Media.cs new file mode 100644 index 0000000..2ff9e63 --- /dev/null +++ b/Server/Media.cs @@ -0,0 +1,92 @@ +using HyperBooru.ApiModels; +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace HyperBooru; + +public class Media : HBObject { + public string? ShortDescription { get; set; } + public string? LongDescription { get; set; } + public virtual OcrData? OcrData { get; set; } + public virtual UploadedFile? CurrentUploadedFile { get; set; } + public virtual List UploadedFiles { get; set; } = new(); + + public bool IsIngest => Tags + .Select(t => t.TagDefinitionId) + .Contains((int) HBObjectId.IngestTag); + + public string? DisplayName { + get { + if(ShortDescription is not null) + return ShortDescription; + + return UploadedFiles + .OrderBy(f => f.UploadTime) + .First()?.Filename ?? Guid.ToString().ToUpper(); + } + } + + public static explicit operator ApiModels.Media(Media media) => + new() { + MediaId = media.Guid, + ShortDescription = media.ShortDescription, + LongDescription = media.LongDescription + }; +} + +public class UploadedFile : HBObject { + public string Checksum { get; set; } + public bool ChecksumVerified { get; set; } = false; + public string? Filename { get; set; } + public long Length { get; set; } + public string MimeType { get; set; } + public int? Width { get; set; } + public int? Height { get; set; } + public DateTime UploadTime { get; set; } = DateTime.UtcNow; + public DateTime? LastAccessTime { get; set; } + public DateTime? LastWriteTime { get; set; } + public DateTime? CreateTime { get; set; } + public string? Path { get; set; } + public PathType? PathType { get; set; } + public virtual Media Media { get; set; } + + public static explicit operator ApiModels.UploadedFile(UploadedFile uploadedFile) => + new() { + MediaId = uploadedFile.Media.Guid, + UploadedFileId = uploadedFile.Guid, + Checksum = uploadedFile.Checksum, + ChecksumVerified = uploadedFile.ChecksumVerified, + Filename = uploadedFile.Filename, + Length = uploadedFile.Length, + MimeType = uploadedFile.MimeType, + Width = uploadedFile.Width, + Height = uploadedFile.Height, + UploadTime = uploadedFile.UploadTime, + LastAccessTime = uploadedFile.LastAccessTime, + LastWriteTime = uploadedFile.LastWriteTime, + CreateTime = uploadedFile.CreateTime, + Path = uploadedFile.Path, + PathType = (ApiModels.PathType?) uploadedFile.PathType + }; +} + +public class OcrData { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int OcrDataId { get; set; } + [ForeignKey("ObjectId")] + public int MediaId { get; set; } + public string Text { get; set; } + public string SearchableText { get; set; } + public DateTime Timestamp { get; set; } + public virtual Media Media { get; set; } + + public static explicit operator ApiModels.OcrData(OcrData ocrData) => + new() { + MediaId = ocrData.Media.Guid, + Text = ocrData.Text, + SearchableText = ocrData.SearchableText, + Timestamp = ocrData.Timestamp + }; +} \ No newline at end of file diff --git a/Server/Migrations/20260131125650_InitialMigration.Designer.cs b/Server/Migrations/20260131125650_InitialMigration.Designer.cs new file mode 100644 index 0000000..2e4a05e --- /dev/null +++ b/Server/Migrations/20260131125650_InitialMigration.Designer.cs @@ -0,0 +1,362 @@ +// +using System; +using HyperBooru; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace HyperBooru.Migrations +{ + [DbContext(typeof(HBContext))] + [Migration("20260131125650_InitialMigration")] + partial class InitialMigration + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.23") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("HyperBooru.HBObject", b => + { + b.Property("ObjectId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("ObjectId")); + + b.Property("Guid") + .HasColumnType("uuid"); + + b.HasKey("ObjectId"); + + b.HasIndex("Guid"); + + b.ToTable("Objects", (string)null); + + b.UseTptMappingStrategy(); + }); + + modelBuilder.Entity("HyperBooru.OcrData", b => + { + b.Property("OcrDataId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("OcrDataId")); + + b.Property("MediaId") + .HasColumnType("integer"); + + b.Property("SearchableText") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.HasKey("OcrDataId"); + + b.HasIndex("MediaId") + .IsUnique(); + + b.ToTable("OcrData"); + }); + + modelBuilder.Entity("TagDefinitionTagDefinition", b => + { + b.Property("ImplicitTagsObjectId") + .HasColumnType("integer"); + + b.Property("TagDefinitionObjectId") + .HasColumnType("integer"); + + b.HasKey("ImplicitTagsObjectId", "TagDefinitionObjectId"); + + b.HasIndex("TagDefinitionObjectId"); + + b.ToTable("TagDefinitionTagDefinition"); + }); + + modelBuilder.Entity("HyperBooru.Media", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property("CurrentUploadedFileId") + .HasColumnType("integer"); + + b.Property("LongDescription") + .HasColumnType("text"); + + b.Property("ShortDescription") + .HasColumnType("text"); + + b.HasIndex("CurrentUploadedFileId") + .IsUnique(); + + b.ToTable("Media", (string)null); + }); + + modelBuilder.Entity("HyperBooru.Tag", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property("CreateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("TagDefinitionId") + .HasColumnType("integer"); + + b.Property("TargetObjectId") + .HasColumnType("integer"); + + b.HasIndex("TagDefinitionId"); + + b.HasIndex("TargetObjectId"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("HyperBooru.TagDefinition", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property("Alias") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Namespace") + .HasColumnType("text"); + + b.Property("Source") + .HasColumnType("integer"); + + b.ToTable("TagDefinitions", (string)null); + + b.HasData( + new + { + ObjectId = -1, + Guid = new Guid("ebdad4f8-455a-4351-8017-1d4854d6fa38"), + Name = "nsfw", + Source = 0 + }, + new + { + ObjectId = -2, + Guid = new Guid("ea212801-5bcc-4c0e-814f-fb9d30db58bc"), + Name = "ingest", + Source = 0 + }); + }); + + modelBuilder.Entity("HyperBooru.UploadedFile", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property("Checksum") + .IsRequired() + .HasColumnType("text"); + + b.Property("ChecksumVerified") + .HasColumnType("boolean"); + + b.Property("CreateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Filename") + .HasColumnType("text"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("LastAccessTime") + .HasColumnType("timestamp with time zone"); + + b.Property("LastWriteTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Length") + .HasColumnType("bigint"); + + b.Property("MediaObjectId") + .HasColumnType("integer"); + + b.Property("MimeType") + .IsRequired() + .HasColumnType("text"); + + b.Property("Path") + .HasColumnType("text"); + + b.Property("PathType") + .HasColumnType("integer"); + + b.Property("UploadTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasIndex("MediaObjectId"); + + b.ToTable("UploadedFiles", (string)null); + }); + + modelBuilder.Entity("HyperBooru.User", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasIndex("Username"); + + b.ToTable("Users"); + + b.HasData( + new + { + ObjectId = -3, + Guid = new Guid("4fa948f4-7c45-4f81-bb6b-e417491e6c96"), + PasswordHash = "P4geAuE2yX/PDRHuJSq74FF5vO782rWz5c0LAQPR8m45DEYAONhu1wYnAn60PSNyjocqEBdnCeKCJfK3sKyuWw==", + Username = "admin" + }); + }); + + modelBuilder.Entity("HyperBooru.OcrData", b => + { + b.HasOne("HyperBooru.Media", "Media") + .WithOne("OcrData") + .HasForeignKey("HyperBooru.OcrData", "MediaId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Media"); + }); + + modelBuilder.Entity("TagDefinitionTagDefinition", b => + { + b.HasOne("HyperBooru.TagDefinition", null) + .WithMany() + .HasForeignKey("ImplicitTagsObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("HyperBooru.TagDefinition", null) + .WithMany() + .HasForeignKey("TagDefinitionObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("HyperBooru.Media", b => + { + b.HasOne("HyperBooru.UploadedFile", "CurrentUploadedFile") + .WithOne() + .HasForeignKey("HyperBooru.Media", "CurrentUploadedFileId"); + + b.HasOne("HyperBooru.HBObject", null) + .WithOne() + .HasForeignKey("HyperBooru.Media", "ObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CurrentUploadedFile"); + }); + + modelBuilder.Entity("HyperBooru.Tag", b => + { + b.HasOne("HyperBooru.HBObject", null) + .WithOne() + .HasForeignKey("HyperBooru.Tag", "ObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("HyperBooru.TagDefinition", "TagDefinition") + .WithMany() + .HasForeignKey("TagDefinitionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("HyperBooru.HBObject", "Target") + .WithMany("Tags") + .HasForeignKey("TargetObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("TagDefinition"); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("HyperBooru.TagDefinition", b => + { + b.HasOne("HyperBooru.HBObject", null) + .WithOne() + .HasForeignKey("HyperBooru.TagDefinition", "ObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("HyperBooru.UploadedFile", b => + { + b.HasOne("HyperBooru.Media", "Media") + .WithMany("UploadedFiles") + .HasForeignKey("MediaObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("HyperBooru.HBObject", null) + .WithOne() + .HasForeignKey("HyperBooru.UploadedFile", "ObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Media"); + }); + + modelBuilder.Entity("HyperBooru.User", b => + { + b.HasOne("HyperBooru.HBObject", null) + .WithOne() + .HasForeignKey("HyperBooru.User", "ObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("HyperBooru.HBObject", b => + { + b.Navigation("Tags"); + }); + + modelBuilder.Entity("HyperBooru.Media", b => + { + b.Navigation("OcrData"); + + b.Navigation("UploadedFiles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Server/Migrations/20260131125650_InitialMigration.cs b/Server/Migrations/20260131125650_InitialMigration.cs new file mode 100644 index 0000000..a1a7d8f --- /dev/null +++ b/Server/Migrations/20260131125650_InitialMigration.cs @@ -0,0 +1,319 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional + +namespace HyperBooru.Migrations +{ + /// + public partial class InitialMigration : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Objects", + columns: table => new + { + ObjectId = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Guid = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Objects", x => x.ObjectId); + }); + + migrationBuilder.CreateTable( + name: "TagDefinitions", + columns: table => new + { + ObjectId = table.Column(type: "integer", nullable: false), + Source = table.Column(type: "integer", nullable: false), + Namespace = table.Column(type: "text", nullable: true), + Name = table.Column(type: "text", nullable: false), + Alias = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_TagDefinitions", x => x.ObjectId); + table.ForeignKey( + name: "FK_TagDefinitions_Objects_ObjectId", + column: x => x.ObjectId, + principalTable: "Objects", + principalColumn: "ObjectId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + ObjectId = table.Column(type: "integer", nullable: false), + Username = table.Column(type: "text", nullable: false), + PasswordHash = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.ObjectId); + table.ForeignKey( + name: "FK_Users_Objects_ObjectId", + column: x => x.ObjectId, + principalTable: "Objects", + principalColumn: "ObjectId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "TagDefinitionTagDefinition", + columns: table => new + { + ImplicitTagsObjectId = table.Column(type: "integer", nullable: false), + TagDefinitionObjectId = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_TagDefinitionTagDefinition", x => new { x.ImplicitTagsObjectId, x.TagDefinitionObjectId }); + table.ForeignKey( + name: "FK_TagDefinitionTagDefinition_TagDefinitions_ImplicitTagsObjec~", + column: x => x.ImplicitTagsObjectId, + principalTable: "TagDefinitions", + principalColumn: "ObjectId", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_TagDefinitionTagDefinition_TagDefinitions_TagDefinitionObje~", + column: x => x.TagDefinitionObjectId, + principalTable: "TagDefinitions", + principalColumn: "ObjectId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Tags", + columns: table => new + { + ObjectId = table.Column(type: "integer", nullable: false), + TagDefinitionId = table.Column(type: "integer", nullable: false), + CreateTime = table.Column(type: "timestamp with time zone", nullable: false), + TargetObjectId = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Tags", x => x.ObjectId); + table.ForeignKey( + name: "FK_Tags_Objects_ObjectId", + column: x => x.ObjectId, + principalTable: "Objects", + principalColumn: "ObjectId", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Tags_Objects_TargetObjectId", + column: x => x.TargetObjectId, + principalTable: "Objects", + principalColumn: "ObjectId", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Tags_TagDefinitions_TagDefinitionId", + column: x => x.TagDefinitionId, + principalTable: "TagDefinitions", + principalColumn: "ObjectId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Media", + columns: table => new + { + ObjectId = table.Column(type: "integer", nullable: false), + ShortDescription = table.Column(type: "text", nullable: true), + LongDescription = table.Column(type: "text", nullable: true), + CurrentUploadedFileId = table.Column(type: "integer", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Media", x => x.ObjectId); + table.ForeignKey( + name: "FK_Media_Objects_ObjectId", + column: x => x.ObjectId, + principalTable: "Objects", + principalColumn: "ObjectId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OcrData", + columns: table => new + { + OcrDataId = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + MediaId = table.Column(type: "integer", nullable: false), + Text = table.Column(type: "text", nullable: false), + SearchableText = table.Column(type: "text", nullable: false), + Timestamp = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OcrData", x => x.OcrDataId); + table.ForeignKey( + name: "FK_OcrData_Media_MediaId", + column: x => x.MediaId, + principalTable: "Media", + principalColumn: "ObjectId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "UploadedFiles", + columns: table => new + { + ObjectId = table.Column(type: "integer", nullable: false), + Checksum = table.Column(type: "text", nullable: false), + ChecksumVerified = table.Column(type: "boolean", nullable: false), + Filename = table.Column(type: "text", nullable: true), + Length = table.Column(type: "bigint", nullable: false), + MimeType = table.Column(type: "text", nullable: false), + Width = table.Column(type: "integer", nullable: true), + Height = table.Column(type: "integer", nullable: true), + UploadTime = table.Column(type: "timestamp with time zone", nullable: false), + LastAccessTime = table.Column(type: "timestamp with time zone", nullable: true), + LastWriteTime = table.Column(type: "timestamp with time zone", nullable: true), + CreateTime = table.Column(type: "timestamp with time zone", nullable: true), + Path = table.Column(type: "text", nullable: true), + PathType = table.Column(type: "integer", nullable: true), + MediaObjectId = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_UploadedFiles", x => x.ObjectId); + table.ForeignKey( + name: "FK_UploadedFiles_Media_MediaObjectId", + column: x => x.MediaObjectId, + principalTable: "Media", + principalColumn: "ObjectId", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UploadedFiles_Objects_ObjectId", + column: x => x.ObjectId, + principalTable: "Objects", + principalColumn: "ObjectId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.InsertData( + table: "Objects", + columns: new[] { "ObjectId", "Guid" }, + values: new object[,] + { + { -3, new Guid("4fa948f4-7c45-4f81-bb6b-e417491e6c96") }, + { -2, new Guid("ea212801-5bcc-4c0e-814f-fb9d30db58bc") }, + { -1, new Guid("ebdad4f8-455a-4351-8017-1d4854d6fa38") } + }); + + migrationBuilder.InsertData( + table: "TagDefinitions", + columns: new[] { "ObjectId", "Alias", "Name", "Namespace", "Source" }, + values: new object[,] + { + { -2, null, "ingest", null, 0 }, + { -1, null, "nsfw", null, 0 } + }); + + migrationBuilder.InsertData( + table: "Users", + columns: new[] { "ObjectId", "PasswordHash", "Username" }, + values: new object[] { -3, "P4geAuE2yX/PDRHuJSq74FF5vO782rWz5c0LAQPR8m45DEYAONhu1wYnAn60PSNyjocqEBdnCeKCJfK3sKyuWw==", "admin" }); + + migrationBuilder.CreateIndex( + name: "IX_Media_CurrentUploadedFileId", + table: "Media", + column: "CurrentUploadedFileId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Objects_Guid", + table: "Objects", + column: "Guid"); + + migrationBuilder.CreateIndex( + name: "IX_OcrData_MediaId", + table: "OcrData", + column: "MediaId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_TagDefinitionTagDefinition_TagDefinitionObjectId", + table: "TagDefinitionTagDefinition", + column: "TagDefinitionObjectId"); + + migrationBuilder.CreateIndex( + name: "IX_Tags_TagDefinitionId", + table: "Tags", + column: "TagDefinitionId"); + + migrationBuilder.CreateIndex( + name: "IX_Tags_TargetObjectId", + table: "Tags", + column: "TargetObjectId"); + + migrationBuilder.CreateIndex( + name: "IX_UploadedFiles_MediaObjectId", + table: "UploadedFiles", + column: "MediaObjectId"); + + migrationBuilder.CreateIndex( + name: "IX_Users_Username", + table: "Users", + column: "Username"); + + migrationBuilder.AddForeignKey( + name: "FK_Media_UploadedFiles_CurrentUploadedFileId", + table: "Media", + column: "CurrentUploadedFileId", + principalTable: "UploadedFiles", + principalColumn: "ObjectId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Media_Objects_ObjectId", + table: "Media"); + + migrationBuilder.DropForeignKey( + name: "FK_UploadedFiles_Objects_ObjectId", + table: "UploadedFiles"); + + migrationBuilder.DropForeignKey( + name: "FK_Media_UploadedFiles_CurrentUploadedFileId", + table: "Media"); + + migrationBuilder.DropTable( + name: "OcrData"); + + migrationBuilder.DropTable( + name: "TagDefinitionTagDefinition"); + + migrationBuilder.DropTable( + name: "Tags"); + + migrationBuilder.DropTable( + name: "Users"); + + migrationBuilder.DropTable( + name: "TagDefinitions"); + + migrationBuilder.DropTable( + name: "Objects"); + + migrationBuilder.DropTable( + name: "UploadedFiles"); + + migrationBuilder.DropTable( + name: "Media"); + } + } +} diff --git a/Server/Migrations/HBContextModelSnapshot.cs b/Server/Migrations/HBContextModelSnapshot.cs new file mode 100644 index 0000000..422037f --- /dev/null +++ b/Server/Migrations/HBContextModelSnapshot.cs @@ -0,0 +1,359 @@ +// +using System; +using HyperBooru; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace HyperBooru.Migrations +{ + [DbContext(typeof(HBContext))] + partial class HBContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.23") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("HyperBooru.HBObject", b => + { + b.Property("ObjectId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("ObjectId")); + + b.Property("Guid") + .HasColumnType("uuid"); + + b.HasKey("ObjectId"); + + b.HasIndex("Guid"); + + b.ToTable("Objects", (string)null); + + b.UseTptMappingStrategy(); + }); + + modelBuilder.Entity("HyperBooru.OcrData", b => + { + b.Property("OcrDataId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("OcrDataId")); + + b.Property("MediaId") + .HasColumnType("integer"); + + b.Property("SearchableText") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.HasKey("OcrDataId"); + + b.HasIndex("MediaId") + .IsUnique(); + + b.ToTable("OcrData"); + }); + + modelBuilder.Entity("TagDefinitionTagDefinition", b => + { + b.Property("ImplicitTagsObjectId") + .HasColumnType("integer"); + + b.Property("TagDefinitionObjectId") + .HasColumnType("integer"); + + b.HasKey("ImplicitTagsObjectId", "TagDefinitionObjectId"); + + b.HasIndex("TagDefinitionObjectId"); + + b.ToTable("TagDefinitionTagDefinition"); + }); + + modelBuilder.Entity("HyperBooru.Media", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property("CurrentUploadedFileId") + .HasColumnType("integer"); + + b.Property("LongDescription") + .HasColumnType("text"); + + b.Property("ShortDescription") + .HasColumnType("text"); + + b.HasIndex("CurrentUploadedFileId") + .IsUnique(); + + b.ToTable("Media", (string)null); + }); + + modelBuilder.Entity("HyperBooru.Tag", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property("CreateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("TagDefinitionId") + .HasColumnType("integer"); + + b.Property("TargetObjectId") + .HasColumnType("integer"); + + b.HasIndex("TagDefinitionId"); + + b.HasIndex("TargetObjectId"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("HyperBooru.TagDefinition", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property("Alias") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Namespace") + .HasColumnType("text"); + + b.Property("Source") + .HasColumnType("integer"); + + b.ToTable("TagDefinitions", (string)null); + + b.HasData( + new + { + ObjectId = -1, + Guid = new Guid("ebdad4f8-455a-4351-8017-1d4854d6fa38"), + Name = "nsfw", + Source = 0 + }, + new + { + ObjectId = -2, + Guid = new Guid("ea212801-5bcc-4c0e-814f-fb9d30db58bc"), + Name = "ingest", + Source = 0 + }); + }); + + modelBuilder.Entity("HyperBooru.UploadedFile", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property("Checksum") + .IsRequired() + .HasColumnType("text"); + + b.Property("ChecksumVerified") + .HasColumnType("boolean"); + + b.Property("CreateTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Filename") + .HasColumnType("text"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("LastAccessTime") + .HasColumnType("timestamp with time zone"); + + b.Property("LastWriteTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Length") + .HasColumnType("bigint"); + + b.Property("MediaObjectId") + .HasColumnType("integer"); + + b.Property("MimeType") + .IsRequired() + .HasColumnType("text"); + + b.Property("Path") + .HasColumnType("text"); + + b.Property("PathType") + .HasColumnType("integer"); + + b.Property("UploadTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasIndex("MediaObjectId"); + + b.ToTable("UploadedFiles", (string)null); + }); + + modelBuilder.Entity("HyperBooru.User", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasIndex("Username"); + + b.ToTable("Users"); + + b.HasData( + new + { + ObjectId = -3, + Guid = new Guid("4fa948f4-7c45-4f81-bb6b-e417491e6c96"), + PasswordHash = "P4geAuE2yX/PDRHuJSq74FF5vO782rWz5c0LAQPR8m45DEYAONhu1wYnAn60PSNyjocqEBdnCeKCJfK3sKyuWw==", + Username = "admin" + }); + }); + + modelBuilder.Entity("HyperBooru.OcrData", b => + { + b.HasOne("HyperBooru.Media", "Media") + .WithOne("OcrData") + .HasForeignKey("HyperBooru.OcrData", "MediaId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Media"); + }); + + modelBuilder.Entity("TagDefinitionTagDefinition", b => + { + b.HasOne("HyperBooru.TagDefinition", null) + .WithMany() + .HasForeignKey("ImplicitTagsObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("HyperBooru.TagDefinition", null) + .WithMany() + .HasForeignKey("TagDefinitionObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("HyperBooru.Media", b => + { + b.HasOne("HyperBooru.UploadedFile", "CurrentUploadedFile") + .WithOne() + .HasForeignKey("HyperBooru.Media", "CurrentUploadedFileId"); + + b.HasOne("HyperBooru.HBObject", null) + .WithOne() + .HasForeignKey("HyperBooru.Media", "ObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CurrentUploadedFile"); + }); + + modelBuilder.Entity("HyperBooru.Tag", b => + { + b.HasOne("HyperBooru.HBObject", null) + .WithOne() + .HasForeignKey("HyperBooru.Tag", "ObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("HyperBooru.TagDefinition", "TagDefinition") + .WithMany() + .HasForeignKey("TagDefinitionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("HyperBooru.HBObject", "Target") + .WithMany("Tags") + .HasForeignKey("TargetObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("TagDefinition"); + + b.Navigation("Target"); + }); + + modelBuilder.Entity("HyperBooru.TagDefinition", b => + { + b.HasOne("HyperBooru.HBObject", null) + .WithOne() + .HasForeignKey("HyperBooru.TagDefinition", "ObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("HyperBooru.UploadedFile", b => + { + b.HasOne("HyperBooru.Media", "Media") + .WithMany("UploadedFiles") + .HasForeignKey("MediaObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("HyperBooru.HBObject", null) + .WithOne() + .HasForeignKey("HyperBooru.UploadedFile", "ObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Media"); + }); + + modelBuilder.Entity("HyperBooru.User", b => + { + b.HasOne("HyperBooru.HBObject", null) + .WithOne() + .HasForeignKey("HyperBooru.User", "ObjectId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("HyperBooru.HBObject", b => + { + b.Navigation("Tags"); + }); + + modelBuilder.Entity("HyperBooru.Media", b => + { + b.Navigation("OcrData"); + + b.Navigation("UploadedFiles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Server/Program.cs b/Server/Program.cs new file mode 100644 index 0000000..687c6f8 --- /dev/null +++ b/Server/Program.cs @@ -0,0 +1,73 @@ +using HyperBooru.ApiClient; +using HyperBooru.Server.Components; +using HyperBooru.Services; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.EntityFrameworkCore; +using System.Text.Json.Serialization; + +namespace HyperBooru.Server; + +public class Program { + public static void Main(string[] args) { + var builder = WebApplication.CreateBuilder(args); + + // Add services to the container. + builder.Services.AddHttpContextAccessor(); + builder.Services.AddControllers().AddJsonOptions(o => { + var converter = new JsonStringEnumConverter(); + o.JsonSerializerOptions.Converters.Add(converter); + }); + builder.Services.AddRazorComponents() + .AddInteractiveWebAssemblyComponents(); + + // Add our custom services + builder.Services.AddSingleton(); + builder.Services.AddDbContextFactory(); + builder.Services.AddSingleton(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddHostedService(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(sp => new HBSession() { + BaseUri = new("https://127.0.0.1:7084") + }); + + // Ensure session keys are stored in a persistent location on all platforms + builder.Services.AddDataProtection() + .PersistKeysToFileSystem(new( + builder.Services.BuildServiceProvider() + .GetRequiredService() + .KeyPath)); + + var app = builder.Build(); + + // Ensure database is created and it's schema is up to date + using var scope = app.Services.CreateScope(); + using var db = scope.ServiceProvider.GetRequiredService(); + db.Database.Migrate(); + + // Configure the HTTP request pipeline. + if(app.Environment.IsDevelopment()) { + app.UseWebAssemblyDebugging(); + } else { + app.UseExceptionHandler("/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); + } + + app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true); + app.UseHttpsRedirection(); + + app.UseAntiforgery(); + + app.MapStaticAssets(); + app.MapControllers(); + app.MapRazorComponents() + .AddInteractiveWebAssemblyRenderMode() + .AddAdditionalAssemblies(typeof(Client._Imports).Assembly); + + app.Run(); + } +} diff --git a/Server/Properties/launchSettings.json b/Server/Properties/launchSettings.json new file mode 100644 index 0000000..f37fc08 --- /dev/null +++ b/Server/Properties/launchSettings.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", + "applicationUrl": "http://localhost:5062", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", + "applicationUrl": "https://localhost:7084;http://localhost:5062", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } + } diff --git a/Server/Server.csproj b/Server/Server.csproj new file mode 100644 index 0000000..829efa4 --- /dev/null +++ b/Server/Server.csproj @@ -0,0 +1,34 @@ + + + + net10.0 + enable + enable + true + HyperBooru.Server + HyperBooru.Server + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + diff --git a/Server/Services/ConfigService.cs b/Server/Services/ConfigService.cs new file mode 100644 index 0000000..ac1f155 --- /dev/null +++ b/Server/Services/ConfigService.cs @@ -0,0 +1,72 @@ +using HyperBooru.ApiModels; + +namespace HyperBooru.Services; + +public interface IConfigService { + public string DataPath { get; } + public string KeyPath { get; } + public string DbConnectionString { get; } + public string MediaBasePath { get; } + public string ThumbnailBasePath { get; } + public string ConvertedMediaBasePath { get; } + public bool EnableOcr { get; } +} + +public class ConfigService : IConfigService { + private IConfiguration config; + + private const string AppName = "HyperBooru"; + + public string DataPath { + get { + #if DEBUG + return "Data"; + #else + string? path = config["DataPath"]; + if(path is not null) + return path; + + switch(Environment.OSVersion.Platform) { + case PlatformID.Win32NT: + return Path.Join( + Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), + AppName); + case PlatformID.Unix: + return $"/var/lib/{AppName.ToLower()}"; + default: + throw new NotImplementedException( + $"Unknown Operating System: {Environment.OSVersion.Platform}"); + } + #endif + } + } + + public string KeyPath => + Path.Join(DataPath, "keys"); + + public string DbConnectionString => + config.GetConnectionString("DefaultConnection") ?? + throw new HBException("Unable to get default connection string"); + + public string MediaBasePath => + Path.Join(DataPath, "media"); + + public string ThumbnailBasePath => + Path.Join(DataPath, "thumb"); + + public string ConvertedMediaBasePath => + Path.Join(DataPath, "converted"); + + public bool EnableOcr => + bool.TryParse(config["DisableOcr"], out bool x) ? !x : true; + + public ConfigService(IConfiguration config) { + this.config = config; + InitDirectoryStructure(); + } + + private void InitDirectoryStructure() { + Directory.CreateDirectory(DataPath); + Directory.CreateDirectory(MediaBasePath); + } +} \ No newline at end of file diff --git a/Server/Services/FeedService.cs b/Server/Services/FeedService.cs new file mode 100644 index 0000000..3744e73 --- /dev/null +++ b/Server/Services/FeedService.cs @@ -0,0 +1,212 @@ +using HyperBooru.ApiModels; +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru.Services; + +public interface IFeedService { + public Media[] LoadChunk( + bool selectIngest, + bool includeNsfw, + Media? key = null, + int count = 50, + SortOrder sortOrder = SortOrder.ObjectId); + + public Media[] LoadChunk( + bool selectIngest, + bool includeNsfw, + string query, + Media? key = null, + int count = 50, + SortOrder sortOrder = SortOrder.ObjectId); + + public Media[] LoadChunk( + bool selectIngest, + bool includeNsfw, + Guid tagId, + Media? key = null, + int count = 50, + SortOrder sortOrder = SortOrder.ObjectId); + + public Media[] LoadChunk(FeedRequest feedRequest); +} + +public class FeedService : IFeedService { + private IDbContextFactory dbFactory; + + public FeedService(IDbContextFactory dbFactory) => + this.dbFactory = dbFactory; + + public Media[] LoadChunk( + bool selectIngest, + bool includeNsfw, + Media? continuationToken, + int count, + SortOrder sortOrder) => LoadChunkInternal( + selectIngest, includeNsfw, null, null, continuationToken?.Guid, count, sortOrder); + + public Media[] LoadChunk( + bool selectIngest, + bool includeNsfw, + string query, + Media? continuationToken, + int count, + SortOrder sortOrder) => LoadChunkInternal( + selectIngest, includeNsfw, query, null, continuationToken?.Guid, count, sortOrder); + + public Media[] LoadChunk( + bool selectIngest, + bool includeNsfw, + Guid tagId, + Media? continuationToken, + int count, + SortOrder sortOrder) => LoadChunkInternal( + selectIngest, includeNsfw, null, tagId, continuationToken?.Guid, count, sortOrder); + + public Media[] LoadChunk(FeedRequest feedRequest) { + switch(feedRequest) { + case FeedSearchRequest searchRequest: + return LoadChunkInternal( + selectIngest: searchRequest.SelectIngest, + includeNsfw: searchRequest.IncludeNsfw, + query: searchRequest.Query, + tagId: null, + continuationToken: searchRequest.ContinuationToken, + count: searchRequest.Count, + sortOrder: searchRequest.SortOrder); + case FeedTagRequest tagRequest: + return LoadChunkInternal( + selectIngest: tagRequest.SelectIngest, + includeNsfw: tagRequest.IncludeNsfw, + query: null, + tagId: tagRequest.TagId, + continuationToken: tagRequest.ContinuationToken, + count: tagRequest.Count, + sortOrder: tagRequest.SortOrder); + default: + return LoadChunkInternal( + selectIngest: feedRequest.SelectIngest, + includeNsfw: feedRequest.IncludeNsfw, + query: null, + tagId: null, + continuationToken: feedRequest.ContinuationToken, + count: feedRequest.Count, + sortOrder: feedRequest.SortOrder); + } + } + + private Media[] LoadChunkInternal( + bool selectIngest, + bool includeNsfw, + string? query, + Guid? tagId, + Guid? continuationToken, + int count, + SortOrder sortOrder) { + + if(selectIngest && !includeNsfw) + return Array.Empty(); + + using var db = dbFactory.CreateDbContext(); + + IQueryable media = db.Media + .AsSingleQuery() + .AsNoTracking() + .Include(m => m.Tags) + .Include(m => m.CurrentUploadedFile); + + if(!includeNsfw) + media = media + .Where(m => !TagsThatImply(db, HBContext.NsfwTag) + .Intersect(m.Tags.Select(t => t.TagDefinitionId)) + .Any()); + + if(selectIngest) { + media = media + .Where(m => m.Tags + .Select(t => t.TagDefinitionId) + .Contains((int) HBObjectId.IngestTag)); + } else { + media = media + .Where(m => !m.Tags + .Select(t => t.TagDefinitionId) + .Contains((int) HBObjectId.IngestTag)); + } + + if(query is not null) { + media = Search(media, query); + } else if(tagId is not null) { + media = media + .Where(m => TagsThatImply(db, (Guid) tagId) + .Intersect(m.Tags.Select(t => t.TagDefinitionId)) + .Any()); + } + + if(continuationToken is not null) + media = media + .Where(m => m.ObjectId > db.Media.First(m => m.Guid == continuationToken).ObjectId); + + switch(sortOrder) { + case SortOrder.ObjectId: + media = media.OrderBy(m => m.ObjectId); + break; + case SortOrder.LastWriteTime: + media = media.OrderBy(m => m.CurrentUploadedFile!.LastWriteTime); + break; + case SortOrder.Random: + media = media.OrderBy(m => EF.Functions.Random()); + break; + } + + return media + .Take(count) + .ToArray(); + } + + private static IQueryable Search(IQueryable media, string query) { + // TODO: search implicit tags as well + + query = query.ToLower().Trim(); + + return media + .Where(m => + (m.ShortDescription != null && m.ShortDescription.ToLower().Contains(query)) || + (m.LongDescription != null && m.LongDescription.ToLower().Contains(query)) || + (m.UploadedFiles.Any(uf => uf.Filename != null && uf.Filename.ToLower().Contains(query))) || + (m.OcrData != null && m.OcrData.SearchableText.ToLower().Contains(query)) || + (m.Tags.Any(t => t.TagDefinition.Name.ToLower().Contains(query)))); + } + + private static IQueryable TagsThatImply(HBContext db, Guid tagId) => + db.Database.SqlQueryRaw(""" + WITH RECURSIVE basetag AS ( + SELECT "ObjectId" FROM "Objects" WHERE "Guid" = {0} + ), + impliedtags AS ( + SELECT + "TagDefinitionObjectId" + FROM + "TagDefinitionTagDefinition" + INNER JOIN + basetag + ON + "ImplicitTagsObjectId" = basetag."ObjectId" + UNION + SELECT + "TagDefinitionTagDefinition"."TagDefinitionObjectId" + FROM + "TagDefinitionTagDefinition" + INNER JOIN + impliedtags + ON + impliedtags."TagDefinitionObjectId" = "TagDefinitionTagDefinition"."ImplicitTagsObjectId" + ) + SELECT DISTINCT + "TagDefinitionObjectId" AS "Value" + FROM impliedtags + UNION + SELECT + "ObjectId" AS "Value" + FROM + basetag + """, tagId); +} diff --git a/Server/Services/MediaService.cs b/Server/Services/MediaService.cs new file mode 100644 index 0000000..e497570 --- /dev/null +++ b/Server/Services/MediaService.cs @@ -0,0 +1,400 @@ +using HyperBooru.ApiModels; +using ImageMagick; +using Microsoft.EntityFrameworkCore; +using MimeDetective; +using MimeDetective.Definitions; +using System.Security.Cryptography; +using System.Text.RegularExpressions; + +namespace HyperBooru.Services; + +public interface IMediaService { + public void SetDescription( + Media media, + string? shortDescription, + string? longDescription); + + public void SetIngest(Media media, bool ingest); + + public Media Create( + Stream fileData, + string fileName, + string? checksum = null, + DateTime? lastAccessTime = null, + DateTime? lastWriteTime = null, + DateTime? createTime = null, + string? path = null, + PathType? pathType = null, + Guid[]? tagIds = null); + + public void Delete(Guid media); + public void Delete(Media media); + public void DeleteThumbnails(Guid media); + public void DeleteThumbnails(Media media); + public Stream GetThumbnail(Guid media, int? width, int? height); + public Stream GetThumbnail(Media media, int? width, int? height); + public Stream GetConverted(Guid mediaId, string mimeType = "image/png"); + public Stream GetConverted(Media media, string mimeType = "image/png"); + public string GetPath(Guid media); + public string GetPath(Media media); + +} + +public class MediaService : IMediaService { + private readonly Dictionary FormatMap = new() { + ["image/jpeg"] = MagickFormat.Jpeg, + ["image/jpg"] = MagickFormat.Jpg, + ["image/png"] = MagickFormat.Png, + ["image/webp"] = MagickFormat.WebP + }; + + private IDbContextFactory dbFactory; + private IConfigService config; + + private IContentInspector inspector; + + public MediaService(IDbContextFactory dbFactory, + IConfigService config) { + + this.dbFactory = dbFactory; + this.config = config; + + ContentInspectorBuilder inspectorBuilder = new() { + Definitions = + DefaultDefinitions.FileTypes.Images.All() + .Union(DefaultDefinitions.FileTypes.Video.All()) + .ToList() + }; + + inspector = inspectorBuilder.Build(); + } + + public void SetIngest(Media media, bool ingest) { + using var db = dbFactory.CreateDbContext(); + media = db.Media + .Include(m => m.Tags) + .ThenInclude(t => t.TagDefinition) + .First(m => m.Guid == media.Guid); + var ingestTag = db.TagDefinitions + .First(td => td.Guid == HBContext.IngestTag); + + if(ingest) { + if(!media.Tags.Select(t => t.TagDefinition.Guid).Contains(HBContext.IngestTag)) + media.Tags.Add(new(ingestTag)); + } else { + media.Tags.RemoveAll(t => t.TagDefinition.Guid == HBContext.IngestTag); + } + + db.SaveChanges(); + } + + public void SetDescription( + Media media, + string? shortDescription, + string? longDescription) { + + using var db = dbFactory.CreateDbContext(); + var m = db.Media.First(m => m.Guid == media.Guid); + + shortDescription = shortDescription?.Trim(); + longDescription = longDescription?.Trim(); + + if(string.IsNullOrEmpty(shortDescription)) + shortDescription = null; + if(string.IsNullOrEmpty(longDescription)) + longDescription = null; + + m.ShortDescription = shortDescription; + m.LongDescription = longDescription; + + db.SaveChanges(); + } + + public Media Create( + Stream fileData, + string fileName, + string? checksum = null, + DateTime? lastAccessTime = null, + DateTime? lastWriteTime = null, + DateTime? createTime = null, + string? path = null, + PathType? pathType = null, + Guid[]? tagIds = null) { + + using var db = dbFactory.CreateDbContext(); + using var transaction = db.Database.BeginTransaction(); + + if(fileData.Length == 0) + throw new MediaCreateException("File is empty"); + + // Calculate the checksum using the in-memory file contents + var hash = BitConverter + .ToString(MD5.Create().ComputeHash(fileData)) + .Replace("-", "") + .ToLower(); + + if(checksum is not null && hash != checksum.ToLower()) + throw new MediaCreateException("Checksum does not match"); + + // Determine the MIME type + fileData.Seek(0, SeekOrigin.Begin); + var defs = inspector.Inspect(fileData); + var mime = defs.ByMimeType().FirstOrDefault()?.MimeType; + if(mime is null) + throw new MediaCreateException("Unsupported file type"); + + // Read the image with ImageMagick to determine the width and height + fileData.Seek(0, SeekOrigin.Begin); + using var magickImage = new MagickImage(fileData); + + var media = db.Media + .Include(m => m.UploadedFiles) + .Include(m => m.Tags) + .FirstOrDefault(m => m.UploadedFiles.Any(uf => uf.Checksum == hash)); + + var fileRecord = new UploadedFile() { + Filename = fileName, + Length = fileData.Length, + Checksum = hash, + ChecksumVerified = checksum is not null, + MimeType = mime, + Width = (int) magickImage.Width, + Height = (int) magickImage.Height, + UploadTime = DateTime.UtcNow, + LastAccessTime = lastAccessTime, + LastWriteTime = lastWriteTime, + CreateTime = createTime, + Path = pathType is null ? null : path, + PathType = pathType + }; + + var tags = Array.Empty(); + if(tagIds is not null) { + tagIds = tagIds.Distinct().ToArray(); + + tags = db.TagDefinitions + .Where(td => tagIds.Contains(td.Guid)) + .ToArray(); + + if(tags.Count() < tagIds.Count()) { + var badIds = tagIds + .Where(x => !tags.Select(td => td.Guid).Contains(x)) + .Order(); + + throw new MediaCreateException( + $"Non-existent tags specified: {string.Join(", ", badIds)}"); + } + } + + if(media is null) { + var ingestTagDef = db.TagDefinitions + .First(td => td.Guid == HBContext.IngestTag); + + media = new() { + UploadedFiles = new() { + fileRecord + }, + Tags = tags is null ? [ new() { TagDefinition = ingestTagDef } ] : tags + .Select(td => new Tag() { TagDefinition = td }) + .ToList() + }; + + using var newFile = File.Create(GetPath(media)); + + fileData.Seek(0, SeekOrigin.Begin); + fileData.CopyTo(newFile); + newFile.Flush(); + + db.Media.Add(media); + db.SaveChanges(); + media.CurrentUploadedFile = fileRecord; + db.SaveChanges(); + } else { + var fileHashes = media.UploadedFiles + .Select(uf => GetUploadedFileHash(uf)); + // Only add the uploaded file record if it contains new information + if(!fileHashes.Contains(GetUploadedFileHash(fileRecord))) + media.UploadedFiles.Add(fileRecord); + // Add new tags if needed + var missingTags = tags + .Where(td => !media.Tags.Select(t => t.TagDefinition.Guid).Contains(td.Guid)); + media.Tags.AddRange(missingTags.Select(td => new Tag() { TagDefinition = td })); + db.Update(media); + db.SaveChanges(); + } + + transaction.Commit(); + + return media; + } + + public void Delete(Guid media) { + using var db = dbFactory.CreateDbContext(); + var m = db.Media.First(m => m.Guid == media); + + var path = Path.Join( + config.MediaBasePath, + m.Guid.ToString().Substring(0, 2), + m.Guid.ToString().Substring(2, 2), + m.Guid.ToString()); + + try { + var fileInfo = new FileInfo(path); + fileInfo.Delete(); + fileInfo.Directory?.Delete(); + fileInfo.Directory?.Parent?.Delete(); + } catch(IOException) {} + + try { + DeleteThumbnails(media); + } catch {} + + db.Media.Remove(m); + db.SaveChanges(); + } + + public void Delete(Media media) => + Delete(media.Guid); + + public void DeleteThumbnails(Guid media) { + var dir = new DirectoryInfo(Path.Join( + config.ThumbnailBasePath, + media.ToString().Substring(0, 2), + media.ToString().Substring(2, 2))); + + var pattern = new Regex($"^{media}-[0-9]+-[0-9]+$"); + var toDelete = dir.GetFiles() + .Where(f => pattern.IsMatch(f.Name)) + .ToList(); + + List exceptions = new(); + + foreach(var file in toDelete) { + try { + file.Delete(); + } catch(Exception e) { + exceptions.Add(e); + } + } + + try { + dir.Delete(); + dir.Parent?.Delete(); + } catch(Exception e) { + exceptions.Add(e); + } + + // TODO: wrap the AggregateException in a ThumbnailException + if(exceptions.Count() > 1) + throw new AggregateException(exceptions); + } + + public void DeleteThumbnails(Media media) => + DeleteThumbnails(media.Guid); + + public Stream GetThumbnail(Guid mediaId, int? width, int? height) { + if(width is null && height is null) + throw new ThumbnailException( + "Both width and height cannot be null!", + mediaId); + + var thumbPath = GetThumbnailPath(mediaId, width, height); + + if(File.Exists(thumbPath)) + return System.IO.File.OpenRead(thumbPath); + + if(!File.Exists(GetPath(mediaId))) + throw new ObjectNotFoundException(mediaId); + + using var image = new MagickImage(GetPath(mediaId)); + + if(width > image.Width || height > image.Height) { + width = (int) image.Width; + height = (int) image.Height; + } + + image.Thumbnail((uint) (width ?? -1), (uint) (height ?? -1)); + image.Write(thumbPath, MagickFormat.Jpeg); + + return System.IO.File.OpenRead(thumbPath); + } + + public Stream GetConverted(Guid mediaId, string mimeType) { + if(!FormatMap.TryGetValue(mimeType, out var format)) + throw new MediaException($"Cannot convert to unknown format ({mimeType})", mediaId); + + var convertedPath = GetConvertedPath(mediaId, mimeType); + + if(File.Exists(convertedPath)) + return System.IO.File.OpenRead(convertedPath); + + if(!File.Exists(GetPath(mediaId))) + throw new ObjectNotFoundException(mediaId); + + using var image = new MagickImage(GetPath(mediaId)); + image.Write(convertedPath, format); + + return System.IO.File.OpenRead(convertedPath); + } + + public Stream GetThumbnail(Media media, int? width, int? height) => + GetThumbnail(media.Guid, width, height); + + public Stream GetConverted(Media media, string mimeType) => + GetConverted(media.Guid, mimeType); + + public string GetPath(Guid mediaId) { + var fileInfo = new FileInfo( + Path.Join( + config.MediaBasePath, + mediaId.ToString().Substring(0, 2), + mediaId.ToString().Substring(2, 2), + mediaId.ToString())); + + Directory.CreateDirectory(fileInfo.Directory!.FullName); + return fileInfo.FullName; + } + + public string GetThumbnailPath(Guid mediaId, int? width, int? height) { + if(width is null && height is null) + throw new ThumbnailException( + "Both width and height cannot be null!", + mediaId); + + var fileInfo = new FileInfo(Path.Join( + config.ThumbnailBasePath, + mediaId.ToString().Substring(0, 2), + mediaId.ToString().Substring(2, 2), + $"{mediaId.ToString()}-{(width ?? 0)}-{(height ?? 0)}")); + + Directory.CreateDirectory(fileInfo.Directory!.FullName); + return fileInfo.FullName; + } + + public string GetConvertedPath(Guid mediaId, string mimeType) { + var fileInfo = new FileInfo(Path.Join( + config.ConvertedMediaBasePath, + mediaId.ToString().Substring(0, 2), + mediaId.ToString().Substring(2, 2), + $"{mediaId.ToString()}-{mimeType.Split('/')[1]}")); + + Directory.CreateDirectory(fileInfo.Directory!.FullName); + return fileInfo.FullName; + } + + public string GetPath(Media media) => + GetPath(media.Guid); + + public string GetThumbnailPath(Media media, int? width, int? height) => + GetThumbnailPath(media.Guid, width, height); + + public string GetConvertedPath(Media media, string mimeType) => + GetConvertedPath(media.Guid, mimeType); + + private int GetUploadedFileHash(UploadedFile uf) => ( + uf.CreateTime, + uf.LastWriteTime, + uf.Filename, + uf.Length, + uf.Checksum).GetHashCode(); +} diff --git a/Server/Services/OcrService.cs b/Server/Services/OcrService.cs new file mode 100644 index 0000000..d43db2e --- /dev/null +++ b/Server/Services/OcrService.cs @@ -0,0 +1,128 @@ +using HyperBooru.Util; +using Microsoft.EntityFrameworkCore; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using Tesseract; + +namespace HyperBooru.Services; + +public class OcrService : IHostedService { + private readonly string[] InvalidMimeTypes = [ "image/heic", "image/webp" ]; + + private readonly TimeSpan ProcessInterval = TimeSpan.FromMinutes(30); + private readonly TimeSpan StartupDelay = TimeSpan.FromSeconds(30); + + private readonly Regex SpaceRegex = new(@"[^0-9a-z]+", RegexOptions.Compiled); + + private Task? task; + private CancellationTokenSource cts = new(); + + private Timer timer; + + private IConfigService configService; + private IServiceScopeFactory scopeFactory; + private ILogger logger; + private IDbContextFactory dbFactory; + + public OcrService( + IConfigService configService, + IServiceScopeFactory scopeFactory, + ILogger logger, + IDbContextFactory dbFactory) { + + this.configService = configService; + this.scopeFactory = scopeFactory; + this.logger = logger; + this.dbFactory = dbFactory; + + timer = new((object? state) => { + if(task is not null && !task.IsCompleted) + return; + cts = new(); + task = ProcessAllAsync(cts.Token); + }); + } + + public Task StartAsync(CancellationToken ct) { + if(configService.EnableOcr) { + logger.LogInformation("Service starting..."); + timer.Change(StartupDelay, ProcessInterval); + } + + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken ct) { + logger.LogInformation("Service stopping..."); + timer.Change(Timeout.Infinite, Timeout.Infinite); + cts.Cancel(); + return Task.CompletedTask; + } + + async Task ProcessAllAsync(CancellationToken ct) { + using var scope = scopeFactory.CreateScope(); + var mediaService = scope.ServiceProvider + .GetRequiredService(); + + using var db = dbFactory.CreateDbContext(); + Guid[] guids = db.Media + .AsNoTracking() + .Include(m => m.CurrentUploadedFile) + .Include(m => m.OcrData) + .Where(m => m.OcrData == null) + .Where(m => m.CurrentUploadedFile!.MimeType.Contains("image/")) + .Where(m => !InvalidMimeTypes.Contains(m.CurrentUploadedFile!.MimeType)) + .Select(m => m.Guid) + .ToArray(); + db.Dispose(); + + logger.LogInformation($"Performing OCR pass on {guids.Count()} media items"); + + var factory = new TaskFactory(new LimitedConcurrencyTaskScheduler()); + var tasks = new List(); + + var stopwatch = Stopwatch.StartNew(); + + foreach(var guid in guids) + tasks.Add(factory.StartNew(() => Process(guid, mediaService), ct)); + + await Task.WhenAll(tasks); + stopwatch.Stop(); + + var time = stopwatch.Elapsed.ToStringHumanReadable(); + logger.LogInformation( + $"Performed OCR pass on {guids.Count()} media items in {time}"); + } + + private void Process(Guid media, IMediaService mediaService) { + logger.LogDebug($"Performing OCR on media item {media}"); + + using var db = dbFactory.CreateDbContext(); + var m = db.Media + .Include(m => m.OcrData) + .First(m => m.Guid == media); + + OcrData o = m.OcrData ?? new(); + + using var engine = new TesseractEngine("tessdata", "eng", EngineMode.Default); + using var image = Pix.LoadFromFile(mediaService.GetPath(m)); + engine.SetVariable("debug_file", NullFile); + + o.Timestamp = DateTime.UtcNow; + o.Text = engine.Process(image).GetText().Trim(); + o.SearchableText = SpaceRegex.Replace(o.Text.ToLower(), " ").Trim(); + + m.OcrData = o; + db.SaveChanges(); + } + + private string NullFile { + get { + if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return "NUL"; + else + return "/dev/null"; + } + } +} diff --git a/Server/Services/SourceService.cs b/Server/Services/SourceService.cs new file mode 100644 index 0000000..d145346 --- /dev/null +++ b/Server/Services/SourceService.cs @@ -0,0 +1,20 @@ +using System.Text.RegularExpressions; + +namespace HyperBooru.Services; + +public interface ISourceService { + public string? GetUrlFromFilename(string filename); +} + +public class SourceService : ISourceService { + private Regex PixivRegex = + new(@"^([0-9]+)_p[0-9]+(_master1200)?\.[^.]+$", RegexOptions.Compiled); + + public string? GetUrlFromFilename(string filename) { + var pixivMatch = PixivRegex.Match(filename); + if(pixivMatch.Success) + return $"https://pixiv.net/en/artworks/{pixivMatch.Groups[1].Value}"; + + return null; + } +} diff --git a/Server/Services/TagService.cs b/Server/Services/TagService.cs new file mode 100644 index 0000000..f7b91dc --- /dev/null +++ b/Server/Services/TagService.cs @@ -0,0 +1,305 @@ +using HyperBooru.ApiModels; +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru.Services; + +public interface ITagService { + public void AddTag(Guid obj, Guid tagDef); + public void AddTag(HBObject obj, TagDefinition tagDef); + public void RemoveTag(Guid obj, Guid tagDef); + public void RemoveTag(HBObject obj, TagDefinition tagDef); + public void SetImplicitTags(TagDefinition tagDef, TagDefinition[] implicitTagDefs); + public void SetImplicitTags(Guid tagDef, Guid[] implicitTagDefs); + public void AddImplicitTag(Guid tagDef, Guid implicitTagDef); + public void AddImplicitTag(TagDefinition tagDef, TagDefinition implicitTagDef); + public void RemoveImplicitTag(Guid tagDef, Guid implicitTagDef); + public void RemoveImplicitTag(TagDefinition tagDef, TagDefinition implicitTagDef); + public void CreateTagDefinition(string name, string? @namespace = null, string? alias = null); + public void DeleteTagDefinition(Guid tagDef); + public void DeleteTagDefinition(TagDefinition tagDef); + public void UpdateTagDefinition(Guid tagDef, string name, string? @namespace = null, string? alias = null); + public void UpdateTagDefinition(TagDefinition tagDef, string name, string? @namespace = null, string? alias = null); + public (TagDefinition tagDefinition, bool isImplicit)[] GetAllTags(Guid obj); + public (TagDefinition tagDefinition, bool isImplicit)[] GetAllTags(HBObject obj); + public (TagDefinition tagDefinition, bool isImplicit)[] GetAllTags(TagDefinition tagDef); + public TagDefinition[] TagsThatImply(Guid tagDef); + public TagDefinition[] TagsThatImply(TagDefinition tagDef); +} + +public class TagService : ITagService { + private IDbContextFactory dbFactory; + + public TagService(IDbContextFactory dbFactory) => + this.dbFactory = dbFactory; + + public void AddTag(Guid obj, Guid tagDef) { + using var db = dbFactory.CreateDbContext(); + + var tag = db.TagDefinitions.First(td => td.Guid == tagDef); + + db.Objects + .Include(o => o.Tags) + .ThenInclude(t => t.TagDefinition) + .Where(o => !o.Tags.Select(t => t.TagDefinition.Guid).Contains(tagDef)) + .FirstOrDefault(o => o.Guid == obj)? + .Tags + .Add(new(tag)); + + db.SaveChanges(); + } + + public void AddTag(HBObject obj, TagDefinition tagDef) => + AddTag(obj.Guid, tagDef.Guid); + + public void RemoveTag(Guid obj, Guid tagDef) { + using var db = dbFactory.CreateDbContext(); + + db.Objects + .Include(o => o.Tags) + .ThenInclude(t => t.TagDefinition) + .First(o => o.Guid == obj) + .Tags + .RemoveAll(t => t.TagDefinition.Guid == tagDef); + + db.SaveChanges(); + } + + public void RemoveTag(HBObject obj, TagDefinition tagDef) => + RemoveTag(obj.Guid, tagDef.Guid); + + public void SetImplicitTags(Guid tagDef, Guid[] implicitTagDefs) { + using var db = dbFactory.CreateDbContext(); + using var transaction = db.Database.BeginTransaction(); + + var tag = db.TagDefinitions + .Include(td => td.ImplicitTags) + .First(td => td.Guid == tagDef); + + tag.ImplicitTags.RemoveAll(td => !implicitTagDefs.Contains(td.Guid)); + tag.ImplicitTags.AddRange( + db.TagDefinitions + .Where(td => implicitTagDefs.Contains(td.Guid)) + .Where(td => !tag.ImplicitTags + .Select(td => td.Guid) + .Contains(td.Guid))); + + db.SaveChanges(); + transaction.Commit(); + } + + public void SetImplicitTags(TagDefinition tagDef, TagDefinition[] implicitTagDefs) => + SetImplicitTags(tagDef.Guid, implicitTagDefs.Select(td => td.Guid).ToArray()); + + public void AddImplicitTag(Guid tagDef, Guid implicitTagDef) { + using var db = dbFactory.CreateDbContext(); + + var tag = db.TagDefinitions + .Include(td => td.ImplicitTags) + .First(td => td.Guid == tagDef); + var implicitTag = db.TagDefinitions.First(td => td.Guid == implicitTagDef); + + tag.ImplicitTags.Add(implicitTag); + db.SaveChanges(); + } + + public void AddImplicitTag(TagDefinition tagDef, TagDefinition implicitTagDef) => + AddImplicitTag(tagDef, implicitTagDef); + + public void RemoveImplicitTag(Guid tagDef, Guid implicitTagDef) { + using var db = dbFactory.CreateDbContext(); + + var tag = db.TagDefinitions + .Include(td => td.ImplicitTags) + .First(td => td.Guid == tagDef); + + tag.ImplicitTags.RemoveAll(td => td.Guid == implicitTagDef); + db.SaveChanges(); + } + + public void RemoveImplicitTag(TagDefinition tagDef, TagDefinition implicitTagDef) => + RemoveImplicitTag(tagDef, implicitTagDef); + + public void CreateTagDefinition(string name, string? @namespace = null, string? alias = null) { + using var db = dbFactory.CreateDbContext(); + + if(string.IsNullOrEmpty(@namespace)) + @namespace = null; + if(string.IsNullOrEmpty(alias)) + alias = null; + + // Remove leading and trailing whitespace + name = name.Trim(); + @namespace = @namespace?.Trim(); + alias = alias?.Trim(); + + TagDefinition tagDef = new() { + Source = TagSource.UserTag, + Namespace = @namespace, + Name = name, + Alias = alias + }; + + bool nameExists = db.TagDefinitions.Any(td => td.Name.ToLower() == name.ToLower()); + bool aliasExists = false; + if(alias is not null) + aliasExists = db.TagDefinitions + .Where(td => td.Alias != null) + .Any(td => td.Alias!.ToLower() == alias.ToLower()); + if(nameExists || aliasExists) + throw new TagDuplicateException(nameExists, aliasExists); + + if(!db.TagDefinitions.Contains(tagDef)) + db.TagDefinitions.Add(tagDef); + db.SaveChanges(); + } + + public void DeleteTagDefinition(Guid tagDef) { + using var db = dbFactory.CreateDbContext(); + + var tag = db.TagDefinitions.First(td => td.Guid == tagDef); + + using var transaction = db.Database.BeginTransaction(); + + db.Tags.RemoveRange( + db.Tags + .Include(t => t.TagDefinition) + .Where(t => t.TagDefinition.Guid == tagDef)); + db.TagDefinitions.Remove(tag); + db.SaveChanges(); + + transaction.Commit(); + } + + public void DeleteTagDefinition(TagDefinition tagDef) => + DeleteTagDefinition(tagDef.Guid); + + public void UpdateTagDefinition(Guid tagDef, string name, string? @namespace = null, string? alias = null) { + using var db = dbFactory.CreateDbContext(); + + if(string.IsNullOrEmpty(@namespace)) + @namespace = null; + if(string.IsNullOrEmpty(alias)) + alias = null; + + // Remove leading and trailing whitespace + name = name.Trim(); + @namespace = @namespace?.Trim(); + alias = alias?.Trim(); + + var tag = db.TagDefinitions.First(td => td.Guid == tagDef); + + TagDefinition? nameExisting = db.TagDefinitions.FirstOrDefault(td => td.Name.ToLower() == name.ToLower()); + TagDefinition? aliasExisting = null; + if(alias is not null) + aliasExisting = db.TagDefinitions + .Where(td => td.Alias != null) + .FirstOrDefault(td => td.Alias!.ToLower() == alias.ToLower()); + bool nameExists = nameExisting is not null && nameExisting != tag; + bool aliasExists = aliasExisting is not null && aliasExisting != tag; + if(nameExists || aliasExists) + throw new TagDuplicateException(nameExists, aliasExists); + + tag.Name = name; + tag.Namespace = @namespace; + tag.Alias = alias; + + db.SaveChanges(); + } + + public void UpdateTagDefinition(TagDefinition tagDef, string name, string? @namespace = null, string? alias = null) => + UpdateTagDefinition(tagDef.Guid, name, @namespace, alias); + + private (TagDefinition tagDefinition, bool isImplicit)[] GetAllTags(IEnumerable tagDefs) { + using var db = dbFactory.CreateDbContext(); + + var tagGuids = tagDefs + .Select(td => td.Guid) + .ToArray(); + + // Query all tag definitions + var allTags = db.TagDefinitions + .Include(td => td.ImplicitTags) + .ToArray(); + + var tags = new List( + allTags.IntersectBy( + tagGuids, + td => td.Guid)); + + while(true) { + var toAdd = tags + .SelectMany(td => td.ImplicitTags) + .ExceptBy(tags.Select(td => td.Guid), td => td.Guid) + .ToArray(); + + if(toAdd.Count() == 0) + break; + + tags.AddRange(toAdd); + } + + return tags + .Select(td => new ValueTuple(td, !tagGuids.Contains(td.Guid))) + .ToArray(); + } + + public (TagDefinition tagDefinition, bool isImplicit)[] GetAllTags(Guid obj) { + using var db = dbFactory.CreateDbContext(); + + // Query a list of tag GUIDs for this object + var tags = db.Objects + .Include(o => o.Tags) + .ThenInclude(t => t.TagDefinition) + .First(o => o.Guid == obj) + .Tags + .Select(t => t.TagDefinition) + .ToArray(); + + return GetAllTags(tags); + } + + + public (TagDefinition tagDefinition, bool isImplicit)[] GetAllTags(HBObject obj) => + GetAllTags(obj.Guid); + + public (TagDefinition tagDefinition, bool isImplicit)[] GetAllTags(TagDefinition tagDef) { + using var db = dbFactory.CreateDbContext(); + + var tags = db.TagDefinitions + .Include(td => td.ImplicitTags) + .First(td => td.Guid == tagDef.Guid) + .ImplicitTags + .ToArray(); + + return GetAllTags(tags); + } + + public TagDefinition[] TagsThatImply(Guid tagDef) { + using var db = dbFactory.CreateDbContext(); + + var tagDefs = db.TagDefinitions + .Include(td => td.ImplicitTags) + .ToArray(); + + var tags = new List() { + db.TagDefinitions.First(td => td.Guid == tagDef) + }; + + while(true) { + var toAdd = tagDefs + .Where(td => td.ImplicitTags.Select(it => it.Guid).Intersect(tags.Select(td => td.Guid)).Any()) + .ExceptBy(tags.Select(td => td.Guid), td => td.Guid) + .ToArray(); + + if(toAdd.Count() == 0) + break; + + tags.AddRange(toAdd); + } + + return tags.ToArray(); + } + + public TagDefinition[] TagsThatImply(TagDefinition tagDef) => + TagsThatImply(tagDef.Guid); +} diff --git a/Server/Services/UserService.cs b/Server/Services/UserService.cs new file mode 100644 index 0000000..9e79dc6 --- /dev/null +++ b/Server/Services/UserService.cs @@ -0,0 +1,76 @@ +using Microsoft.AspNetCore.Cryptography.KeyDerivation; + +namespace HyperBooru.Services; + +public interface IUserService { + public UserSessionState UserSessionState { get; } +} + +public class UserService : IUserService { + public UserSessionState UserSessionState => + globalUserService.GetSessionState(httpContext.Session.Id); + + private IHttpContextAccessor httpContextAccessor; + private IGlobalUserService globalUserService; + + private HttpContext httpContext => + httpContextAccessor.HttpContext!; + + public UserService( + IHttpContextAccessor httpContextAccessor, + IGlobalUserService globalUserService) { + + this.httpContextAccessor = httpContextAccessor; + this.globalUserService = globalUserService; + + // HTTP context session states are discarded if no values + // are set. Set a dummy value so that the session state + // will not be discarded later when we actually need it. + httpContext.Session.SetInt32("Persist", 1); + } + + public static string HashPassword(string password) => + Convert.ToBase64String( + KeyDerivation.Pbkdf2( + password, + Array.Empty(), + KeyDerivationPrf.HMACSHA512, + 100_000, + 512 / 8)); +} + +public interface IGlobalUserService { + public UserSessionState GetSessionState(string id); +} + +public class GlobalUserService : IGlobalUserService { + // TODO: prune this list periodically + private Dictionary sessionStates = new(); + + public UserSessionState GetSessionState(string id) { + sessionStates.TryGetValue(id, out var state); + + if(state is null) { + state = new(); + sessionStates[id] = state; + } + + return state; + } +} + +public record UserSessionState { + public event UserSessionStateChange OnStateChange; + + public bool ShowNsfw { + get => showNsfw; + set { + showNsfw = value; + OnStateChange.Invoke(this); + } + } + + private bool showNsfw = false; +} + +public delegate void UserSessionStateChange(UserSessionState sessionState); diff --git a/Server/Tag.cs b/Server/Tag.cs new file mode 100644 index 0000000..c857c66 --- /dev/null +++ b/Server/Tag.cs @@ -0,0 +1,37 @@ +using System.ComponentModel.DataAnnotations.Schema; + +namespace HyperBooru; + +public enum TagSource { + Internal, + UserTag +} + +public class TagDefinition : HBObject { + public TagSource Source { get; set; } = TagSource.Internal; + public string? Namespace { get; set; } + public string Name { get; set; } + public string? Alias { get; set; } + public virtual List ImplicitTags { get; set; } = new(); + + public static explicit operator ApiModels.TagDefinition(TagDefinition tagDefinition) => new() { + TagDefinitionId = tagDefinition.Guid, + Namespace = tagDefinition.Namespace, + Name = tagDefinition.Name, + Alias = tagDefinition.Alias, + ImplicitTags = tagDefinition.ImplicitTags.Select(td => td.Guid).ToArray() + }; +} + +public class Tag : HBObject { + [ForeignKey("ObjectId")] + public int TagDefinitionId { get; set; } + public virtual TagDefinition TagDefinition { get; set; } + public DateTime CreateTime { get; set; } = DateTime.UtcNow; + public virtual HBObject Target { get; set; } + + public Tag() {} + + public Tag(TagDefinition tagDef) => + this.TagDefinition = tagDef; +} diff --git a/Server/Todo.md b/Server/Todo.md new file mode 100644 index 0000000..23c406d --- /dev/null +++ b/Server/Todo.md @@ -0,0 +1,41 @@ +# Bugs + - [X] Images in the gallery on mobile can easily exceed screen width + - [X] Images smaller than the requested thumbnail size aren't delivered + - [X] Autocorrect needs to be disabled on inputs such as username, tag name, etc + - [X] Mobile menu does not automatically hide upon page navigation + - [X] Input not focused + - [ ] Setting implicit tags removes builtin tags + - [X] UserService listeners don't seem to be removed after disposal + - [X] Cancelling tag creation creates the tag anyway + - [ ] Prevent marking tagging complete unless there are actually user tags + - [X] Media upload not deduping media + - [ ] Can't delete media + +# Short-term Features + - [ ] Ability to set password (at least via API) + - [ ] PowerShell uploading with initial tagging + - [ ] Proper thumbnail generation + - [ ] Video support + - [ ] User/security support + - [X] Record in UploadedFiles whether the checksums was verified at upload time + - [X] Record in Media which UploadedFile actually holds the current content + +# Long-term Features + - [ ] Redirect to last page after login + - [ ] Enlarge image view in ViewMedia + - [ ] Periodic thumbnail scrubbing + - [ ] Loading animations + - [ ] Keyboard shortcuts + - [ ] Find source + - [ ] Collections + - [ ] Search memes by audio (for some reason) + - [ ] Jump into ingest feed at random point + - [ ] Rating system + - [ ] Instantaneous OCR processing when media is uploaded + - [ ] OCR status reporting on admin page + - [ ] Dynamically update OCR data on ViewMedia page + - [ ] Image deduplication by visual similarity + - [ ] Audit log + - [ ] Journaled operations + - [ ] Confirmation dialog before enabling NSFW mode + - [ ] Upload progress bars diff --git a/Server/User.cs b/Server/User.cs new file mode 100644 index 0000000..87384d2 --- /dev/null +++ b/Server/User.cs @@ -0,0 +1,15 @@ +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru; + +[Index(nameof(Username))] +public class User : HBObject { + public string Username { get; set; } + public string PasswordHash { get; set; } + + public static explicit operator ApiModels.User(User user) => + new() { + UserId = user.Guid, + Username = user.Username + }; +} diff --git a/Server/Util.cs b/Server/Util.cs new file mode 100644 index 0000000..6af6c81 --- /dev/null +++ b/Server/Util.cs @@ -0,0 +1,120 @@ +namespace HyperBooru.Util; + +public static class Extensions { + public static readonly string[] MagnitudeOrders = new[] { + "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q" + }; + + public static DateTime? TryParseDateTimeUtc(this string s) { + bool success = DateTime.TryParse(s, out var dateTime); + return success ? DateTime.SpecifyKind(dateTime, DateTimeKind.Utc) : null; + } + + public static string ToBytesSI(this long x) { + var exp = (int) Math.Log10(x); + var suffix = MagnitudeOrders.ElementAtOrDefault(exp / 3 - 1); + if(suffix is null) + return x.ToString(); + double n = x / Math.Pow(10, exp / 3 * 3); + return $"{Math.Round(n, 2 - (exp % 3))} {suffix}B"; + } + + public static string ToStringHumanReadable(this TimeSpan t) { + if(t.TotalMilliseconds < 1000) + return string.Format("{0:0}ms", t.TotalMilliseconds); + if(t.TotalSeconds < 60) + return string.Format("{0:0.00}s", t.TotalSeconds); + if(t.TotalMinutes < 60) + return string.Format("{0:0}m{0:0}s", t.TotalMinutes, t.Seconds); + if(t.TotalHours < 24) + return string.Format("{0:0}h{0:0}m", t.TotalHours, t.Minutes); + return string.Format("{0:0.00}d", t.TotalDays); + } +} + +public class LimitedConcurrencyTaskScheduler : TaskScheduler { + public sealed override int MaximumConcurrencyLevel => + maxConcurrency; + + private int maxConcurrency; + + [ThreadStatic] + private static bool threadIsProcessingItems; + + private readonly LinkedList tasks = new(); + + private int delegatesQueuedOrRunning = 0; + + public LimitedConcurrencyTaskScheduler() { + maxConcurrency = Environment.ProcessorCount; + } + + public LimitedConcurrencyTaskScheduler(int maxConcurrency) { + if(maxConcurrency < 1) + throw new ArgumentOutOfRangeException("maxConcurrency must be greater than 0"); + this.maxConcurrency = (int) maxConcurrency; + } + + protected sealed override void QueueTask(Task task) { + lock(tasks) { + tasks.AddLast(task); + if(delegatesQueuedOrRunning < maxConcurrency) { + delegatesQueuedOrRunning++; + NotifyThreadPoolOfPendingWork(); + } + } + } + + private void NotifyThreadPoolOfPendingWork() { + ThreadPool.UnsafeQueueUserWorkItem(_ => { + threadIsProcessingItems = true; + try { + while(true) { + Task item; + lock(tasks) { + if(tasks.Count == 0) { + delegatesQueuedOrRunning--; + break; + } else { + item = tasks.First.Value; + tasks.RemoveFirst(); + } + } + TryExecuteTask(item); + } + } finally { + threadIsProcessingItems = false; + } + }, null); + } + + protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { + if(!threadIsProcessingItems) + return false; + + if(taskWasPreviouslyQueued) + return TryDequeue(task) ? TryExecuteTask(task) : false; + else + return TryExecuteTask(task); + } + + protected sealed override bool TryDequeue(Task task) { + lock(tasks) { + return tasks.Remove(task); + } + } + + protected sealed override IEnumerable GetScheduledTasks() { + bool lockTaken = false; + try { + Monitor.TryEnter(tasks, ref lockTaken); + if(lockTaken) + return tasks; + else + throw new NotSupportedException(); + } finally { + if(lockTaken) + Monitor.Exit(tasks); + } + } +} diff --git a/Server/appsettings.Development.json b/Server/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Server/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Server/appsettings.json b/Server/appsettings.json new file mode 100644 index 0000000..414e673 --- /dev/null +++ b/Server/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "ConnectionStrings": { + "DefaultConnection": "Host=127.0.0.1;Database=hyperbooru;Username=hyperbooru;Password=password" + }, + "AllowedHosts": "*" +} diff --git a/Server/dotnet-tools.json b/Server/dotnet-tools.json new file mode 100644 index 0000000..7dcefc3 --- /dev/null +++ b/Server/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-ef": { + "version": "10.0.8", + "commands": [ + "dotnet-ef" + ], + "rollForward": false + } + } +} \ No newline at end of file diff --git a/Server/tessdata/eng.traineddata b/Server/tessdata/eng.traineddata new file mode 100644 index 0000000..176dc32 Binary files /dev/null and b/Server/tessdata/eng.traineddata differ diff --git a/Server/wwwroot/app.css b/Server/wwwroot/app.css new file mode 100644 index 0000000..73a69d6 --- /dev/null +++ b/Server/wwwroot/app.css @@ -0,0 +1,60 @@ +html, body { + font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; +} + +a, .btn-link { + color: #006bb7; +} + +.btn-primary { + color: #fff; + background-color: #1b6ec2; + border-color: #1861ac; +} + +.btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { + box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; +} + +.content { + padding-top: 1.1rem; +} + +h1:focus { + outline: none; +} + +.valid.modified:not([type=checkbox]) { + outline: 1px solid #26b050; +} + +.invalid { + outline: 1px solid #e50000; +} + +.validation-message { + color: #e50000; +} + +.blazor-error-boundary { + background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; + padding: 1rem 1rem 1rem 3.7rem; + color: white; +} + + .blazor-error-boundary::after { + content: "An error has occurred." + } + +.darker-border-checkbox.form-check-input { + border-color: #929292; +} + +.form-floating > .form-control-plaintext::placeholder, .form-floating > .form-control::placeholder { + color: var(--bs-secondary-color); + text-align: end; +} + +.form-floating > .form-control-plaintext:focus::placeholder, .form-floating > .form-control:focus::placeholder { + text-align: start; +} \ No newline at end of file diff --git a/Server/wwwroot/css/site.css b/Server/wwwroot/css/site.css new file mode 100644 index 0000000..21f9a94 --- /dev/null +++ b/Server/wwwroot/css/site.css @@ -0,0 +1,28 @@ +#blazor-error-ui { + background: #555; + bottom: 0; + box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); + display: none; + left: 0; + padding: 0.6rem 1.25rem 0.7rem 1.25rem; + position: fixed; + width: 100%; + z-index: 1000; +} + +#blazor-error-ui .dismiss { + cursor: pointer; + position: absolute; + right: 3.5rem; + top: 0.5rem; +} + +.blazor-error-boundary { + background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; + color: white; + padding: 1rem 1rem 1rem 3.7rem; +} + +.blazor-error-boundary::after { + content: "An error has occurred." +} diff --git a/Server/wwwroot/favicon.ico b/Server/wwwroot/favicon.ico new file mode 100644 index 0000000..a1be4cc Binary files /dev/null and b/Server/wwwroot/favicon.ico differ diff --git a/Server/wwwroot/icon-192.png b/Server/wwwroot/icon-192.png new file mode 100644 index 0000000..28ce06d Binary files /dev/null and b/Server/wwwroot/icon-192.png differ diff --git a/Server/wwwroot/icon-512.png b/Server/wwwroot/icon-512.png new file mode 100644 index 0000000..8c28696 Binary files /dev/null and b/Server/wwwroot/icon-512.png differ diff --git a/Server/wwwroot/images/book.svg b/Server/wwwroot/images/book.svg new file mode 100644 index 0000000..6cdfc79 --- /dev/null +++ b/Server/wwwroot/images/book.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Server/wwwroot/images/checkmark.svg b/Server/wwwroot/images/checkmark.svg new file mode 100644 index 0000000..5e55d9e --- /dev/null +++ b/Server/wwwroot/images/checkmark.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Server/wwwroot/images/cross.svg b/Server/wwwroot/images/cross.svg new file mode 100644 index 0000000..0c37363 --- /dev/null +++ b/Server/wwwroot/images/cross.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Server/wwwroot/images/edit.svg b/Server/wwwroot/images/edit.svg new file mode 100644 index 0000000..d4c6ec4 --- /dev/null +++ b/Server/wwwroot/images/edit.svg @@ -0,0 +1,7 @@ + + + + + + alt-square-pencil + \ No newline at end of file diff --git a/Server/wwwroot/images/info.svg b/Server/wwwroot/images/info.svg new file mode 100644 index 0000000..b194f05 --- /dev/null +++ b/Server/wwwroot/images/info.svg @@ -0,0 +1,63 @@ + + + + + + + + + + + + diff --git a/Server/wwwroot/images/loginbg.webp b/Server/wwwroot/images/loginbg.webp new file mode 100644 index 0000000..759e666 Binary files /dev/null and b/Server/wwwroot/images/loginbg.webp differ diff --git a/Server/wwwroot/images/photo.svg b/Server/wwwroot/images/photo.svg new file mode 100644 index 0000000..486c360 --- /dev/null +++ b/Server/wwwroot/images/photo.svg @@ -0,0 +1,7 @@ + + + + + + image + \ No newline at end of file diff --git a/Server/wwwroot/images/tag.svg b/Server/wwwroot/images/tag.svg new file mode 100644 index 0000000..3eb8843 --- /dev/null +++ b/Server/wwwroot/images/tag.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Server/wwwroot/images/trash.svg b/Server/wwwroot/images/trash.svg new file mode 100644 index 0000000..18ff9c1 --- /dev/null +++ b/Server/wwwroot/images/trash.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Server/wwwroot/js/dialog.js b/Server/wwwroot/js/dialog.js new file mode 100644 index 0000000..418962f --- /dev/null +++ b/Server/wwwroot/js/dialog.js @@ -0,0 +1,78 @@ +function dialogMouseDown(e) { + bumpDialog(e.currentTarget); +} + +function dialogTitleMouseDown(e) { + e = e || window.event; + e.preventDefault(); + var element = e.currentTarget.parentElement; + var ds = element.dataset; + ds.lastX = e.clientX; + ds.lastY = e.clientY; + + window.dragDialog = element; + document.onmouseup = dragMouseUp; + document.onmousemove = dragMouseMove; +} + +function dragMouseUp() { + window.dragDialog = null; + document.onmouseup = null; + document.onmousemove = null; +} + +function dragMouseMove(e) { + e = e || window.event; + e.preventDefault(); + var element = window.dragDialog; + var ds = element.dataset; + deltaX = ds.lastX - e.clientX; + deltaY = ds.lastY - e.clientY; + ds.lastX = e.clientX; + ds.lastY = e.clientY; + element.style.left = (element.offsetLeft - deltaX) + 'px'; + element.style.top = (element.offsetTop - deltaY) + 'px'; +} + +function setDialogVisibility(element, visible) { + if(visible) { + element.style.left = null; + element.style.top = null; + element.style.opacity = 1; + element.style.visibility = 'visible'; + bumpDialog(element); + + var input = element.querySelector('input[type="text"]'); + if(input) { + setTimeout(() => input.focus(), 100); + } + } else { + element.style.opacity = 0; + element.style.visibility = 'hidden'; + } +} + +function bumpDialog(element) { + var dialogs = Array + .from(document.querySelectorAll('div.dialog')) + .map(e => ({ zIndex: parseInt(e.style.zIndex), element: e })) + .sort((a, b) => a.zIndex - b.zIndex) + .map(d => d.element) + .filter(e => e != element); + + dialogs.push(element); + + var z = 900; + for(var d of dialogs) + d.style.zIndex = z++; +} + +function dialogAddObjectReference(element, dialogObject) { + if(!window.dialogObjects) + window.dialogObjects = [] + + window.dialogObjects.push({ + element: element, + dialogObject: dialogObject + }); +} diff --git a/Server/wwwroot/js/keyboard.js b/Server/wwwroot/js/keyboard.js new file mode 100644 index 0000000..8b46639 --- /dev/null +++ b/Server/wwwroot/js/keyboard.js @@ -0,0 +1,57 @@ +async function keyDownHandler(e) { + function isDialogChild(e) { + while(e = e.parentElement) + if(e.tagName == 'DIV' && e.classList.contains('dialog')) + return true; + return false; + } + + var tag = document.activeElement.tagName; + if((tag == 'INPUT' || (tag == 'TEXTAREA' && e.ctrlKey)) && e.key == 'Enter') { + var element = document.activeElement; + while(element = element.parentElement) { + if(element.tagName == 'FORM') { + element + .querySelectorAll('input,textarea') + .forEach(e => e.dispatchEvent(new Event('change'))); + element.requestSubmit(); + e.preventDefault(); + return; + } + } + } + + if((tag == 'INPUT' || tag == 'TEXTAREA') && e.key != 'Escape') + return; + + var element = Array.from(document.querySelectorAll('div.dialog')) + .filter(e => e.style.visibility == 'visible') + .map(e => ({ element: e, zIndex: parseInt(e.style.zIndex) })) + .sort((a, b) => b.zIndex - a.zIndex) + .map(e => e.element)[0]; + + if(element) { + await window.dialogObjects + .find(d => d.element == element) + .dialogObject + .invokeMethodAsync('KeyHandler', e.key); + e.preventDefault(); + return; + } + + var button = Array.from(document.getElementsByTagName('button')) + .filter(b => typeof(b.dataset.keyboardShortcut) == 'string') + .filter(b => !isDialogChild(b)) + .find(b => b.dataset.keyboardShortcut == e.key); + + if(!e.ctrlKey && button) { + button.click(); + e.preventDefault(); + return; + } + + if(typeof pageKeyDownHandler == 'function') + pageKeyDownHandler(e); +} + +window.onload = () => document.onkeydown = keyDownHandler; \ No newline at end of file diff --git a/Server/wwwroot/js/mobile.js b/Server/wwwroot/js/mobile.js new file mode 100644 index 0000000..0af11cc --- /dev/null +++ b/Server/wwwroot/js/mobile.js @@ -0,0 +1,7 @@ +function hideMobileMenu() { + document.getElementsByTagName('body')[0].classList.remove('mobile-menu-visible'); +} + +function toggleMobileMenu() { + document.getElementsByTagName('body')[0].classList.toggle('mobile-menu-visible'); +} diff --git a/Server/wwwroot/loginbg.webm b/Server/wwwroot/loginbg.webm new file mode 100644 index 0000000..139ed0d Binary files /dev/null and b/Server/wwwroot/loginbg.webm differ diff --git a/Server/wwwroot/manifest.webmanifest b/Server/wwwroot/manifest.webmanifest new file mode 100644 index 0000000..f150f98 --- /dev/null +++ b/Server/wwwroot/manifest.webmanifest @@ -0,0 +1,6 @@ +{ + "icons": [ + { "src": "/icon-192.png", "type": "images/png", "sizes": "192x192" }, + { "src": "/icon-512.png", "type": "images/png", "sizes": "512x512" } + ] +} \ No newline at end of file diff --git a/Server/wwwroot/styles/data-table.css b/Server/wwwroot/styles/data-table.css new file mode 100644 index 0000000..994d625 --- /dev/null +++ b/Server/wwwroot/styles/data-table.css @@ -0,0 +1,21 @@ +table.data-table { + border-collapse: collapse; + width: 100%; +} + +table.data-table > tr > th { + border-bottom: 1px solid white; + padding: 4px; +} + +table.data-table > tr > td { + padding: 4px; +} + +table.data-table > tr:nth-child(2n) { + background: rgba(255, 255, 255, 0.1); +} + +table.data-table > tr > td:not(:last-child) { + border-right: 1px solid white; +} diff --git a/Server/wwwroot/styles/global.css b/Server/wwwroot/styles/global.css new file mode 100644 index 0000000..9de9fc1 --- /dev/null +++ b/Server/wwwroot/styles/global.css @@ -0,0 +1,214 @@ +@import url('data-table.css'); + +:root { + --col-accent-pri: #0aa; + --col-accent-pri-hl: #0cc; + --col-error-pri: #ffaa00; + --col-checksum-verified-pri: #8dff76; + --col-bg: #222; + --col-dialog-bg: #333; + --col-navbar-bg: var(--col-accent-pri); + --col-button-pri: var(--col-accent-pri); + --col-button-pri-hl: var(--col-accent-pri-hl); + --col-button-disabled: #777; + --col-button-disabled-bg: #444; + --col-button-sec: #555; + --col-button-sec-hl: #777; + --col-button-sec-disabled: #555; + --col-button-sec-disabled-bg: #000; + --col-button-warning: #ff4848; + --col-button-warning-hl: #ff9999; + --col-hr: #888; + --col-scrollbar: #666; + --col-scrollbar-hover: #aaaaaa; + --col-switch-bg: var(--col-bg); + --col-switch-fg: #fff; + --col-switch-bg-hl: var(--col-accent-pri); + --col-progbar-fg: var(--col-accent-pri); + --col-progbar-bg: #777; + + --size-default-gap: 30px; +} + +::selection { + background: var(--col-accent-pri); +} + +body { + background: var(--col-bg); + color: white; + display: flex; + flex-direction: column; + font-family: 'Trebuchet MS', 'Lucida Sans Unicode'; + height: 100dvh; + margin: 0; + overflow: hidden; + width: 100dvw; +} + +a { + color: var(--col-accent-pri); + text-decoration: none; +} + +@media (hover: hover) { + a:hover { + filter: brightness(1.5); + } +} + +a::selection { + background: var(--col-accent-pri); + color: #fff; +} + +a.nondecorated { + color: #fff; +} + +@media (hover: hover) { + a.nondecorated:hover { + color: #999; + } +} + +code { + background: #222; + border-radius: 10px; + box-sizing: border-box; + font-family: 'Lucida Console'; + font-size: 8pt; + overflow-y: auto; + padding: 20px; + white-space: pre-line; +} + +button, input[type=submit] { + align-items: center; + background: var(--col-button-pri); + border-radius: 10px; + border: none; + box-sizing: border-box; + color: white; + cursor: pointer; + display: flex; + height: 30px; + margin: 10px 5px 0 5px; + padding: 0 9px 0 9px; + user-select: none; +} + +button:disabled { + color: var(--col-button-disabled) !important; + background: var(--col-button-disabled-bg) !important; +} + +button.warning { + background: var(--col-button-warning); +} + +button > img { + height: 15px; + margin-right: 5px; + width: 15px; +} + +@media (hover: none) and (pointer: coarse) { + button > :not(:first-child) { + display: none; + } + + button > img { + height: 20px; + margin-right: 0; + padding: 8px; + width: 20px; + } +} + +@media (hover: hover) { + button.warning:hover { + background: var(--col-button-warning-hl); + } +} + +button.warning:active { + color: var(--col-button-warning); + background: white; +} + +button.secondary { + background: var(--col-button-sec); +} + +@media (hover: hover) { + button.secondary:hover { + background: var(--col-button-sec-hl); + } +} + +button.secondary:active { + background: white; + color: var(--col-button-sec); +} + +button.secondary:disabled { + color: var(--col-button-sec-disabled) !important; + background: var(--col-button-sec-disabled-bg) !important; +} + +@media (hover: hover) { + button:hover, input[type=submit]:hover { + background: var(--col-button-pri-hl); + } +} + +button:active, input[type=submit]:active { + background: white; + color: var(--col-button-pri); +} + +input, textarea { + background: rgba(0, 0, 0, 0); + border-radius: 5px; + border: 1px solid #aaa; + box-sizing: border-box; + color: white; + margin-bottom: 10px; +} + +input { + height: 25px !important; +} + +/* disable hotkey underlines on mobile devices */ +@media (hover: none) and (pointer: coarse) { + button > u { + text-decoration: none !important; + } +} + +/* necessary for use inside flex containers */ +hr { + width: 100%; +} + +::-webkit-scrollbar { + width: 10px; + height: 10px; +} + +::-webkit-scrollbar-thumb { + background: var(--col-scrollbar); + border-radius: 10px; +} + +@media (hover: hover) { + ::-webkit-scrollbar-thumb:hover { + background: var(--col-scrollbar-hover); + } +} + +::-webkit-scrollbar-corner { + opacity: 0; +} -- cgit v1.3