diff options
| author | Jake Mannens <jake@asger.xyz> | 2026-03-17 03:04:36 +1100 |
|---|---|---|
| committer | Jake Mannens <jake@asger.xyz> | 2026-03-25 01:57:41 +1100 |
| commit | c751709b1b4fe6f16fd84647e8e071455e7b78d6 (patch) | |
| tree | 47734a083d888660606e6cf6cf158c93e69a9807 | |
v0.1av0.1a
81 files changed, 6673 insertions, 0 deletions
diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 0000000..e3d2b85 --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-ef": { + "version": "8.0.23", + "commands": [ + "dotnet-ef" + ], + "rollForward": false + } + } +}
\ No newline at end of file diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..6d8f727 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# CS8618: Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +dotnet_diagnostic.CS8618.severity = silent diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e6e4b24 --- /dev/null +++ b/.gitignore @@ -0,0 +1,365 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +Data/
\ No newline at end of file diff --git a/App.razor b/App.razor new file mode 100644 index 0000000..b4e47c9 --- /dev/null +++ b/App.razor @@ -0,0 +1,19 @@ +<CascadingAuthenticationState> + <Router AppAssembly="@typeof(App).Assembly"> + <Found Context="routeData"> + <AuthorizeRouteView + RouteData="@routeData" + DefaultLayout="@typeof(MainLayout)"> + <NotAuthorized> + <RedirectLogin/> + </NotAuthorized> + </AuthorizeRouteView> + </Found> + <NotFound> + <PageTitle>Not found</PageTitle> + <LayoutView Layout="@typeof(MainLayout)"> + <p role="alert">Sorry, there's nothing at this address.</p> + </LayoutView> + </NotFound> + </Router> +</CascadingAuthenticationState> diff --git a/Controllers/LoginController.cs b/Controllers/LoginController.cs new file mode 100644 index 0000000..b01553c --- /dev/null +++ b/Controllers/LoginController.cs @@ -0,0 +1,50 @@ +using HyperBooru.Services; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Cryptography.KeyDerivation; +using Microsoft.AspNetCore.Mvc; +using System.Security.Claims; + +namespace HyperBooru.Controllers; + +[ApiController] +[Route("/")] +public class LoginController : Controller { + private IHttpContextAccessor httpContextAccessor; + + public LoginController(IHttpContextAccessor httpContextAccessor) => + this.httpContextAccessor = httpContextAccessor; + + [HttpPost("Login")] + public async Task<IActionResult> Login( + [FromForm] string username, + [FromForm] string password, + HBContext db) { + + var user = db.Users.FirstOrDefault(u => u.Username == username); + if(user is null) + return StatusCode(403); + + var hash = UserService.HashPassword(password); + if(hash != user.PasswordHash) + return StatusCode(403); + + var claims = new Claim[] { + new Claim(ClaimTypes.Name, user.Username), + new Claim("ObjectId", user.ObjectId.ToString()) + }; + + var claimsIdentity = new ClaimsIdentity( + claims, + CookieAuthenticationDefaults.AuthenticationScheme); + + var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); + + await httpContextAccessor.HttpContext!.SignInAsync(claimsPrincipal); + return Ok(); + } + + [HttpPost("Logout")] + public async Task Logout() => + await httpContextAccessor.HttpContext!.SignOutAsync(); +} diff --git a/Controllers/MediaController.cs b/Controllers/MediaController.cs new file mode 100644 index 0000000..3368f45 --- /dev/null +++ b/Controllers/MediaController.cs @@ -0,0 +1,113 @@ +using HyperBooru.Services; +using HyperBooru.Util; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru.Controllers; + +[ApiController] +[Route("/media")] +public class MediaController : Controller { + private IMediaService mediaService; + private IConfigService config; + private HBContext db; + + public MediaController( + IMediaService mediaService, + IConfigService config, + HBContext db) { + + 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(); + + 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); + + media = mediaService.Create( + formFile.OpenReadStream(), + formFile.FileName, + formFile.Headers["X-HyperBooru-Checksum"] + .ElementAtOrDefault(0), + lastAccessTime, + lastWriteTime, + createTime, + path, + (PathType?) pathType); + } 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/Dockerfile b/Dockerfile new file mode 100644 index 0000000..463a11d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM mcr.microsoft.com/dotnet/sdk:8.0@sha256:aa05b91be697b83229cb000b90120f0783604ad74ed92a0b45cdf3d1a9c873de AS build +WORKDIR /App + +COPY . ./ +RUN dotnet restore +RUN dotnet publish -o out + +FROM mcr.microsoft.com/dotnet/aspnet:8.0@sha256:4b8f0b08534833b39bb662fb19a65e78cb086f5ca8dd35de3f87026de8885be4 +RUN apt update +RUN apt install -y imagemagick +RUN apt clean +RUN rm -rf /var/lib/apt/lists/* +WORKDIR /App +COPY --from=build /App/out . +ENTRYPOINT [ "dotnet", "HyperBooru.dll" ] @@ -0,0 +1,6 @@ +namespace HyperBooru; + +public enum PathType { + Windows, + Unix +} diff --git a/Exception.cs b/Exception.cs new file mode 100644 index 0000000..1e070eb --- /dev/null +++ b/Exception.cs @@ -0,0 +1,65 @@ +namespace HyperBooru; + +public class HBException : Exception { + public HBException() + : base() {} + public HBException(string message) + : base(message) {} + public HBException(string message, Exception inner) + : base(message, inner) {} +} + +public class ObjectNotFoundException : HBException { + public Guid Guid { get; private init; } + + public ObjectNotFoundException(Guid guid) + : base($"Object not found: {guid}") {} +} + +public class TagException : HBException { + public TagDefinition? TagDefinition { get; private init; } + + public TagException(string message) : base(message) {} + public TagException(string message, TagDefinition tagDefinition) + : base(message) => + TagDefinition = tagDefinition; +} + +public class TagDuplicateException : TagException { + public bool NameExists { get; private init; } + public bool AliasExists { get; private init; } + + public TagDuplicateException(bool nameExists, bool aliasExists) + : base(GenerateMessage(nameExists, aliasExists)) { + + NameExists = nameExists; + AliasExists = aliasExists; + } + + private static string GenerateMessage(bool nameExists, bool aliasExists) { + if(nameExists && aliasExists) + return $"Both tag name and alias already exist!"; + else if(nameExists) + return $"Tag name already exists!"; + else + return $"Tag alias already exists"; + } +} + +public class MediaException : HBException { + public Media? Media { get; private init; } + + public MediaException(string message) : base(message) {} + public MediaException(string message, Media media) : base(message) => + Media = media; +} + +public class MediaCreateException : MediaException { + public MediaCreateException(string message) + : base(message) {} +} + +public class ThumbnailException : MediaException { + public ThumbnailException(string message, Media media) + :base(message, media) {} +} diff --git a/HBContext.cs b/HBContext.cs new file mode 100644 index 0000000..bb0572f --- /dev/null +++ b/HBContext.cs @@ -0,0 +1,84 @@ +using Microsoft.EntityFrameworkCore; +using HyperBooru.Services; + +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<HBObject> Objects { get; set; } + public DbSet<User> Users { get; set; } + public DbSet<TagDefinition> TagDefinitions { get; set; } + public DbSet<Tag> Tags { get; set; } + public DbSet<Media> Media { get; set; } + public DbSet<UploadedFile> UploadedFiles { get; set; } + public DbSet<OcrData> OcrData { get; set; } + + private IConfigService config; + + public HBContext(DbContextOptions<HBContext> 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<HBObject>().ToTable("Objects"); + modelBuilder.Entity<TagDefinition>().ToTable("TagDefinitions"); + modelBuilder.Entity<Tag>().ToTable("Tags"); + modelBuilder.Entity<Media>().ToTable("Media"); + modelBuilder.Entity<UploadedFile>().ToTable("UploadedFiles"); + + // Seed internal tag definitions + // These should NEVER change + modelBuilder.Entity<TagDefinition>().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<User>().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<TagDefinition>() + .HasMany(e => e.ImplicitTags) + .WithMany(); + + modelBuilder.Entity<Media>() + .HasOne(m => m.CurrentUploadedFile) + .WithOne() + .HasForeignKey<Media>("CurrentUploadedFileId"); + } +}
\ No newline at end of file diff --git a/HBObject.cs b/HBObject.cs new file mode 100644 index 0000000..8001ea3 --- /dev/null +++ b/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<Tag> Tags { get; set; } = new(); +}
\ No newline at end of file diff --git a/IDialog.cs b/IDialog.cs new file mode 100644 index 0000000..41e86a8 --- /dev/null +++ b/IDialog.cs @@ -0,0 +1,8 @@ +namespace HyperBooru; + +public interface IDialog { + public bool Visible { get; set; } + + public void Show(); + public void Hide(); +} diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + 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. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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 <https://www.gnu.org/licenses/>. + +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 +<https://www.gnu.org/licenses/>. diff --git a/MainLayout.razor b/MainLayout.razor new file mode 100644 index 0000000..5d68b65 --- /dev/null +++ b/MainLayout.razor @@ -0,0 +1,9 @@ +@inherits LayoutComponentBase + +<link href="@(nameof(HyperBooru)).styles.css" rel="stylesheet" /> + +<Titlebar/> + +<div id="content"> + @Body +</div> diff --git a/MainLayout.razor.css b/MainLayout.razor.css new file mode 100644 index 0000000..0ce15c2 --- /dev/null +++ b/MainLayout.razor.css @@ -0,0 +1,5 @@ +#content { + flex: 1 1 calc(100vh - 59px); + overflow-x: hidden; + overflow-y: auto; +} diff --git a/Media.cs b/Media.cs new file mode 100644 index 0000000..51626be --- /dev/null +++ b/Media.cs @@ -0,0 +1,59 @@ +using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Net.NetworkInformation; + +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<UploadedFile> 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 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 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; } +}
\ No newline at end of file diff --git a/Migrations/20260131125650_InitialMigration.Designer.cs b/Migrations/20260131125650_InitialMigration.Designer.cs new file mode 100644 index 0000000..2e4a05e --- /dev/null +++ b/Migrations/20260131125650_InitialMigration.Designer.cs @@ -0,0 +1,362 @@ +// <auto-generated /> +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 + { + /// <inheritdoc /> + 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<int>("ObjectId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("ObjectId")); + + b.Property<Guid>("Guid") + .HasColumnType("uuid"); + + b.HasKey("ObjectId"); + + b.HasIndex("Guid"); + + b.ToTable("Objects", (string)null); + + b.UseTptMappingStrategy(); + }); + + modelBuilder.Entity("HyperBooru.OcrData", b => + { + b.Property<int>("OcrDataId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("OcrDataId")); + + b.Property<int>("MediaId") + .HasColumnType("integer"); + + b.Property<string>("SearchableText") + .IsRequired() + .HasColumnType("text"); + + b.Property<string>("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property<DateTime>("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.HasKey("OcrDataId"); + + b.HasIndex("MediaId") + .IsUnique(); + + b.ToTable("OcrData"); + }); + + modelBuilder.Entity("TagDefinitionTagDefinition", b => + { + b.Property<int>("ImplicitTagsObjectId") + .HasColumnType("integer"); + + b.Property<int>("TagDefinitionObjectId") + .HasColumnType("integer"); + + b.HasKey("ImplicitTagsObjectId", "TagDefinitionObjectId"); + + b.HasIndex("TagDefinitionObjectId"); + + b.ToTable("TagDefinitionTagDefinition"); + }); + + modelBuilder.Entity("HyperBooru.Media", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property<int?>("CurrentUploadedFileId") + .HasColumnType("integer"); + + b.Property<string>("LongDescription") + .HasColumnType("text"); + + b.Property<string>("ShortDescription") + .HasColumnType("text"); + + b.HasIndex("CurrentUploadedFileId") + .IsUnique(); + + b.ToTable("Media", (string)null); + }); + + modelBuilder.Entity("HyperBooru.Tag", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property<DateTime>("CreateTime") + .HasColumnType("timestamp with time zone"); + + b.Property<int>("TagDefinitionId") + .HasColumnType("integer"); + + b.Property<int>("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<string>("Alias") + .HasColumnType("text"); + + b.Property<string>("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property<string>("Namespace") + .HasColumnType("text"); + + b.Property<int>("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<string>("Checksum") + .IsRequired() + .HasColumnType("text"); + + b.Property<bool>("ChecksumVerified") + .HasColumnType("boolean"); + + b.Property<DateTime?>("CreateTime") + .HasColumnType("timestamp with time zone"); + + b.Property<string>("Filename") + .HasColumnType("text"); + + b.Property<int?>("Height") + .HasColumnType("integer"); + + b.Property<DateTime?>("LastAccessTime") + .HasColumnType("timestamp with time zone"); + + b.Property<DateTime?>("LastWriteTime") + .HasColumnType("timestamp with time zone"); + + b.Property<long>("Length") + .HasColumnType("bigint"); + + b.Property<int>("MediaObjectId") + .HasColumnType("integer"); + + b.Property<string>("MimeType") + .IsRequired() + .HasColumnType("text"); + + b.Property<string>("Path") + .HasColumnType("text"); + + b.Property<int?>("PathType") + .HasColumnType("integer"); + + b.Property<DateTime>("UploadTime") + .HasColumnType("timestamp with time zone"); + + b.Property<int?>("Width") + .HasColumnType("integer"); + + b.HasIndex("MediaObjectId"); + + b.ToTable("UploadedFiles", (string)null); + }); + + modelBuilder.Entity("HyperBooru.User", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property<string>("PasswordHash") + .IsRequired() + .HasColumnType("text"); + + b.Property<string>("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/Migrations/20260131125650_InitialMigration.cs b/Migrations/20260131125650_InitialMigration.cs new file mode 100644 index 0000000..a1a7d8f --- /dev/null +++ b/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 +{ + /// <inheritdoc /> + public partial class InitialMigration : Migration + { + /// <inheritdoc /> + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Objects", + columns: table => new + { + ObjectId = table.Column<int>(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Guid = table.Column<Guid>(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Objects", x => x.ObjectId); + }); + + migrationBuilder.CreateTable( + name: "TagDefinitions", + columns: table => new + { + ObjectId = table.Column<int>(type: "integer", nullable: false), + Source = table.Column<int>(type: "integer", nullable: false), + Namespace = table.Column<string>(type: "text", nullable: true), + Name = table.Column<string>(type: "text", nullable: false), + Alias = table.Column<string>(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<int>(type: "integer", nullable: false), + Username = table.Column<string>(type: "text", nullable: false), + PasswordHash = table.Column<string>(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<int>(type: "integer", nullable: false), + TagDefinitionObjectId = table.Column<int>(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<int>(type: "integer", nullable: false), + TagDefinitionId = table.Column<int>(type: "integer", nullable: false), + CreateTime = table.Column<DateTime>(type: "timestamp with time zone", nullable: false), + TargetObjectId = table.Column<int>(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<int>(type: "integer", nullable: false), + ShortDescription = table.Column<string>(type: "text", nullable: true), + LongDescription = table.Column<string>(type: "text", nullable: true), + CurrentUploadedFileId = table.Column<int>(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<int>(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + MediaId = table.Column<int>(type: "integer", nullable: false), + Text = table.Column<string>(type: "text", nullable: false), + SearchableText = table.Column<string>(type: "text", nullable: false), + Timestamp = table.Column<DateTime>(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<int>(type: "integer", nullable: false), + Checksum = table.Column<string>(type: "text", nullable: false), + ChecksumVerified = table.Column<bool>(type: "boolean", nullable: false), + Filename = table.Column<string>(type: "text", nullable: true), + Length = table.Column<long>(type: "bigint", nullable: false), + MimeType = table.Column<string>(type: "text", nullable: false), + Width = table.Column<int>(type: "integer", nullable: true), + Height = table.Column<int>(type: "integer", nullable: true), + UploadTime = table.Column<DateTime>(type: "timestamp with time zone", nullable: false), + LastAccessTime = table.Column<DateTime>(type: "timestamp with time zone", nullable: true), + LastWriteTime = table.Column<DateTime>(type: "timestamp with time zone", nullable: true), + CreateTime = table.Column<DateTime>(type: "timestamp with time zone", nullable: true), + Path = table.Column<string>(type: "text", nullable: true), + PathType = table.Column<int>(type: "integer", nullable: true), + MediaObjectId = table.Column<int>(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"); + } + + /// <inheritdoc /> + 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/Migrations/HBContextModelSnapshot.cs b/Migrations/HBContextModelSnapshot.cs new file mode 100644 index 0000000..422037f --- /dev/null +++ b/Migrations/HBContextModelSnapshot.cs @@ -0,0 +1,359 @@ +// <auto-generated /> +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<int>("ObjectId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("ObjectId")); + + b.Property<Guid>("Guid") + .HasColumnType("uuid"); + + b.HasKey("ObjectId"); + + b.HasIndex("Guid"); + + b.ToTable("Objects", (string)null); + + b.UseTptMappingStrategy(); + }); + + modelBuilder.Entity("HyperBooru.OcrData", b => + { + b.Property<int>("OcrDataId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("OcrDataId")); + + b.Property<int>("MediaId") + .HasColumnType("integer"); + + b.Property<string>("SearchableText") + .IsRequired() + .HasColumnType("text"); + + b.Property<string>("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property<DateTime>("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.HasKey("OcrDataId"); + + b.HasIndex("MediaId") + .IsUnique(); + + b.ToTable("OcrData"); + }); + + modelBuilder.Entity("TagDefinitionTagDefinition", b => + { + b.Property<int>("ImplicitTagsObjectId") + .HasColumnType("integer"); + + b.Property<int>("TagDefinitionObjectId") + .HasColumnType("integer"); + + b.HasKey("ImplicitTagsObjectId", "TagDefinitionObjectId"); + + b.HasIndex("TagDefinitionObjectId"); + + b.ToTable("TagDefinitionTagDefinition"); + }); + + modelBuilder.Entity("HyperBooru.Media", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property<int?>("CurrentUploadedFileId") + .HasColumnType("integer"); + + b.Property<string>("LongDescription") + .HasColumnType("text"); + + b.Property<string>("ShortDescription") + .HasColumnType("text"); + + b.HasIndex("CurrentUploadedFileId") + .IsUnique(); + + b.ToTable("Media", (string)null); + }); + + modelBuilder.Entity("HyperBooru.Tag", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property<DateTime>("CreateTime") + .HasColumnType("timestamp with time zone"); + + b.Property<int>("TagDefinitionId") + .HasColumnType("integer"); + + b.Property<int>("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<string>("Alias") + .HasColumnType("text"); + + b.Property<string>("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property<string>("Namespace") + .HasColumnType("text"); + + b.Property<int>("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<string>("Checksum") + .IsRequired() + .HasColumnType("text"); + + b.Property<bool>("ChecksumVerified") + .HasColumnType("boolean"); + + b.Property<DateTime?>("CreateTime") + .HasColumnType("timestamp with time zone"); + + b.Property<string>("Filename") + .HasColumnType("text"); + + b.Property<int?>("Height") + .HasColumnType("integer"); + + b.Property<DateTime?>("LastAccessTime") + .HasColumnType("timestamp with time zone"); + + b.Property<DateTime?>("LastWriteTime") + .HasColumnType("timestamp with time zone"); + + b.Property<long>("Length") + .HasColumnType("bigint"); + + b.Property<int>("MediaObjectId") + .HasColumnType("integer"); + + b.Property<string>("MimeType") + .IsRequired() + .HasColumnType("text"); + + b.Property<string>("Path") + .HasColumnType("text"); + + b.Property<int?>("PathType") + .HasColumnType("integer"); + + b.Property<DateTime>("UploadTime") + .HasColumnType("timestamp with time zone"); + + b.Property<int?>("Width") + .HasColumnType("integer"); + + b.HasIndex("MediaObjectId"); + + b.ToTable("UploadedFiles", (string)null); + }); + + modelBuilder.Entity("HyperBooru.User", b => + { + b.HasBaseType("HyperBooru.HBObject"); + + b.Property<string>("PasswordHash") + .IsRequired() + .HasColumnType("text"); + + b.Property<string>("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/Pages/Component/AboutDialog.razor b/Pages/Component/AboutDialog.razor new file mode 100644 index 0000000..9ffbad4 --- /dev/null +++ b/Pages/Component/AboutDialog.razor @@ -0,0 +1,709 @@ +@using System.Reflection +@using Microsoft.AspNetCore.Hosting +@inject IHostingEnvironment hostingEnvironment +@implements IDialog + +<Dialog @ref=dialog> + <p id="title">@Title</p> + <p id="author">Created by Jake Mannens</p> + <div id="license"> + <center>GNU AFFERO GENERAL PUBLIC LICENSE</center><br/> + <center>Version 3, 19 November 2007</center> + <br/><br/> + Copyright (C) 2007 Free Software Foundation, Inc. + <<a href="https://fsf.org/" target="_blank">https://fsf.org/</a>> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + <br/><br/> + <center>Preamble</center> + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + The precise terms and conditions for copying, distribution and + modification follow. + <br/><br/> + <center>TERMS AND CONDITIONS</center> + <br/><br/> + 0. Definitions. + <br/><br/> + "This License" refers to version 3 of the GNU Affero General Public License. + <br/><br/> + "Copyright" also means copyright-like laws that apply to other kinds of + works, such as semiconductor masks. + <br/><br/> + "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. + <br/><br/> + 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. + <br/><br/> + A "covered work" means either the unmodified Program or a work based + on the Program. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 1. Source Code. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + The Corresponding Source need not include anything that users + can regenerate automatically from other parts of the Corresponding + Source. + <br/><br/> + The Corresponding Source for a work in source code form is that + same work. + <br/><br/> + 2. Basic Permissions. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + Conveying under any other circumstances is permitted solely under + the conditions stated below. Sublicensing is not allowed; section 10 + makes it unnecessary. + <br/><br/> + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 4. Conveying Verbatim Copies. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 5. Conveying Modified Source Versions. + <br/><br/> + 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: + <br/><br/> + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + <br/><br/> + 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". + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 6. Conveying Non-Source Forms. + <br/><br/> + 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: + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + "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. + <br/><br/> + 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). + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 7. Additional Terms. + <br/><br/> + "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. + <br/><br/> + 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. + <br/><br/> + 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: + <br/><br/> + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + <br/><br/> + 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 + <br/><br/> + 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 + <br/><br/> + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + <br/><br/> + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 8. Termination. + <br/><br/> + 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). + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 9. Acceptance Not Required for Having Copies. + <br/><br/> + 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. + <br/><br/> + 10. Automatic Licensing of Downstream Recipients. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 11. Patents. + <br/><br/> + 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". + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 12. No Surrender of Others' Freedom. + <br/><br/> + 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. + <br/><br/> + 13. Remote Network Interaction; Use with the GNU General Public License. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 14. Revised Versions of this License. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + 15. Disclaimer of Warranty. + <br/><br/> + 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. + <br/><br/> + 16. Limitation of Liability. + <br/><br/> + 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. + <br/><br/> + 17. Interpretation of Sections 15 and 16. + <br/><br/> + 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. + <br/><br/> + <center>END OF TERMS AND CONDITIONS</center> + <br/><br/> + <center>How to Apply These Terms to Your New Programs</center> + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + <br/><br/> + 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. + <br/><br/> + 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. + <br/><br/> + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see + <<a href="https://www.gnu.org/licenses/" target="_blank">https://www.gnu.org/licenses/</a>>. + <br/><br/> + Also add information on how to contact you by electronic and paper mail. + <br/><br/> + 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. + <br/><br/> + 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 + <<a href="https://www.gnu.org/licenses/" target="_blank">https://www.gnu.org/licenses/</a>>. + </div> + <a href="https://gitlab.com/plasmicplexus/HyperBooru-Server" target="_blank">Source</a> + <ButtonContainer> + <button @onclick=Hide>Close</button> + </ButtonContainer> +</Dialog> + +@code { + private Dialog dialog; + + public bool Visible { + get => dialog.Visible; + set => dialog.Visible = value; + } + + public void Show() => Visible = true; + public void Hide() => Visible = false; + + public string Title => + $"HyperBooru v{Version} {Development}"; + + public string? Version => + GetType() + .Assembly + .GetCustomAttribute<AssemblyInformationalVersionAttribute>()? + .InformationalVersion; + + public string? Development { + get { + #if DEBUG + return "(Development)"; + #else + return hostingEnvironment.IsDevelopment() ? "(Development)" : null; + #endif + } + } +} diff --git a/Pages/Component/AboutDialog.razor.css b/Pages/Component/AboutDialog.razor.css new file mode 100644 index 0000000..0a523a4 --- /dev/null +++ b/Pages/Component/AboutDialog.razor.css @@ -0,0 +1,18 @@ +p#title { + margin-bottom: 0; +} + +p#author { + font-size: 8pt; +} + +div#license { + background: #222; + border-radius: 10px; + box-sizing: border-box; + font-family: 'Lucida Console'; + font-size: 8pt; + max-height: 300px; + overflow-y: auto; + padding: 20px; +} diff --git a/Pages/Component/ButtonContainer.razor b/Pages/Component/ButtonContainer.razor new file mode 100644 index 0000000..a631dcc --- /dev/null +++ b/Pages/Component/ButtonContainer.razor @@ -0,0 +1,8 @@ +<div> + @ChildContent +</div> + +@code { + [Parameter] + public RenderFragment ChildContent { get; set; } +} diff --git a/Pages/Component/ButtonContainer.razor.css b/Pages/Component/ButtonContainer.razor.css new file mode 100644 index 0000000..6de94c7 --- /dev/null +++ b/Pages/Component/ButtonContainer.razor.css @@ -0,0 +1,4 @@ +div { + display: flex; + justify-content: flex-end; +} diff --git a/Pages/Component/Dialog.razor b/Pages/Component/Dialog.razor new file mode 100644 index 0000000..673ec2f --- /dev/null +++ b/Pages/Component/Dialog.razor @@ -0,0 +1,70 @@ +@inject IJSRuntime jsRuntime +@implements IDialog + +<div + class="dialog" + onmousedown="dialogMouseDown(event)" + style="opacity:0;visibility:hidden;@(heightStyle)" + @ref=dialogDiv> + @if(Title is not null) { + <div class="titlebar" onmousedown="dialogTitleMouseDown(event)"> + <p class="title">@Title</p> + <hr/> + </div> + } + <div class="content"> + @ChildContent + </div> +</div> + +@code { + [Parameter] + public string? Title { get; set; } + + [Parameter] + public RenderFragment ChildContent { get; set; } + + [Parameter] + public int HeightPixels { set => height = $"{value}px"; } + [Parameter] + public int HeightPercent { set => height = $"{value}%"; } + + public bool Visible { + get => visible; + set { + visible = value; + jsRuntime.InvokeVoidAsync( + "setDialogVisibility", + new object?[] { dialogDiv, value }); + } + } + + private bool visible = false; + + private string? height; + + private ElementReference dialogDiv; + + public void Show() => Visible = true; + public void Hide() => Visible = false; + + protected override async void OnAfterRender(bool firstRender) { + if(firstRender) { + await jsRuntime.InvokeVoidAsync("dialogAddObjectReference", new object[] { + dialogDiv, + DotNetObjectReference.Create(this) + }); + } + } + + [JSInvokable("KeyHandler")] + public void KeyHandler(string key) { + if(key == "Escape") { + Hide(); + return; + } + } + + private string heightStyle => + $"{(height is null ? "" : $"max-height:{height};")}"; +} diff --git a/Pages/Component/Dialog.razor.css b/Pages/Component/Dialog.razor.css new file mode 100644 index 0000000..1447407 --- /dev/null +++ b/Pages/Component/Dialog.razor.css @@ -0,0 +1,35 @@ +div.dialog { + background: var(--col-dialog-bg); + border-radius: 20px; + box-shadow: 0px 5px 10px 10px rgb(0 0 0 / 25%); + display: flex; + flex-direction: column; + left: 50%; + padding: 0; + position: absolute; + top: 50%; + transform: translate(-50%, -50%); + transition: visibility 0.1s, opacity 0.1s linear; + width: 450px; + z-index: 1000; +} + +hr { + margin: 0; +} + +div.titlebar { + cursor: grab; +} + +div.titlebar p.title { + font-size: 10pt; + margin: 0; + padding: 10px 20px 10px 20px; +} + +div.content { + display: flex; + flex-direction: column; + padding: 20px; +} diff --git a/Pages/Component/MediaTagTable.razor b/Pages/Component/MediaTagTable.razor new file mode 100644 index 0000000..e367f7f --- /dev/null +++ b/Pages/Component/MediaTagTable.razor @@ -0,0 +1,72 @@ +@inject IDbContextFactory<HBContext> dbFactory +@inject ITagService tagService + +<link rel="stylesheet" href="@(nameof(HyperBooru)).styles.css"/> + +<table class="data-table"> + <tr> + <th>Namespace</th> + <th>Tag Name</th> + <th></th> + </tr> + @foreach(var e in tagDefs) { + <tr> + <td> + @if(e.isImplicit) { + <i>@e.tagDef.Namespace</i> + } else { + @e.tagDef.Namespace + } + </td> + <td> + <a href="/Gallery?q=@(e.tagDef.Name)" class="nondecorated"> + @if(e.isImplicit) { + <i>@e.tagDef.Name</i> + } else { + @e.tagDef.Name + } + </a> + </td> + <td> + @if(!e.isImplicit) { + <a href="javascript:;" @onclick=@(() => Delete(e.tagDef))>Delete</a> + } else { + <a href="javascript:;" @onclick=@(() => MakeExplicit(e.tagDef))>Make Explicit</a> + } + </td> + </tr> + } +</table> + +@code { + [Parameter] + public Media Media { get; set; } + + private (TagDefinition tagDef, bool isImplicit)[] tagDefs; + + protected override void OnInitialized() => LoadTagDefs(); + + public void Refresh() { + LoadTagDefs(); + StateHasChanged(); + } + + private void Delete(TagDefinition tagDef) { + tagService.RemoveTag(Media.Guid, tagDef.Guid); + Refresh(); + } + + private void LoadTagDefs() { + using var db = dbFactory.CreateDbContext(); + var media = db.Media.First(m => m.ObjectId == Media.ObjectId); + + tagDefs = tagService.GetAllTags(Media) + .Where(e => e.tagDefinition.Source == TagSource.UserTag) + .ToArray(); + } + + private void MakeExplicit(TagDefinition tagDef) { + tagService.AddTag(Media, tagDef); + Refresh(); + } +} diff --git a/Pages/Component/MediaTagTable.razor.css b/Pages/Component/MediaTagTable.razor.css new file mode 100644 index 0000000..dcf5e09 --- /dev/null +++ b/Pages/Component/MediaTagTable.razor.css @@ -0,0 +1,3 @@ +td { + font-size: 8pt; +} diff --git a/Pages/Component/NsfwSwitch.razor b/Pages/Component/NsfwSwitch.razor new file mode 100644 index 0000000..b96606d --- /dev/null +++ b/Pages/Component/NsfwSwitch.razor @@ -0,0 +1,8 @@ +@inject IUserService userService + +<Switch InitialValue=userService.UserSessionState.ShowNsfw OnToggle=ToggleNsfw/> + +@code { + private void ToggleNsfw(bool showNsfw) => + userService.UserSessionState.ShowNsfw = showNsfw; +}
\ No newline at end of file diff --git a/Pages/Component/RedirectLogin.razor b/Pages/Component/RedirectLogin.razor new file mode 100644 index 0000000..290a7ac --- /dev/null +++ b/Pages/Component/RedirectLogin.razor @@ -0,0 +1,6 @@ +@inject NavigationManager navigationManager + +@code { + protected override void OnInitialized() => + navigationManager.NavigateTo("/Login", true); +}
\ No newline at end of file diff --git a/Pages/Component/Switch.razor b/Pages/Component/Switch.razor new file mode 100644 index 0000000..d11ac81 --- /dev/null +++ b/Pages/Component/Switch.razor @@ -0,0 +1,20 @@ +<link rel="stylesheet" href="@(nameof(HyperBooru)).styles.css"/> + +<label> + <input + type="checkbox" + checked=@InitialValue + @onchange=@(e => OnToggle.InvokeAsync((e.Value as bool?) ?? false)) + hidden/> + <div class="switch-outer"> + <div class="switch-inner"/> + </div> +</label> + +@code { + [Parameter] + public bool InitialValue { get; set; } = false; + + [Parameter] + public EventCallback<bool> OnToggle { get; set; } +} diff --git a/Pages/Component/Switch.razor.css b/Pages/Component/Switch.razor.css new file mode 100644 index 0000000..6b1f5d5 --- /dev/null +++ b/Pages/Component/Switch.razor.css @@ -0,0 +1,25 @@ +div.switch-outer { + background: var(--col-switch-bg); + border-radius: 20px; + border: 1px solid var(--col-switch-fg); + cursor: pointer; + height: 20px; + transition: background 0.1s linear; + width: 40px; +} + +div.switch-inner { + background: var(--col-switch-fg); + border-radius: 20px; + height: 20px; + transition: margin-left 0.1s linear; + width: 20px; +} + +input:checked + div.switch-outer { + background: var(--col-switch-bg-hl); +} + +input:checked + div.switch-outer > div.switch-inner { + margin-left: 20px; +} diff --git a/Pages/Component/TabContainer.razor b/Pages/Component/TabContainer.razor new file mode 100644 index 0000000..3caab0b --- /dev/null +++ b/Pages/Component/TabContainer.razor @@ -0,0 +1,35 @@ +<link rel="stylesheet" href="@(nameof(HyperBooru)).styles.css"/> + +<div class="tabs"> + @foreach(var pane in Panes) { + <a href="javascript:;" @onclick=@(() => ActivePane = pane) class="@(pane == ActivePane ? "selected" : "")"> + @pane.Title + </a> + } +</div> + +<CascadingValue Value="this"> + @ChildContent +</CascadingValue> + +@code { + [Parameter] + public RenderFragment ChildContent { get; set; } + + public TabPane? ActivePane { get; set; } + List<TabPane> Panes = new(); + + public void AddPane(TabPane tabPane) { + Panes.Add(tabPane); + if(Panes.Count == 1) + ActivePane = tabPane; + StateHasChanged(); + } + + public void RemovePane(TabPane tabPane) { + if(ActivePane == tabPane) + ActivePane = Panes.ElementAtOrDefault(0); + Panes.Remove(tabPane); + StateHasChanged(); + } +}
\ No newline at end of file diff --git a/Pages/Component/TabContainer.razor.css b/Pages/Component/TabContainer.razor.css new file mode 100644 index 0000000..6a56021 --- /dev/null +++ b/Pages/Component/TabContainer.razor.css @@ -0,0 +1,19 @@ +div.tabs { + display: inherit !important; + border-bottom: 1px solid white; +} + +div.tabs > a { + display: inline-block; + padding: 10px 10px 9px 10px; +} + +div.tabs > a.selected { + border-bottom: 4px solid white; + padding-bottom: 5px; +} + +div.tabs > a:hover { + background: rgba(255, 255, 255, 0.4); + filter: none; +} diff --git a/Pages/Component/TabPane.razor b/Pages/Component/TabPane.razor new file mode 100644 index 0000000..ba4a13a --- /dev/null +++ b/Pages/Component/TabPane.razor @@ -0,0 +1,29 @@ +@implements IDisposable + +<link rel="stylesheet" href="@(nameof(HyperBooru)).styles.css"/> + +@if(Parent.ActivePane == this) { + @ChildContent +} + +@code { + [CascadingParameter] + private TabContainer Parent { get; set; } + + [Parameter] + public string Title { get; set; } + + [Parameter] + public RenderFragment ChildContent { get; set; } + + protected override void OnInitialized() { + if (Parent is null) + throw new ArgumentNullException(nameof(Parent), "TabPane must exist within a TabContainer"); + + Parent.AddPane(this); + } + + public void Dispose() { + Parent.RemovePane(this); + } +}
\ No newline at end of file diff --git a/Pages/Component/TabPane.razor.css b/Pages/Component/TabPane.razor.css new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/Pages/Component/TabPane.razor.css @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/Pages/Component/TagEditDialog.razor b/Pages/Component/TagEditDialog.razor new file mode 100644 index 0000000..2e443d4 --- /dev/null +++ b/Pages/Component/TagEditDialog.razor @@ -0,0 +1,96 @@ +@inject IDbContextFactory<HBContext> dbFactory; +@inject ITagService tagService +@implements IDialog + +<Dialog Title=@Title @ref=dialog> + <label> + Name + @if(nameExists) { + <p class="error">Tag with that name already exists!</p> + } + </label> + <input type="text" @bind=tagName required/> + <label>Namespace</label> + <input type="text" @bind=tagNamespace/> + <label> + Alias + @if(aliasExists) { + <p class="error">Tag with that alias already exists!</p> + } + </label> + <input type="text" @bind=tagAlias/> + <ButtonContainer> + <button @onclick=Hide class="secondary">Cancel</button> + <button @onclick=Submit>@(TagDefinition is null ? "Create" : "Apply")</button> + </ButtonContainer> +</Dialog> + +@code { + [Parameter] + public TagDefinition? TagDefinition { get; set; } + + [Parameter] + public EventHandler OnTagUpdate { get; set; } + + public bool Visible { + get => visible; + set { + if(value) + Load(); + visible = dialog.Visible = value; + } + } + + private string Title => + TagDefinition is null ? "Create a new tag definition" : "Edit tag definition"; + + private Dialog dialog; + + private string? tagName; + private string? tagNamespace; + private string? tagAlias; + + private bool nameExists = false; + private bool aliasExists = false; + + private bool visible = false; + + public void Show() => Visible = true; + public void Hide() => Visible = false; + + public void Show(TagDefinition? toEdit) { + TagDefinition = toEdit; + Visible = true; + } + + public void Show(string? @namespace) { + TagDefinition = null; + Visible = true; + tagNamespace = @namespace; + } + + private void Load() { + tagName = TagDefinition?.Name; + tagNamespace = TagDefinition?.Namespace; + tagAlias = TagDefinition?.Alias; + nameExists = false; + aliasExists = false; + } + + private void Submit() { + try { + if(TagDefinition is null) { + tagService.CreateTagDefinition(tagName, tagNamespace, tagAlias); + } else { + tagService.UpdateTagDefinition(TagDefinition, tagName, tagNamespace, tagAlias); + } + } catch(TagDuplicateException e) { + nameExists = e.NameExists; + aliasExists = e.AliasExists; + return; + } + + OnTagUpdate.Invoke(this, new EventArgs()); + Hide(); + } +} diff --git a/Pages/Component/TagEditDialog.razor.css b/Pages/Component/TagEditDialog.razor.css new file mode 100644 index 0000000..02781c0 --- /dev/null +++ b/Pages/Component/TagEditDialog.razor.css @@ -0,0 +1,11 @@ +p.error { + color: var(--col-error-pri); + display: inline; + font-size: 8pt; + margin-left: 5px; + vertical-align: middle; +} + +input { + width: 100%; +} diff --git a/Pages/Component/TagSelectDialog.razor b/Pages/Component/TagSelectDialog.razor new file mode 100644 index 0000000..20be31e --- /dev/null +++ b/Pages/Component/TagSelectDialog.razor @@ -0,0 +1,183 @@ +@inject IDbContextFactory<HBContext> dbFactory +@inject ITagService tagService +@inject IUserService userService +@implements IDisposable +@implements IDialog + +<link rel="stylesheet" href="@(nameof(HyperBooru)).styles.css"/> + +<Dialog Title=@(Title ?? "Select one or more tag(s)") @ref=dialog> + <input type="text" placeholder="Search" @ref=queryInput @oninput=QueryInput @onkeypress=QueryKey value=@query/> + <div class="tag-definitions"> + @for(int i = 0; i < tagDefinitions.Count(); i++) { + if(!MatchesQuery(tagDefinitions[i].tagDefinition)) + continue; + var local = i; + var ns = tagDefinitions[i].tagDefinition.Namespace; + var alias = tagDefinitions[i].tagDefinition.Alias; + var title = string.Join(" ", new[] { + ns, + alias is not null ? $"({alias})" : null + }); + <input + type="checkbox" + id="tagDef-@tagDefinitions[i].tagDefinition.Guid" + @bind=tagDefinitions[local].selected /> + <label + for="tagDef-@tagDefinitions[i].tagDefinition.Guid" + title=@title> + @tagDefinitions[i].tagDefinition.Name + </label> + } + </div> + <ButtonContainer> + <button @onclick=@(() => dialog.Hide()) class="secondary">Cancel</button> + <button @onclick=@(() => Submit())>Accept</button> + </ButtonContainer> +</Dialog> + +@code { + [Parameter] + public string? Title { get; set; } + + [Parameter] + public EventCallback<TagDefinition[]> OnSubmit { get; set; } + + public TagDefinition[] SelectedTags { get; set; } = + Array.Empty<TagDefinition>(); + + public bool Visible { + get => visible; + set { + if(value) + LoadTags(); + query = null; + visible = dialog.Visible = value; + } + } + + private (TagDefinition tagDefinition, bool selected)[] tagDefinitions; + + private HBContext db; + + private Dialog dialog; + + private bool visible; + + private string? query; + private ElementReference queryInput; + + public void Show() => Visible = true; + public void Hide() => Visible = false; + + protected override void OnInitialized() { + userService.UserSessionState.OnStateChange += ShowNsfwChanged; + LoadTags(); + } + + private void LoadTags() { + db = dbFactory.CreateDbContext(); + + var selected = SelectedTags.Select(td => td.Guid); + + int[] nsfwTags = Array.Empty<int>(); + if(!userService.UserSessionState.ShowNsfw) + nsfwTags = tagService.TagsThatImply(HBContext.NsfwTag) + .Select(td => td.ObjectId) + .ToArray(); + + tagDefinitions = db.TagDefinitions + .Include(td => td.ImplicitTags) + .Where(td => td.Source == TagSource.UserTag) + .OrderBy(td => td.Name) + .AsEnumerable() + .Where(td => userService.UserSessionState.ShowNsfw || !td.ImplicitTags + .IntersectBy(nsfwTags, td => td.ObjectId) + .Any()) + .Select(td => new Tuple<TagDefinition, bool>( + td, + selected.Contains(td.Guid)).ToValueTuple()) + .ToArray(); + } + + private void QueryInput(ChangeEventArgs e) { + query = (string?) e.Value; + StateHasChanged(); + } + + private void QueryKey(KeyboardEventArgs e) { + if(e.Code != "Enter" && e.Code != "NumpadEnter") + return; + + if(string.IsNullOrEmpty(query)) { + Submit(); + return; + } + + int c = 0; + int? last = null; + for(int i = 0; i < tagDefinitions.Count(); i++) { + if(!MatchesQuery(tagDefinitions[i].tagDefinition)) + continue; + last = i; + c++; + } + + if(c == 1 && last is not null) + tagDefinitions[(int) last].selected = + !tagDefinitions[(int) last].selected; + + query = null; + StateHasChanged(); + } + + private bool MatchesQuery(TagDefinition tagDef) { + TagDefinition? singleTag = null; + + if(string.IsNullOrEmpty(query)) + return true; + + singleTag = tagDefinitions.FirstOrDefault( + e => string.Equals( + e.tagDefinition.Alias, + query, + StringComparison.OrdinalIgnoreCase)).tagDefinition; + + if(singleTag is not null) + return tagDef.Guid == singleTag.Guid; + + singleTag = tagDefinitions.FirstOrDefault( + e => string.Equals( + e.tagDefinition.Name, + query, + StringComparison.OrdinalIgnoreCase)).tagDefinition; + + if(singleTag is not null) + return tagDef.Guid == singleTag.Guid; + + return tagDef.Name.ToLower().Contains(query.ToLower()); + } + + private async void Submit() { + await OnSubmit.InvokeAsync( + tagDefinitions + .Where(e => e.selected) + .Select(e => e.tagDefinition) + .ToArray()); + for(int i = 0; i < tagDefinitions.Count(); i++) + tagDefinitions[i].selected = false; + Hide(); + StateHasChanged(); + } + + public async void ShowNsfwChanged(UserSessionState userSessionState) => + await InvokeAsync(() => { + LoadTags(); + StateHasChanged(); + }); + + public void Dispose() { + db.Dispose(); + userService.UserSessionState.OnStateChange -= ShowNsfwChanged; + } +} diff --git a/Pages/Component/TagSelectDialog.razor.css b/Pages/Component/TagSelectDialog.razor.css new file mode 100644 index 0000000..7b50077 --- /dev/null +++ b/Pages/Component/TagSelectDialog.razor.css @@ -0,0 +1,27 @@ +div.tag-definitions { + max-height: 450px; + overflow-y: auto; + user-select: none; +} + +div.tag-definitions label { + background: #555; + border-radius: 10px; + display: inline-block; + font-size: 10pt; + margin: 0 5px 5px 0; + padding: 5px 7px 5px 7px; + transition: background 0.1s linear; +} + +div.tag-definitions label:hover { + background: #777; +} + +div.tag-definitions input:checked + label { + background: #aaa; +} + +div.tag-definitions input { + display: none; +} diff --git a/Pages/Component/Titlebar.razor b/Pages/Component/Titlebar.razor new file mode 100644 index 0000000..8033413 --- /dev/null +++ b/Pages/Component/Titlebar.razor @@ -0,0 +1,77 @@ +@inject IJSRuntime jsRuntime +@inject IUserService userService + +<script suppress-error="BL9992"> + async function login() { + var username = document.querySelector('input#username'); + var password = document.querySelector('input#password'); + + var formData = new FormData(); + formData.append('username', username.value); + formData.append('password', password.value); + + var resp = await fetch('/Login', { + method: 'POST', + body: formData + }); + + if(resp.ok) { + window.location.href = '/'; + } else if(resp.status == 403) { + var form = document.querySelector('form.login'); + form.classList.remove('bad-login'); + @* TODO: improve this hacky method of triggering reflow *@ + form.offsetWidth; + form.classList.add('bad-login'); + username.value = password.value = null; + username.focus(); + } else { + alert('Unknown error while attempting to login!'); + } + } + + async function logout() { + var resp = await fetch('/Logout', { method: 'POST' }); + if(resp.ok) { + window.location.href = '/Login'; + } else { + alert('Error logging out!'); + } + } +</script> + +<AuthorizeView> + <Authorized> + <div id="navbar"> + <a href="/">Home</a> + <a href="/TagDefinitions">Tags</a> + <a href="/Gallery?ingest=true">Ingest</a> + <a href="/Upload">Upload</a> + <a href="javascript:;" @onclick=@(() => aboutDialog.Show())>About</a> + + <p id="nsfw-label">NSFW</p> + <div id="nsfw-switch"> + <NsfwSwitch/> + </div> + <form action="/Gallery" method="get"> + <input type="text" name="q" placeholder="Search"/> + </form> + <a href="javascript:logout();">Logout</a> + </div> + <AboutDialog @ref=aboutDialog/> + </Authorized> + <NotAuthorized> + <div id="navbar"> + <h2>Login</h2> + <form class="login" action="javascript:login();"> + <input id="username" placeholder="Username" type="text"/> + <input id="password" placeholder="Password" type="password"/> + </form> + <a href="javascript:login();">Login</a> + </div> + </NotAuthorized> +</AuthorizeView> + +@code { + private AboutDialog aboutDialog; +} diff --git a/Pages/Component/Titlebar.razor.css b/Pages/Component/Titlebar.razor.css new file mode 100644 index 0000000..ea10740 --- /dev/null +++ b/Pages/Component/Titlebar.razor.css @@ -0,0 +1,79 @@ +div#navbar { + align-items: center; + background: var(--col-navbar-bg); + box-shadow: rgba(0, 0, 0, 0.5) 0px 10px 10px; + display: flex; + height: 59px; + z-index: 100; +} + +div#navbar > h2 { + margin-left: 20px; +} + +div#navbar > a { + align-items: center; + color: white; + display: flex; + height: 100%; + padding: 0 20px 0 20px; +} + +div#navbar > a:hover { + background: rgba(255, 255, 255, 0.4); + filter: none; +} + +div#navbar > a:active { + background: #fff; + color: var(--col-navbar-bg); +} + +p#nsfw-label { + align-self: center; + font-size: 9pt; + margin-left: auto; +} + +div#nsfw-switch { + align-self: center; + margin-left: 10px; +} + +form { + display: flex; + margin: 0 20px 0 20px; + min-width: 30%; +} + +form.login { + margin-left: auto; +} + +form.login.bad-login { + animation-iteration-count: 3; + animation-timing-function: linear; + animation: bad-login 0.2s; +} + +@keyframes bad-login { + 0% { transform: translateX(0); } + 33% { transform: translateX(-20px); } + 66% { transform: translateX(+20px); } + 100% { transform: translateX(0); } +} + +input[type="text"], input[type="password"] { + align-self: center; + background: var(--col-bg); + border-radius: 0; + color: white; + font-size: 12pt; + height: 40px !important; + margin: 0; + width: 100%; +} + +input[type="password"] { + margin-left: 20px; +} diff --git a/Pages/Gallery.razor b/Pages/Gallery.razor new file mode 100644 index 0000000..762ef7f --- /dev/null +++ b/Pages/Gallery.razor @@ -0,0 +1,149 @@ +@page "/" +@page "/Gallery" +@inject IDbContextFactory<HBContext> dbFactory +@inject ITagService tagService +@inject ISearchService searchService +@inject IUserService userService +@inject IJSRuntime jsRuntime +@implements IDisposable +@attribute [Authorize] + +<PageTitle>@Title</PageTitle> + +@if(Ingest && !userService.UserSessionState.ShowNsfw) { + <div id="ingest-warning"> + <p><center>Ingest feed is not available unless NSFW mode is enabled!</center></p> + <p><center><i>You must enable NSFW mode to continue...</i></center></p> + </div> +} + +<div style="padding:var(--size-default-gap);"> + @foreach(var media in displayMedia) { + // Precalculate thumbnail size to help the browser + // lay out the images during initial page load + int width = (int) media.CurrentUploadedFile.Width! * 200 / (int) media.CurrentUploadedFile.Height!; + <a href="/ViewMedia?m=@(media.Guid)"> + <img src="/media/thumb/@(media.Guid)?h=200" width=@width height="200"/> + </a> + } +</div> + +<div id="canary"/> + +<script suppress-error="BL9992"> + function registerScrollObserver(dotNetObject) { + var scrollObserver = new IntersectionObserver( + async (e) => { + if(e[0].isIntersecting) { + await dotNetObject.invokeMethodAsync('LoadMore'); + } + }, + { threshold: [1] }); + scrollObserver.observe(document.getElementById("canary")); + } +</script> + +@code { + [Parameter] + [SupplyParameterFromQuery(Name = "q")] + public string? Query { get; set; } + + [Parameter] + [SupplyParameterFromQuery] + public bool Ingest { get; set; } = false; + + public const int PageSize = 50; + + private string Title { + get { + if(Query is null) + return Ingest ? "Ingest Feed" : "Gallery"; + else + return "Search Results"; + } + } + + private List<Media> displayMedia; + private Media[] queryResult; + private IEnumerator<Media> mediaEnumerator; + + protected override void OnInitialized() => + userService.UserSessionState.OnStateChange += ShowNsfwChanged; + + protected override void OnParametersSet() => LoadMedia(); + + protected override void OnAfterRender(bool firstRender) { + if(firstRender) + jsRuntime.InvokeVoidAsync( + "registerScrollObserver", + DotNetObjectReference.Create(this)); + } + + private void LoadMedia() { + using var db = dbFactory.CreateDbContext(); + + if(Query is not null) { + queryResult = searchService.Search(Query) + .OrderByDescending(m => m.ObjectId) + .ToArray(); + } else { + queryResult = db.Media + .Include(m => m.Tags) + .Include(m => m.CurrentUploadedFile) + .OrderByDescending(m => m.ObjectId) + .ToArray(); + } + + mediaEnumerator = FilterMedia(queryResult).GetEnumerator(); + + displayMedia = new(); + + LoadMore(); + } + + [JSInvokable("LoadMore")] + public void LoadMore() { + for(int i = 0; i < PageSize; i++) { + if(!mediaEnumerator.MoveNext()) + break; + displayMedia.Add(mediaEnumerator.Current); + } + StateHasChanged(); + } + + private IEnumerable<Media> FilterMedia(IEnumerable<Media> media) { + var nsfwTags = tagService.TagsThatImply(HBContext.NsfwTag) + .Select(td => td.ObjectId) + .ToArray(); + + using var enumerator = media.GetEnumerator(); + + while(true) { + bool success = enumerator.MoveNext(); + if(!success) + break; + Media? m = enumerator.Current; + + if(!userService.UserSessionState.ShowNsfw) + if(m.Tags.Select(t => t.TagDefinitionId).Intersect(nsfwTags).Any() || m.IsIngest) + continue; + + if(m.IsIngest != Ingest) + continue; + + yield return m; + } + } + + private async void ShowNsfwChanged(UserSessionState userSessionState) { + await InvokeAsync(() => { + LoadMedia(); + StateHasChanged(); + }); + } + + public void Dispose() { + mediaEnumerator.Dispose(); + userService.UserSessionState.OnStateChange -= ShowNsfwChanged; + } +} diff --git a/Pages/Gallery.razor.css b/Pages/Gallery.razor.css new file mode 100644 index 0000000..0e01e0e --- /dev/null +++ b/Pages/Gallery.razor.css @@ -0,0 +1,11 @@ +img { + margin-right: 5px; + max-height: 200px; +} + +div#ingest-warning { + position: relative; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); +}
\ No newline at end of file diff --git a/Pages/Login.razor b/Pages/Login.razor new file mode 100644 index 0000000..723a78a --- /dev/null +++ b/Pages/Login.razor @@ -0,0 +1,17 @@ +@page "/Login" +@inject NavigationManager navigationManager + +<PageTitle>HyperBooru Login</PageTitle> + +<div/> + +@code { + [CascadingParameter] + public Task<AuthenticationState> AuthenticationState{ get; set; } + + protected override void OnInitialized() { + var authState = AuthenticationState.GetAwaiter().GetResult(); + if(authState!.User.Identity?.IsAuthenticated ?? false) + navigationManager.NavigateTo("/"); + } +}
\ No newline at end of file diff --git a/Pages/Login.razor.css b/Pages/Login.razor.css new file mode 100644 index 0000000..fc8c8ca --- /dev/null +++ b/Pages/Login.razor.css @@ -0,0 +1,6 @@ +div { + background: url('/images/loginbg.webp'); + filter: brightness(0.6); + height: 100%; + width: 100%; +}
\ No newline at end of file diff --git a/Pages/TagDefinitions.razor b/Pages/TagDefinitions.razor new file mode 100644 index 0000000..e2e4df6 --- /dev/null +++ b/Pages/TagDefinitions.razor @@ -0,0 +1,187 @@ +@page "/TagDefinitions" +@inject IDbContextFactory<HBContext> dbFactory +@inject ITagService tagService +@inject IUserService userService +@implements IDisposable +@attribute [Authorize] + +<PageTitle>Tag Definitions</PageTitle> + +<div style="padding:var(--size-default-gap);"> + <ButtonContainer> + <button @onclick=PromptTagCreate data-keyboard-shortcut="c"><u>C</u>reate</button> + </ButtonContainer> + + <TabContainer @ref=tabContainer> + @foreach(var ns in tagNamespaces) { + <TabPane Title="@(ns ?? "Default")"> + <table id="tag-definitions" class="data-table"> + <tr> + <th>Alias</th> + <th>Name</th> + <th>Implicit Tags</th> + <th></th> + </tr> + @foreach(var tagDef in tagDefinitions.Where(td => td.Namespace == ns)) { + <tr data-guid="@tagDef.Guid"> + <td>@tagDef.Alias</td> + <td> + <a href="/Gallery?q=@tagDef.Name" class="nondecorated"> + @tagDef.Name + </a> + </td> + <td> + <i> + @{ + var implicitTags = tagDef.ImplicitTags + .Where(td => td.Source == TagSource.UserTag); + foreach(var tag in implicitTags) { + <a href="/Gallery?q=@tag.Name" class="nondecorated"> + @tag.Name + </a> + if(tag != implicitTags.Last()) + @(", ") + } + } + </i> + </td> + <td class="actions"> + <a href="javascript:;" @onclick=@(() => tagEditDialog.Show(tagDef))>Edit</a> + <a href="javascript:;" @onclick=@(() => PromptToDelete(tagDef))> + Delete + </a> + <a href="javascript:;" @onclick=@(() => PromptImplicitTags(tagDef))> + Implicit Tags + </a> + @if(tagDef.ImplicitTags.Select(td => td.Guid).Contains(HBContext.NsfwTag)) { + <a href="javascript:;" @onclick=@(() => SetNsfw(tagDef, false))>Make SFW</a> + } else { + <a href="javascript:;" @onclick=@(() => SetNsfw(tagDef, true))>Make NSFW</a> + } + </td> + </tr> + } + </table> + </TabPane> + } + </TabContainer> +</div> + +<Dialog Title="Are you sure you want to delete this tag definition?" @ref=deleteTagDialog> + <ButtonContainer> + <button @onclick=@(() => deleteTagDialog.Hide()) class="secondary">Cancel</button> + <button @onclick=@(() => DeleteTagDefinition()) class="warning">Confirm</button> + </ButtonContainer> +</Dialog> + +<TagEditDialog OnTagUpdate=TagUpdated @ref=tagEditDialog/> + +<TagSelectDialog + OnSubmit=SetImplicitTags + @ref=implicitTagDialog /> + +@code { + private TabContainer tabContainer; + private Dialog deleteTagDialog; + private TagEditDialog tagEditDialog; + private TagSelectDialog implicitTagDialog; + + private TagDefinition? toDelete; + private TagDefinition? toEditImplicit; + + private TagDefinition[] tagDefinitions; + + private string?[] tagNamespaces; + + protected override void OnInitialized() => + userService.UserSessionState.OnStateChange += ShowNsfwChanged; + + protected override void OnParametersSet() => + LoadTags(); + + private void LoadTags() { + int[] nsfwTags = Array.Empty<int>(); + if(!userService.UserSessionState.ShowNsfw) + nsfwTags = tagService.TagsThatImply(HBContext.NsfwTag) + .Select(td => td.ObjectId) + .ToArray(); + + tagDefinitions = dbFactory.CreateDbContext().TagDefinitions + .Include(td => td.ImplicitTags) + .Where(td => td.Source == TagSource.UserTag) + .OrderBy(td => td.Namespace) + .ThenBy(td => td.Name) + .AsEnumerable() + .Where(td => userService.UserSessionState.ShowNsfw || !td.ImplicitTags + .IntersectBy(nsfwTags, td => td.ObjectId) + .Any()) + .ToArray(); + + tagNamespaces = tagDefinitions + .Select(td => td.Namespace) + .Order() + .Distinct() + .ToArray(); + } + + private void PromptToDelete(TagDefinition toDelete) { + this.toDelete = toDelete; + deleteTagDialog.Show(); + } + + private void DeleteTagDefinition() { + if(toDelete is null) + return; + + tagService.DeleteTagDefinition(toDelete); + deleteTagDialog.Hide(); + LoadTags(); + StateHasChanged(); + } + + private void PromptTagCreate() { + string? ns = tabContainer.ActivePane?.Title; + if(ns == "Default") + ns = null; + tagEditDialog.Show(ns); + } + + private void TagUpdated(object? sender, EventArgs e) { + LoadTags(); + StateHasChanged(); + } + + private void PromptImplicitTags(TagDefinition toEditImplicit) { + this.toEditImplicit = toEditImplicit; + implicitTagDialog.SelectedTags = + toEditImplicit.ImplicitTags.ToArray(); + implicitTagDialog.Show(); + } + + private void SetImplicitTags(TagDefinition[] tagDefs) { + if(toEditImplicit is null) + return; + + tagService.SetImplicitTags(toEditImplicit, tagDefs); + LoadTags(); + StateHasChanged(); + } + + private void SetNsfw(TagDefinition tagDef, bool nsfw) { + if(nsfw) + tagService.AddImplicitTag(tagDef.Guid, HBContext.NsfwTag); + else + tagService.RemoveImplicitTag(tagDef.Guid, HBContext.NsfwTag); + LoadTags(); + StateHasChanged(); + } + + private async void ShowNsfwChanged(UserSessionState userSessionState) => + await InvokeAsync(() => { + LoadTags(); + StateHasChanged(); + }); + + public void Dispose() => + userService.UserSessionState.OnStateChange -= ShowNsfwChanged; +} diff --git a/Pages/Upload.razor b/Pages/Upload.razor new file mode 100644 index 0000000..614cec0 --- /dev/null +++ b/Pages/Upload.razor @@ -0,0 +1,43 @@ +@page "/Upload" +@attribute [Authorize] + +<div id="dropzone"> + <p>Drag a file to upload it<br/>or click to select one or more file(s)</p> + <form id="uploadForm" action="/media" method="post" enctype="multipart/form-data"> + <input type="file" id="fileUpload" name="fileUpload" accept="image/*,video/*" multiple/> + </form> +</div> + +<script suppress-error="BL9992"> + var dropzone = document.getElementById('dropzone'); + var uploadForm = document.getElementById('uploadForm'); + var fileUpload = document.getElementById('fileUpload'); + + dropzone.ondragover = function (e) { + e.preventDefault(); + } + + dropzone.ondragenter = function(e) { + e.preventDefault(); + dropzone.classList.toggle('hover', true); + } + + dropzone.ondragleave = function(e) { + e.preventDefault(); + dropzone.classList.toggle('hover', false); + } + + dropzone.ondrop = function(e) { + e.preventDefault(); + fileUpload.files = e.dataTransfer.files; + uploadForm.submit(); + } + + dropzone.onclick = function(e) { + fileUpload.click(); + } + + fileUpload.onchange = function(e) { + uploadForm.submit(); + } +</script> diff --git a/Pages/Upload.razor.css b/Pages/Upload.razor.css new file mode 100644 index 0000000..6ff40a2 --- /dev/null +++ b/Pages/Upload.razor.css @@ -0,0 +1,35 @@ +div#dropzone { + border-radius: 10px; + border: 3px dashed #aaa; + cursor: pointer; + height: 400px; + left: 50%; + position: relative; + top: 50%; + transform: translate(-50%, -50%); + transition: border-color 0.1s linear; + width: 700px; +} + +div#dropzone p { + color: #aaa; + display: inline-block; + left: 50%; + margin: 0; + position: relative; + text-align: center; + top: 50%; + transform: translate(-50%, -50%); +} + +div#dropzone input { + display: none; +} + +div#dropzone.hover, div#dropzone:hover { + border: 3px dashed white; +} + +div#dropzone.hover p, div#dropzone:hover p { + color: white; +}
\ No newline at end of file diff --git a/Pages/ViewMedia.razor b/Pages/ViewMedia.razor new file mode 100644 index 0000000..ce9d608 --- /dev/null +++ b/Pages/ViewMedia.razor @@ -0,0 +1,218 @@ +@page "/ViewMedia" +@using HyperBooru.Util +@inject IJSRuntime jsRuntime +@inject IDbContextFactory<HBContext> dbFactory +@inject ITagService tagService +@inject IMediaService mediaService +@inject ISourceService sourceService +@attribute [Authorize] + +<PageTitle>@title</PageTitle> + +<script suppress-warning="BL9992"> + function toggleSidebar() { + document.getElementById("metadata").classList.toggle("hidden"); + } +</script> + +<div id="content"> + <div id="image-container"> + <img + src="/media/@(media.Guid)" + width=@media.CurrentUploadedFile.Width + height=@media.CurrentUploadedFile.Height + onclick="toggleSidebar()"/> + </div> + <div id="metadata"> + <div id="metadata-container"> + <div id="metadata-fileinfo"> + @if(infoEditMode) { + <form action="javascript:;" @onsubmit=@(() => ApplyInfoEdit(true))> + <table id="edit-metadata"> + <tr> + <td>Title:</td> + <td><input type="text" @bind=shortDescription @ref=shortDescriptionInput/></td> + </tr> + <tr> + <td>Description:</td> + <td><textarea rows="4" @bind=longDescription/></td> + </tr> + </table> + </form> + } else { + <p>Title: <i>@(media.ShortDescription ?? "None")</i></p> + <p class="newlines">Description:<br/><i>@(media.LongDescription ?? "None")</i></p> + } + <p>Resolution: @(media.CurrentUploadedFile.Width)x@(media.CurrentUploadedFile.Height)</p> + <p class="heading">Upload history</p> + <hr/> + <table id="uploaded-files" class="data-table"> + <tr> + <th>Created On</th> + <th>Last Write</th> + <th>Uploaded On</th> + <th>Filename</th> + <th>Size</th> + <th>Original Checksum</th> + </tr> + @foreach(var file in media.UploadedFiles.OrderByDescending(uf => uf.UploadTime)) { + string? sourceUrl = null; + if(file.Filename is not null) + sourceUrl = sourceService.GetUrlFromFilename(file.Filename); + <tr> + <td title=@file.CreateTime?.ToString()> + @(file.CreateTime?.ToString("d") ?? "N/A") + </td> + <td title=@file.LastWriteTime?.ToString()> + @(file.LastWriteTime?.ToString("d") ?? "N/A") + </td> + <td title=@file.UploadTime>@(file.UploadTime.ToString("d"))</td> + <td title=@file.Filename> + @if(sourceUrl is not null) { + <a class="nondecorated" target="_blank" href=@sourceUrl>@file.Filename</a> + } else { + @file.Filename + } + </td> + <td title=@file.Length>@file.Length.ToBytesSI()</td> + <td + title=@(file.Checksum + (file.ChecksumVerified ? " (verified)" : "")) + class=@(file.ChecksumVerified ? "verified" : null)> + + @file.Checksum.Substring(0, 8) + </td> + </tr> + } + </table> + </div> + <div id="metadata-tags"> + <p class="heading">Tags</p> + <hr/> + <MediaTagTable Media=media @ref=mediaTagTable/> + </div> + </div> + <div id="button-container"> + <ButtonContainer> + <button @onclick=@(() => deleteDialog.Show()) class="warning" data-keyboard-shortcut="d"><u>D</u>elete</button> + <button @onclick=@(() => tagDialog.Show()) class="secondary" data-keyboard-shortcut="t">Add <u>T</u>ag</button> + <button @onclick=@(() => ocrDialog.Show()) class="secondary" data-keyboard-shortcut="o">View <u>O</u>CR</button> + @if(infoEditMode) { + <button @onclick=@(() => ApplyInfoEdit(false)) class="secondary">Cancel</button> + <button @onclick=@(() => ApplyInfoEdit(true))>Apply</button> + } else { + <button @onclick=@(() => InfoEditMode = true) class="secondary" data-keyboard-shortcut="e"><u>E</u>dit Info</button> + } + @if(media.IsIngest) { + <button @onclick=@(() => SetIngest(false)) data-keyboard-shortcut="c">Mark Tagging <u>C</u>omplete</button> + } else { + <button class="secondary" @onclick=@(() => SetIngest(true)) data-keyboard-shortcut="c">Mark Tagging In<u>c</u>omplete</button> + } + </ButtonContainer> + </div> + </div> +</div> + +<Dialog Title="Delete this media?" @ref=deleteDialog> + <ButtonContainer> + <button @onclick=@(() => deleteDialog.Hide()) class="secondary">Cancel</button> + <button @onclick=DeleteMedia class="warning">Confirm</button> + </ButtonContainer> +</Dialog> + +<Dialog Title="OCR Data" @ref=ocrDialog> + @if(media.OcrData is null) { + <p><center>This media item hasn't been scanned yet!</center></p> + } else { + <code style="max-height:400px;">@media.OcrData?.Text</code> + } + <ButtonContainer> + <button @onclick=@(() => ocrDialog.Hide())>Close</button> + </ButtonContainer> +</Dialog> + +<TagSelectDialog + Title="Select one or more tag(s) to add" + OnSubmit=AddTags + @ref=tagDialog/> + +@code { + [Parameter] + [SupplyParameterFromQuery(Name = "m")] + public Guid MediaId { get; set; } + + private Media media; + + private string title; + + private bool infoEditMode = false; + private string? shortDescription; + private string? longDescription; + + private MediaTagTable mediaTagTable; + private Dialog deleteDialog; + private Dialog ocrDialog; + private TagSelectDialog tagDialog; + + private ElementReference shortDescriptionInput; + + protected override void OnInitialized() => + LoadMedia(); + + protected override async void OnAfterRender(bool firstRender) { + if(infoEditMode) + await shortDescriptionInput.FocusAsync(); + } + + private void LoadMedia() { + using var db = dbFactory.CreateDbContext(); + media = db.Media + .Include(m => m.Tags) + .ThenInclude(t => t.TagDefinition) + .Include(m => m.CurrentUploadedFile) + .Include(m => m.UploadedFiles) + .Include(m => m.OcrData) + .First(m => m.Guid == MediaId); + + title = media.DisplayName ?? "Media View"; + } + + private void AddTags(TagDefinition[] tagDefs) { + foreach(var tagDef in tagDefs) + tagService.AddTag(media, tagDef); + mediaTagTable.Refresh(); + } + + private async void SetIngest(bool ingest) { + mediaService.SetIngest(media, ingest); + LoadMedia(); + + if(ingest) + StateHasChanged(); + else + await jsRuntime.InvokeVoidAsync("history.back"); + } + + private bool InfoEditMode { + get => infoEditMode; + set { + shortDescription = media.ShortDescription; + longDescription = media.LongDescription; + infoEditMode = value; + StateHasChanged(); + } + } + + private void ApplyInfoEdit(bool apply) { + if(apply) { + mediaService.SetDescription(media, shortDescription, longDescription); + LoadMedia(); + } + + infoEditMode = false; + } + + private async void DeleteMedia() { + mediaService.Delete(media); + await jsRuntime.InvokeVoidAsync("history.back"); + } +} diff --git a/Pages/ViewMedia.razor.css b/Pages/ViewMedia.razor.css new file mode 100644 index 0000000..53d5eca --- /dev/null +++ b/Pages/ViewMedia.razor.css @@ -0,0 +1,116 @@ +div#content { + display: flex; + align-items: start; + height: 100%; +} + +div#image-container { + box-sizing: border-box; + flex: 1 0 0; + height: 100%; + padding: var(--size-default-gap); + width: 100%; +} + +div#image-container > img { + display: block; + left: 50%; + max-height: 100%; + max-width: 100%; + object-fit: contain; + position: relative; + top: 50%; + transform: translate(-50%, -50%); +} + +div#metadata { + background: #333; + box-shadow: rgba(0, 0, 0, 0.5) -10px 0px 10px; + box-sizing: border-box; + display: flex; + flex-direction: column; + flex: 0 0 auto; + height: 100%; + margin-left: auto; + padding: 30px; + transition: margin-right 0.1s linear; + width: 700px; + z-index: 90; +} + +div#metadata.hidden { + box-shadow: none; + margin-right: -700px; +} + +@media (max-aspect-ratio: 4/3) { + div#metadata { + box-shadow: none; + margin-right: -700px; + } +} + +div#button-container { + margin-top: auto; +} + +div#metadata-container { + overflow-x: hidden; + overflow-y: auto; +} + +table#edit-metadata { + border-collapse: collapse; + width: 100%; +} + +table#edit-metadata tr:first-child { + vertical-align: middle; +} + +table#edit-metadata tr:last-child { + vertical-align: top; +} + +table#edit-metadata td:last-child { + width: 100%; +} + +table#edit-metadata td > input { + width: 100%; + margin: 0; +} + +table#edit-metadata td > textarea { + margin: 0; + resize: none; + width: 100%; +} + +table#uploaded-files th { + font-size: 8pt; +} + +table#uploaded-files td { + font-family: 'Lucida Console'; + font-size: 8pt; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +table#uploaded-files td:nth-child(4) { + max-width: 170px; +} + +table#uploaded-files td.verified { + color: var(--col-checksum-verified-pri); +} + +p.heading { + margin-top: 30px; +} + +p.newlines { + white-space: pre-line; +} diff --git a/Pages/_Host.cshtml b/Pages/_Host.cshtml new file mode 100644 index 0000000..69bced8 --- /dev/null +++ b/Pages/_Host.cshtml @@ -0,0 +1,35 @@ +@page "/" +@using Microsoft.AspNetCore.Components.Web +@namespace HyperBooru.Pages +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers + +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8" /> + <base href="~/" /> + <link href="css/site.css" rel="stylesheet" /> + <link href="/styles/global.css" rel="stylesheet" /> + <link href="/favicon.ico" rel="icon" /> + <link href="/manifest.webmanifest" rel="manifest" /> + <script type="text/javascript" src="/js/keyboard.js"></script> + <script type="text/javascript" src="/js/dialog.js"></script> + <component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" /> +</head> +<body> + <component type="typeof(App)" render-mode="ServerPrerendered" /> + + <div id="blazor-error-ui"> + <environment include="Staging,Production"> + An error has occurred. This application may no longer respond until reloaded. + </environment> + <environment include="Development"> + An unhandled exception has occurred. See browser dev tools for details. + </environment> + <a href="" class="reload">Reload</a> + <a class="dismiss">🗙</a> + </div> + + <script src="_framework/blazor.server.js"></script> +</body> +</html> diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..f80b996 --- /dev/null +++ b/Program.cs @@ -0,0 +1,51 @@ +using Microsoft.EntityFrameworkCore; +using System.Text.Json.Serialization; +using HyperBooru.Services; +using Microsoft.AspNetCore.Authentication.Cookies; + +namespace HyperBooru; + +public class Program { + public static void Main(string[] args) { + var builder = WebApplication.CreateBuilder(args); + builder.Services.AddSession(); + builder.Services.AddHttpContextAccessor(); + builder.Services.AddAuthentication( + CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(); + builder.Services.AddControllers().AddJsonOptions(o => { + var converter = new JsonStringEnumConverter(); + o.JsonSerializerOptions.Converters.Add(converter); + }); + builder.Services.AddRazorPages(); + builder.Services.AddServerSideBlazor(); + + // Add our custom services + builder.Services.AddSingleton<IConfigService, ConfigService>(); + builder.Services.AddDbContextFactory<HBContext>(); + builder.Services.AddScoped<ISearchService, SearchService>(); + builder.Services.AddScoped<ITagService, TagService>(); + builder.Services.AddScoped<IMediaService, MediaService>(); + builder.Services.AddSingleton<IGlobalUserService, GlobalUserService>(); + builder.Services.AddScoped<IUserService, UserService>(); + builder.Services.AddHostedService<OcrService>(); + builder.Services.AddSingleton<ISourceService, SourceService>(); + + 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<HBContext>(); + db.Database.Migrate(); + + app.UseSession(); + app.UseHsts(); + app.UseHttpsRedirection(); + app.UseStaticFiles(); + app.UseRouting(); + app.MapBlazorHub(); + app.MapControllers(); + app.MapFallbackToPage("/_Host"); + + app.Run(); + } +} diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json new file mode 100644 index 0000000..9f4966c --- /dev/null +++ b/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "profiles": { + "WSL": { + "commandName": "WSL2", + "launchBrowser": true, + "launchUrl": "https://localhost:7132", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "ASPNETCORE_URLS": "https://localhost:7132;http://localhost:5186" + }, + "distributionName": "" + }, + "HyperBooru": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "https://localhost:7132;http://localhost:5186" + } + }, + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:1922", + "sslPort": 44354 + } + } +}
\ No newline at end of file diff --git a/Server.csproj b/Server.csproj new file mode 100644 index 0000000..e3ca595 --- /dev/null +++ b/Server.csproj @@ -0,0 +1,37 @@ +<Project Sdk="Microsoft.NET.Sdk.Web"> + + <PropertyGroup> + <TargetFramework>net8.0</TargetFramework> + <Nullable>enable</Nullable> + <ImplicitUsings>enable</ImplicitUsings> + <AssemblyName>HyperBooru</AssemblyName> + <RootNamespace>HyperBooru</RootNamespace> + <AssemblyVersion>0.1.0.0</AssemblyVersion> + <FileVersion>$(AssemblyVersion)</FileVersion> + <Version>0.1-alpha</Version> + <UserSecretsId>2907567f-4640-4581-8f4d-0977952d26bd</UserSecretsId> + </PropertyGroup> + + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> + <NoWarn>1701;1702;8618</NoWarn> + </PropertyGroup> + + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> + <NoWarn>1701;1702;8618</NoWarn> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="Magick.NET-Q16-AnyCPU" Version="14.10.2" /> + <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.23" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.23"> + <PrivateAssets>all</PrivateAssets> + <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> + </PackageReference> + <PackageReference Include="Mime-Detective" Version="25.8.1" /> + <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.11" /> + <PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.4" /> + <PackageReference Include="System.Drawing.Common" Version="8.0.23" /> + <PackageReference Include="Tesseract" Version="5.2.0" /> + </ItemGroup> + +</Project> diff --git a/Services/ConfigService.cs b/Services/ConfigService.cs new file mode 100644 index 0000000..b42b80c --- /dev/null +++ b/Services/ConfigService.cs @@ -0,0 +1,58 @@ +namespace HyperBooru.Services; + +public interface IConfigService { + public string DataPath { get; } + public string DbConnectionString { get; } + public string MediaBasePath { get; } + public string ThumbnailBasePath { 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 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 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/Services/MediaService.cs b/Services/MediaService.cs new file mode 100644 index 0000000..104d0db --- /dev/null +++ b/Services/MediaService.cs @@ -0,0 +1,329 @@ +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); + + 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 string GetPath(Media media); + public string GetPath(Media media, int width, int height); + +} + +public class MediaService : IMediaService { + private IDbContextFactory<HBContext> dbFactory; + private IConfigService config; + + private IContentInspector inspector; + + public MediaService(IDbContextFactory<HBContext> 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) { + + 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.UploadedFiles + .Include(uf => uf.Media) + .FirstOrDefault(uf => uf.Checksum == hash)? + .Media; + + 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 + }; + + if(media is null) { + var ingestTagDef = db.TagDefinitions + .First(td => td.Guid == HBContext.IngestTag); + + media = new() { + UploadedFiles = new() { + fileRecord + }, + Tags = new() { + new() { TagDefinition = ingestTagDef } + } + }; + + 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 { + db.Entry(media).Collection(m => m.UploadedFiles).Load(); + 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); + 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<Exception> 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 media, int? width, int? height) { + using var db = dbFactory.CreateDbContext(); + + var m = db.Media + .Include(m => m.CurrentUploadedFile) + .First(m => m.Guid == media); + if(m is null) + throw new ObjectNotFoundException(media); + + if(m.CurrentUploadedFile.MimeType.Split("/")[0] != "image") + throw new ThumbnailException("Media object not an image", m); + + using var image = new MagickImage(GetPath(m)); + + if(width is null && height is null) + throw new ThumbnailException("Both width and height cannot be null!", m); + + if(width > image.Width || height > image.Height) + throw new ThumbnailException("Requested thumbnail size is larger than original media", m); + + #pragma warning disable CS8629 + int w = (int) (width is not null ? width : image.Width * height / image.Height); + int h = (int) (height is not null ? height : image.Height * width / image.Width); + #pragma warning restore CS8629 + + var thumbPath = GetPath(m, w, h); + + if(!File.Exists(thumbPath)) { + image.Resize((uint) w, (uint) h); + image.Write(thumbPath); + } + + return System.IO.File.OpenRead(thumbPath); + } + + public Stream GetThumbnail(Media media, int? width, int? height) => + GetThumbnail(media.Guid, width, height); + + public string GetPath(Media media) { + var fileInfo = new FileInfo( + Path.Join( + config.MediaBasePath, + media.Guid.ToString().Substring(0, 2), + media.Guid.ToString().Substring(2, 2), + media.Guid.ToString())); + + Directory.CreateDirectory(fileInfo.Directory.FullName); + return fileInfo.FullName; + } + + public string GetPath(Media media, int width, int height) { + var fileInfo = new FileInfo(Path.Join( + config.ThumbnailBasePath, + media.Guid.ToString().Substring(0, 2), + media.Guid.ToString().Substring(2, 2), + $"{media.Guid.ToString()}-{width}-{height}")); + + Directory.CreateDirectory(fileInfo.Directory.FullName); + return fileInfo.FullName; + } + + private int GetUploadedFileHash(UploadedFile uf) => ( + uf.CreateTime, + uf.LastWriteTime, + uf.Filename, + uf.Length, + uf.Checksum).GetHashCode(); +} diff --git a/Services/OcrService.cs b/Services/OcrService.cs new file mode 100644 index 0000000..4d21705 --- /dev/null +++ b/Services/OcrService.cs @@ -0,0 +1,120 @@ +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 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 IServiceScopeFactory scopeFactory; + private ILogger<OcrService> logger; + private IDbContextFactory<HBContext> dbFactory; + + public OcrService( + IServiceScopeFactory scopeFactory, + ILogger<OcrService> logger, + IDbContextFactory<HBContext> dbFactory) { + + 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) { + 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) { + return; + + using var scope = scopeFactory.CreateScope(); + var mediaService = scope.ServiceProvider + .GetRequiredService<IMediaService>(); + + using var db = dbFactory.CreateDbContext(); + Guid[] guids = db.Media + .Include(m => m.CurrentUploadedFile) + .Include(m => m.OcrData) + .Where(m => m.OcrData == null) + .Where(m => m.CurrentUploadedFile.MimeType.Contains("image/")) + .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<Task>(); + + 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/Services/SearchService.cs b/Services/SearchService.cs new file mode 100644 index 0000000..5ca12e1 --- /dev/null +++ b/Services/SearchService.cs @@ -0,0 +1,117 @@ +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru.Services; + +public interface ISearchService { + public Media[] Search(string query); +} + +public class SearchService : ISearchService { + private ITagService tagService; + + private IDbContextFactory<HBContext> dbFactory; + + public SearchService( + IDbContextFactory<HBContext> dbFactory, + ITagService tagService) { + + this.tagService = tagService; + this.dbFactory = dbFactory; + } + + public Media[] Search(string query) { + var db = dbFactory.CreateDbContext(); + + query = query.ToLower().Trim(); + + int[] descriptionResults = SearchDescription(query); + int[] filenameResults = SearchFilenames(query); + int[] ocrResults = SearchOcr(query); + + var matchedTag = db.TagDefinitions + .FirstOrDefault(td => td.Name.ToLower() == query); + + int[] tags; + if(matchedTag is not null) { + tags = tagService + .TagsThatImply(matchedTag) + .Select(td => td.ObjectId) + .ToArray(); + } else { + // TODO: Expand scope to all tags that imply + tags = db.TagDefinitions + .Where(td => td.Name.ToLower().Contains(query)) + .Select(td => td.ObjectId) + .ToArray(); + } + + int[] tagResults = SearchTags(tags); + + int[] mediaIds = descriptionResults + .Union(filenameResults) + .Union(ocrResults) + .Union(tagResults) + .OrderDescending() + .ToArray(); + + return db.Media + .Include(m => m.Tags) + .Include(m => m.CurrentUploadedFile) + .Where(m => mediaIds.Contains(m.ObjectId)) + .ToArray(); + } + + // TODO: Make asynchronous + private int[] SearchDescription(string query) { + return Task.Run(() => { + using var db = dbFactory.CreateDbContext(); + query = query.ToLower(); + return db.Media + .Where(m => + (m.ShortDescription != null && m.ShortDescription.ToLower().Contains(query)) || + (m.LongDescription != null && m.LongDescription.ToLower().Contains(query))) + .Select(m => m.ObjectId) + .ToArray(); + }).GetAwaiter().GetResult(); + } + + // TODO: Make asynchronous + private int[] SearchFilenames(string query) { + return Task.Run(() => { + using var db = dbFactory.CreateDbContext(); + query = query.ToLower(); + return db.UploadedFiles + .Include(uf => uf.Media) + .Where(uf => uf.Filename != null && uf.Filename.ToLower().Contains(query)) + .Select(uf => uf.Media.ObjectId) + .Distinct() + .ToArray(); + }).GetAwaiter().GetResult(); + } + + // TODO: Make asynchronous + private int[] SearchOcr(string query) { + return Task.Run(() => { + using var db = dbFactory.CreateDbContext(); + query = query.ToLower(); + return db.OcrData + .Include(o => o.Media) + .Where(o => o.SearchableText.Contains(query)) + .Select(o => o.Media.ObjectId) + .ToArray(); + }).GetAwaiter().GetResult(); + } + + // TODO: Make asynchronous + private int[] SearchTags(int[] tags) { + return Task.Run(() => { + using var db = dbFactory.CreateDbContext(); + return db.Media + .Include(m => m.Tags) + .AsEnumerable() + .Where(m => m.Tags.IntersectBy(tags, t => t.TagDefinitionId).Any()) + .Select(m => m.ObjectId) + .ToArray(); + }).GetAwaiter().GetResult(); + } +} diff --git a/Services/SourceService.cs b/Services/SourceService.cs new file mode 100644 index 0000000..d145346 --- /dev/null +++ b/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/Services/TagService.cs b/Services/TagService.cs new file mode 100644 index 0000000..56aba04 --- /dev/null +++ b/Services/TagService.cs @@ -0,0 +1,309 @@ +using Microsoft.AspNetCore.Components.Web; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Razor.TagHelpers; +using Microsoft.EntityFrameworkCore; +using System.Reflection; +using System.Reflection.Metadata; + +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<HBContext> dbFactory; + + public TagService(IDbContextFactory<HBContext> 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<TagDefinition> 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<TagDefinition>( + 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<TagDefinition, bool>(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<TagDefinition>() { + 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/Services/UserService.cs b/Services/UserService.cs new file mode 100644 index 0000000..39b1963 --- /dev/null +++ b/Services/UserService.cs @@ -0,0 +1,77 @@ +using Microsoft.AspNetCore.Cryptography.KeyDerivation; +using Microsoft.EntityFrameworkCore; + +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<byte>(), + 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<string, UserSessionState> 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); @@ -0,0 +1,31 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +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<TagDefinition> ImplicitTags { get; set; } = new(); +} + +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; +}
\ No newline at end of file @@ -0,0 +1,35 @@ +# Bugs + - [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 + - [ ] 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 @@ -0,0 +1,9 @@ +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru; + +[Index(nameof(Username))] +public class User : HBObject { + public string Username { get; set; } + public string PasswordHash { get; set; } +} @@ -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<Task> 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<Task> 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/_Imports.razor b/_Imports.razor new file mode 100644 index 0000000..4c5566b --- /dev/null +++ b/_Imports.razor @@ -0,0 +1,9 @@ +@using HyperBooru +@using HyperBooru.Pages.Component +@using HyperBooru.Services +@using Microsoft.AspNetCore.Authorization +@using Microsoft.AspNetCore.Components.Authorization +@using Microsoft.AspNetCore.Components.Routing +@using Microsoft.AspNetCore.Components.Web +@using Microsoft.EntityFrameworkCore +@using Microsoft.JSInterop diff --git a/appsettings.Development.json b/appsettings.Development.json new file mode 100644 index 0000000..6860045 --- /dev/null +++ b/appsettings.Development.json @@ -0,0 +1,10 @@ +{ + "DetailedErrors": true, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "HyperBooru.Services.OcrService": "Debug" + } + } +} diff --git a/appsettings.json b/appsettings.json new file mode 100644 index 0000000..414e673 --- /dev/null +++ b/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/tessdata/eng.traineddata b/tessdata/eng.traineddata Binary files differnew file mode 100644 index 0000000..176dc32 --- /dev/null +++ b/tessdata/eng.traineddata diff --git a/wwwroot/css/site.css b/wwwroot/css/site.css new file mode 100644 index 0000000..21f9a94 --- /dev/null +++ b/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/wwwroot/favicon.ico b/wwwroot/favicon.ico Binary files differnew file mode 100644 index 0000000..a1be4cc --- /dev/null +++ b/wwwroot/favicon.ico diff --git a/wwwroot/icon-192.png b/wwwroot/icon-192.png Binary files differnew file mode 100644 index 0000000..28ce06d --- /dev/null +++ b/wwwroot/icon-192.png diff --git a/wwwroot/icon-512.png b/wwwroot/icon-512.png Binary files differnew file mode 100644 index 0000000..8c28696 --- /dev/null +++ b/wwwroot/icon-512.png diff --git a/wwwroot/images/loginbg.webp b/wwwroot/images/loginbg.webp Binary files differnew file mode 100644 index 0000000..759e666 --- /dev/null +++ b/wwwroot/images/loginbg.webp diff --git a/wwwroot/js/dialog.js b/wwwroot/js/dialog.js new file mode 100644 index 0000000..418962f --- /dev/null +++ b/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/wwwroot/js/keyboard.js b/wwwroot/js/keyboard.js new file mode 100644 index 0000000..72ed3cb --- /dev/null +++ b/wwwroot/js/keyboard.js @@ -0,0 +1,51 @@ +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.submit(); + 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; + } +} + +window.onload = () => document.onkeydown = keyDownHandler;
\ No newline at end of file diff --git a/wwwroot/loginbg.webm b/wwwroot/loginbg.webm Binary files differnew file mode 100644 index 0000000..139ed0d --- /dev/null +++ b/wwwroot/loginbg.webm diff --git a/wwwroot/manifest.webmanifest b/wwwroot/manifest.webmanifest new file mode 100644 index 0000000..f150f98 --- /dev/null +++ b/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/wwwroot/styles/data-table.css b/wwwroot/styles/data-table.css new file mode 100644 index 0000000..994d625 --- /dev/null +++ b/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/wwwroot/styles/global.css b/wwwroot/styles/global.css new file mode 100644 index 0000000..ebcda47 --- /dev/null +++ b/wwwroot/styles/global.css @@ -0,0 +1,169 @@ +@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-scrollbar: #666666; + --col-scrollbar-hover: #aaaaaa; + --col-switch-bg: var(--col-bg); + --col-switch-fg: #fff; + --col-switch-bg-hl: var(--col-accent-pri); + + --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'; + margin: 0; + overflow: hidden; +} + +a { + color: var(--col-accent-pri); + text-decoration: none; +} + +a:hover { + filter: brightness(1.5); +} + +a::selection { + background: var(--col-accent-pri); + color: #fff; +} + +a.nondecorated { + color: #fff; +} + +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] { + background: var(--col-button-pri); + border-radius: 10px; + border: none; + box-sizing: border-box; + color: white; + cursor: pointer; + 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.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); +} + +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; +} + +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; +} + +/* 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; +} + +::-webkit-scrollbar-thumb:hover { + background: var(--col-scrollbar-hover); +} + +::-webkit-scrollbar-corner { + opacity: 0; +} |
