Compare commits
16 Commits
45afb57df5
...
feature/FA
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3612c89b99 | ||
|
|
ebb2e6e7fc | ||
|
|
01d3b94050 | ||
|
|
c0290cc5af | ||
| 1d950b7721 | |||
|
|
7738bcf438 | ||
| 61e0cb69d8 | |||
|
|
02525d611a | ||
| c21fe0fbd5 | |||
|
|
bbc0b5ec7d | ||
| 5527c15ae7 | |||
|
|
1e374e6eeb | ||
| c710f14257 | |||
|
|
6c10077505 | ||
| fecb3e6f43 | |||
|
|
f0ea71e00e |
@@ -7,6 +7,7 @@ using FictionArchive.Service.NovelService.Services;
|
|||||||
using FictionArchive.Service.NovelService.Services.SourceAdapters;
|
using FictionArchive.Service.NovelService.Services.SourceAdapters;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
using HotChocolate.Authorization;
|
using HotChocolate.Authorization;
|
||||||
|
using HotChocolate.Types;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace FictionArchive.Service.NovelService.GraphQL;
|
namespace FictionArchive.Service.NovelService.GraphQL;
|
||||||
@@ -26,4 +27,12 @@ public class Mutation
|
|||||||
{
|
{
|
||||||
return await service.QueueChapterPull(novelId, chapterNumber);
|
return await service.QueueChapterPull(novelId, chapterNumber);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Error<KeyNotFoundException>]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<bool> DeleteNovel(uint novelId, NovelUpdateService service)
|
||||||
|
{
|
||||||
|
await service.DeleteNovel(novelId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -44,7 +44,6 @@ public class Program
|
|||||||
#region GraphQL
|
#region GraphQL
|
||||||
|
|
||||||
builder.Services.AddDefaultGraphQl<Query, Mutation>()
|
builder.Services.AddDefaultGraphQl<Query, Mutation>()
|
||||||
.ModifyCostOptions(opt => opt.MaxFieldCost = 5000)
|
|
||||||
.AddAuthorization();
|
.AddAuthorization();
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -63,12 +62,14 @@ public class Program
|
|||||||
builder.Services.AddHttpClient<NovelpiaAuthMessageHandler>(client =>
|
builder.Services.AddHttpClient<NovelpiaAuthMessageHandler>(client =>
|
||||||
{
|
{
|
||||||
client.BaseAddress = new Uri("https://novelpia.com");
|
client.BaseAddress = new Uri("https://novelpia.com");
|
||||||
});
|
})
|
||||||
|
.AddStandardResilienceHandler();
|
||||||
builder.Services.AddHttpClient<ISourceAdapter, NovelpiaAdapter>(client =>
|
builder.Services.AddHttpClient<ISourceAdapter, NovelpiaAdapter>(client =>
|
||||||
{
|
{
|
||||||
client.BaseAddress = new Uri("https://novelpia.com");
|
client.BaseAddress = new Uri("https://novelpia.com");
|
||||||
})
|
})
|
||||||
.AddHttpMessageHandler<NovelpiaAuthMessageHandler>();
|
.AddHttpMessageHandler<NovelpiaAuthMessageHandler>()
|
||||||
|
.AddStandardResilienceHandler();
|
||||||
|
|
||||||
builder.Services.Configure<NovelUpdateServiceConfiguration>(builder.Configuration.GetSection("UpdateService"));
|
builder.Services.Configure<NovelUpdateServiceConfiguration>(builder.Configuration.GetSection("UpdateService"));
|
||||||
builder.Services.AddTransient<NovelUpdateService>();
|
builder.Services.AddTransient<NovelUpdateService>();
|
||||||
|
|||||||
@@ -281,15 +281,16 @@ public class NovelUpdateService
|
|||||||
// Step 3: Check for existing novel by ExternalId + Source.Key
|
// Step 3: Check for existing novel by ExternalId + Source.Key
|
||||||
var existingNovel = await _dbContext.Novels
|
var existingNovel = await _dbContext.Novels
|
||||||
.Include(n => n.Author)
|
.Include(n => n.Author)
|
||||||
.ThenInclude(a => a.Name)
|
.ThenInclude(a => a.Name)
|
||||||
.ThenInclude(lk => lk.Texts)
|
.ThenInclude(lk => lk.Texts)
|
||||||
.Include(n => n.Source)
|
.Include(n => n.Source)
|
||||||
.Include(n => n.Name)
|
.Include(n => n.Name)
|
||||||
.ThenInclude(lk => lk.Texts)
|
.ThenInclude(lk => lk.Texts)
|
||||||
.Include(n => n.Description)
|
.Include(n => n.Description)
|
||||||
.ThenInclude(lk => lk.Texts)
|
.ThenInclude(lk => lk.Texts)
|
||||||
.Include(n => n.Tags)
|
.Include(n => n.Tags)
|
||||||
.Include(n => n.Chapters)
|
.Include(n => n.Chapters).ThenInclude(chapter => chapter.Body)
|
||||||
|
.ThenInclude(localizationKey => localizationKey.Texts)
|
||||||
.Include(n => n.CoverImage)
|
.Include(n => n.CoverImage)
|
||||||
.FirstOrDefaultAsync(n =>
|
.FirstOrDefaultAsync(n =>
|
||||||
n.ExternalId == metadata.ExternalId &&
|
n.ExternalId == metadata.ExternalId &&
|
||||||
@@ -378,12 +379,23 @@ public class NovelUpdateService
|
|||||||
var chapter = novel.Chapters.Where(chapter => chapter.Order == chapterNumber).FirstOrDefault();
|
var chapter = novel.Chapters.Where(chapter => chapter.Order == chapterNumber).FirstOrDefault();
|
||||||
var adapter = _sourceAdapters.FirstOrDefault(adapter => adapter.SourceDescriptor.Key == novel.Source.Key);
|
var adapter = _sourceAdapters.FirstOrDefault(adapter => adapter.SourceDescriptor.Key == novel.Source.Key);
|
||||||
var rawChapter = await adapter.GetRawChapter(chapter.Url);
|
var rawChapter = await adapter.GetRawChapter(chapter.Url);
|
||||||
var localizationText = new LocalizationText()
|
|
||||||
|
// If we already have the raw for this, overwrite it for now. Revisions will come later.
|
||||||
|
var localizationText = chapter.Body.Texts.FirstOrDefault(text => text.Language == novel.RawLanguage);
|
||||||
|
if (localizationText == null)
|
||||||
{
|
{
|
||||||
Text = rawChapter.Text,
|
localizationText = new LocalizationText()
|
||||||
Language = novel.RawLanguage
|
{
|
||||||
};
|
Text = rawChapter.Text,
|
||||||
chapter.Body.Texts.Add(localizationText);
|
Language = novel.RawLanguage
|
||||||
|
};
|
||||||
|
chapter.Body.Texts.Add(localizationText);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
localizationText.Text = rawChapter.Text;
|
||||||
|
}
|
||||||
|
|
||||||
chapter.Images = rawChapter.ImageData.Select(img => new Image()
|
chapter.Images = rawChapter.ImageData.Select(img => new Image()
|
||||||
{
|
{
|
||||||
OriginalPath = img.Url
|
OriginalPath = img.Url
|
||||||
@@ -476,4 +488,49 @@ public class NovelUpdateService
|
|||||||
await _eventBus.Publish(chapterPullEvent);
|
await _eventBus.Publish(chapterPullEvent);
|
||||||
return chapterPullEvent;
|
return chapterPullEvent;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task DeleteNovel(uint novelId)
|
||||||
|
{
|
||||||
|
var novel = await _dbContext.Novels
|
||||||
|
.Include(n => n.CoverImage)
|
||||||
|
.Include(n => n.Name).ThenInclude(k => k.Texts)
|
||||||
|
.Include(n => n.Description).ThenInclude(k => k.Texts)
|
||||||
|
.Include(n => n.Chapters).ThenInclude(c => c.Images)
|
||||||
|
.Include(n => n.Chapters).ThenInclude(c => c.Name).ThenInclude(k => k.Texts)
|
||||||
|
.Include(n => n.Chapters).ThenInclude(c => c.Body).ThenInclude(k => k.Texts)
|
||||||
|
.FirstOrDefaultAsync(n => n.Id == novelId);
|
||||||
|
|
||||||
|
if (novel == null)
|
||||||
|
throw new KeyNotFoundException($"Novel with ID '{novelId}' not found");
|
||||||
|
|
||||||
|
// Collect all LocalizationKey IDs for cleanup
|
||||||
|
var locKeyIds = new List<Guid> { novel.Name.Id, novel.Description.Id };
|
||||||
|
locKeyIds.AddRange(novel.Chapters.Select(c => c.Name.Id));
|
||||||
|
locKeyIds.AddRange(novel.Chapters.Select(c => c.Body.Id));
|
||||||
|
|
||||||
|
// 1. Remove LocalizationRequests referencing these keys
|
||||||
|
var locRequests = await _dbContext.LocalizationRequests
|
||||||
|
.Where(r => locKeyIds.Contains(r.KeyRequestedForTranslation.Id))
|
||||||
|
.ToListAsync();
|
||||||
|
_dbContext.LocalizationRequests.RemoveRange(locRequests);
|
||||||
|
|
||||||
|
// 2. Remove LocalizationTexts (NO ACTION FK - won't cascade)
|
||||||
|
_dbContext.RemoveRange(novel.Name.Texts);
|
||||||
|
_dbContext.RemoveRange(novel.Description.Texts);
|
||||||
|
foreach (var chapter in novel.Chapters)
|
||||||
|
{
|
||||||
|
_dbContext.RemoveRange(chapter.Name.Texts);
|
||||||
|
_dbContext.RemoveRange(chapter.Body.Texts);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Remove Images (NO ACTION FK - won't cascade)
|
||||||
|
if (novel.CoverImage != null)
|
||||||
|
_dbContext.Images.Remove(novel.CoverImage);
|
||||||
|
foreach (var chapter in novel.Chapters)
|
||||||
|
_dbContext.Images.RemoveRange(chapter.Images);
|
||||||
|
|
||||||
|
// 4. Remove novel - cascades: chapters, localization keys, tag mappings
|
||||||
|
_dbContext.Novels.Remove(novel);
|
||||||
|
await _dbContext.SaveChangesAsync();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ using Microsoft.IdentityModel.Tokens;
|
|||||||
using FictionArchive.Service.Shared.Constants;
|
using FictionArchive.Service.Shared.Constants;
|
||||||
using FictionArchive.Service.Shared.Models.Authentication;
|
using FictionArchive.Service.Shared.Models.Authentication;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Security.Claims;
|
||||||
|
|
||||||
namespace FictionArchive.Service.Shared.Extensions;
|
namespace FictionArchive.Service.Shared.Extensions;
|
||||||
|
|
||||||
@@ -78,7 +79,7 @@ public static class AuthenticationExtensions
|
|||||||
|
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
"JWT token validated for subject: {Subject}",
|
"JWT token validated for subject: {Subject}",
|
||||||
context.Principal?.FindFirst("sub")?.Value ?? "unknown");
|
context.Principal?.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "unknown");
|
||||||
|
|
||||||
return existingEvents?.OnTokenValidated?.Invoke(context) ?? Task.CompletedTask;
|
return existingEvents?.OnTokenValidated?.Invoke(context) ?? Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ public static class GraphQLExtensions
|
|||||||
.AddErrorFilter<LoggingErrorFilter>()
|
.AddErrorFilter<LoggingErrorFilter>()
|
||||||
.AddType<UnsignedIntType>()
|
.AddType<UnsignedIntType>()
|
||||||
.AddType<InstantType>()
|
.AddType<InstantType>()
|
||||||
|
.ModifyCostOptions(opt => opt.MaxFieldCost = 10000)
|
||||||
.AddMutationConventions(applyToAllMutations: true)
|
.AddMutationConventions(applyToAllMutations: true)
|
||||||
.AddFiltering(opt => opt.AddDefaults().BindRuntimeType<uint, UnsignedIntOperationFilterInputType>())
|
.AddFiltering(opt => opt.AddDefaults().BindRuntimeType<uint, UnsignedIntOperationFilterInputType>())
|
||||||
.AddSorting()
|
.AddSorting()
|
||||||
|
|||||||
@@ -25,10 +25,12 @@
|
|||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="10.1.0" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
<PackageReference Include="NodaTime.Serialization.JsonNet" Version="3.2.0" />
|
<PackageReference Include="NodaTime.Serialization.JsonNet" Version="3.2.0" />
|
||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime" Version="9.0.4" />
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime" Version="9.0.4" />
|
||||||
|
<PackageReference Include="Polly" Version="8.6.5" />
|
||||||
<PackageReference Include="RabbitMQ.Client" Version="7.2.0" />
|
<PackageReference Include="RabbitMQ.Client" Version="7.2.0" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.11" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.11" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="FluentAssertions" Version="6.12.0" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="9.0.11" />
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
|
||||||
|
<PackageReference Include="NSubstitute" Version="5.1.0" />
|
||||||
|
<PackageReference Include="xunit" Version="2.9.2" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="coverlet.collector" Version="6.0.2">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\FictionArchive.Service.UserService\FictionArchive.Service.UserService.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,329 @@
|
|||||||
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
|
using FictionArchive.Service.UserService.Models.Database;
|
||||||
|
using FictionArchive.Service.UserService.Services;
|
||||||
|
using FictionArchive.Service.UserService.Services.AuthenticationClient;
|
||||||
|
using FictionArchive.Service.UserService.Services.AuthenticationClient.Authentik;
|
||||||
|
using FluentAssertions;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
using NSubstitute;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserService.Tests;
|
||||||
|
|
||||||
|
public class UserManagementServiceTests
|
||||||
|
{
|
||||||
|
#region Helper Methods
|
||||||
|
|
||||||
|
private static UserServiceDbContext CreateDbContext()
|
||||||
|
{
|
||||||
|
var options = new DbContextOptionsBuilder<UserServiceDbContext>()
|
||||||
|
.UseInMemoryDatabase($"UserManagementServiceTests-{Guid.NewGuid()}")
|
||||||
|
.Options;
|
||||||
|
|
||||||
|
return new UserServiceDbContext(options, NullLogger<UserServiceDbContext>.Instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static UserManagementService CreateService(
|
||||||
|
UserServiceDbContext dbContext,
|
||||||
|
IAuthenticationServiceClient authClient,
|
||||||
|
IEventBus? eventBus = null)
|
||||||
|
{
|
||||||
|
return new UserManagementService(
|
||||||
|
dbContext,
|
||||||
|
NullLogger<UserManagementService>.Instance,
|
||||||
|
authClient,
|
||||||
|
eventBus ?? Substitute.For<IEventBus>());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static User CreateTestUser(string username, string email, int availableInvites = 5)
|
||||||
|
{
|
||||||
|
return new User
|
||||||
|
{
|
||||||
|
Username = username,
|
||||||
|
Email = email,
|
||||||
|
OAuthProviderId = Guid.NewGuid().ToString(),
|
||||||
|
Disabled = false,
|
||||||
|
AvailableInvites = availableInvites
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region InviteUserAsync Tests
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task InviteUserAsync_WithValidInviter_CreatesUserAndDecrementsInvites()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
using var dbContext = CreateDbContext();
|
||||||
|
var inviter = CreateTestUser("inviter", "inviter@test.com", availableInvites: 3);
|
||||||
|
dbContext.Users.Add(inviter);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
authClient.CreateUserAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||||
|
.Returns(new AuthentikUserResponse { Pk = 123, Uid = "authentik-uid-456" });
|
||||||
|
authClient.SendRecoveryEmailAsync(Arg.Any<int>()).Returns(true);
|
||||||
|
|
||||||
|
var service = CreateService(dbContext, authClient);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await service.InviteUserAsync(inviter, "new@test.com", "newuser");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result!.Username.Should().Be("newuser");
|
||||||
|
result.Email.Should().Be("new@test.com");
|
||||||
|
result.InviterId.Should().Be(inviter.Id);
|
||||||
|
result.AvailableInvites.Should().Be(0);
|
||||||
|
inviter.AvailableInvites.Should().Be(2);
|
||||||
|
|
||||||
|
await authClient.Received(1).CreateUserAsync("newuser", "new@test.com", "newuser");
|
||||||
|
await authClient.Received(1).SendRecoveryEmailAsync(123);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task InviteUserAsync_WithNoAvailableInvites_ReturnsNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
using var dbContext = CreateDbContext();
|
||||||
|
var inviter = CreateTestUser("inviter", "inviter@test.com", availableInvites: 0);
|
||||||
|
dbContext.Users.Add(inviter);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
var service = CreateService(dbContext, authClient);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await service.InviteUserAsync(inviter, "new@test.com", "newuser");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
await authClient.DidNotReceive().CreateUserAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task InviteUserAsync_WithDuplicateEmail_ReturnsNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
using var dbContext = CreateDbContext();
|
||||||
|
var existingUser = CreateTestUser("existing", "existing@test.com");
|
||||||
|
var inviter = CreateTestUser("inviter", "inviter@test.com", availableInvites: 3);
|
||||||
|
dbContext.Users.AddRange(existingUser, inviter);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
var service = CreateService(dbContext, authClient);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await service.InviteUserAsync(inviter, "existing@test.com", "newuser");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
await authClient.DidNotReceive().CreateUserAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
|
||||||
|
inviter.AvailableInvites.Should().Be(3); // Not decremented
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task InviteUserAsync_WithDuplicateUsername_ReturnsNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
using var dbContext = CreateDbContext();
|
||||||
|
var existingUser = CreateTestUser("existinguser", "existing@test.com");
|
||||||
|
var inviter = CreateTestUser("inviter", "inviter@test.com", availableInvites: 3);
|
||||||
|
dbContext.Users.AddRange(existingUser, inviter);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
var service = CreateService(dbContext, authClient);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await service.InviteUserAsync(inviter, "new@test.com", "existinguser");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
await authClient.DidNotReceive().CreateUserAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
|
||||||
|
inviter.AvailableInvites.Should().Be(3); // Not decremented
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task InviteUserAsync_WhenAuthentikFails_ReturnsNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
using var dbContext = CreateDbContext();
|
||||||
|
var inviter = CreateTestUser("inviter", "inviter@test.com", availableInvites: 3);
|
||||||
|
dbContext.Users.Add(inviter);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
authClient.CreateUserAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||||
|
.Returns((AuthentikUserResponse?)null);
|
||||||
|
|
||||||
|
var service = CreateService(dbContext, authClient);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await service.InviteUserAsync(inviter, "new@test.com", "newuser");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
await authClient.DidNotReceive().SendRecoveryEmailAsync(Arg.Any<int>());
|
||||||
|
|
||||||
|
// Verify no user was added to the database
|
||||||
|
var usersInDb = await dbContext.Users.ToListAsync();
|
||||||
|
usersInDb.Should().HaveCount(1); // Only the inviter
|
||||||
|
inviter.AvailableInvites.Should().Be(3); // Not decremented
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task InviteUserAsync_WhenRecoveryEmailFails_StillCreatesUser()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
using var dbContext = CreateDbContext();
|
||||||
|
var inviter = CreateTestUser("inviter", "inviter@test.com", availableInvites: 3);
|
||||||
|
dbContext.Users.Add(inviter);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
authClient.CreateUserAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||||
|
.Returns(new AuthentikUserResponse { Pk = 123, Uid = "authentik-uid-456" });
|
||||||
|
authClient.SendRecoveryEmailAsync(Arg.Any<int>()).Returns(false); // Email fails
|
||||||
|
|
||||||
|
var service = CreateService(dbContext, authClient);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await service.InviteUserAsync(inviter, "new@test.com", "newuser");
|
||||||
|
|
||||||
|
// Assert - User should still be created despite email failure
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result!.Username.Should().Be("newuser");
|
||||||
|
inviter.AvailableInvites.Should().Be(2);
|
||||||
|
|
||||||
|
// Verify user was added to database
|
||||||
|
var usersInDb = await dbContext.Users.ToListAsync();
|
||||||
|
usersInDb.Should().HaveCount(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task InviteUserAsync_SetsCorrectUserProperties()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
using var dbContext = CreateDbContext();
|
||||||
|
var inviter = CreateTestUser("inviter", "inviter@test.com", availableInvites: 5);
|
||||||
|
dbContext.Users.Add(inviter);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
var authentikUid = "authentik-uid-789";
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
authClient.CreateUserAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||||
|
.Returns(new AuthentikUserResponse { Pk = 456, Uid = authentikUid });
|
||||||
|
authClient.SendRecoveryEmailAsync(Arg.Any<int>()).Returns(true);
|
||||||
|
|
||||||
|
var service = CreateService(dbContext, authClient);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await service.InviteUserAsync(inviter, "newuser@test.com", "newusername");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result!.Username.Should().Be("newusername");
|
||||||
|
result.Email.Should().Be("newuser@test.com");
|
||||||
|
result.OAuthProviderId.Should().Be(authentikUid);
|
||||||
|
result.InviterId.Should().Be(inviter.Id);
|
||||||
|
result.AvailableInvites.Should().Be(0);
|
||||||
|
result.Disabled.Should().BeFalse();
|
||||||
|
result.Id.Should().NotBeEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region GetUserByOAuthProviderIdAsync Tests
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetUserByOAuthProviderIdAsync_WithExistingUser_ReturnsUser()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
using var dbContext = CreateDbContext();
|
||||||
|
var oAuthProviderId = "oauth-provider-123";
|
||||||
|
var user = new User
|
||||||
|
{
|
||||||
|
Username = "testuser",
|
||||||
|
Email = "test@test.com",
|
||||||
|
OAuthProviderId = oAuthProviderId,
|
||||||
|
Disabled = false,
|
||||||
|
AvailableInvites = 5
|
||||||
|
};
|
||||||
|
dbContext.Users.Add(user);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
var service = CreateService(dbContext, authClient);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await service.GetUserByOAuthProviderIdAsync(oAuthProviderId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result!.Id.Should().Be(user.Id);
|
||||||
|
result.Username.Should().Be("testuser");
|
||||||
|
result.OAuthProviderId.Should().Be(oAuthProviderId);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetUserByOAuthProviderIdAsync_WithNonExistingUser_ReturnsNull()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
using var dbContext = CreateDbContext();
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
var service = CreateService(dbContext, authClient);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await service.GetUserByOAuthProviderIdAsync("non-existing-id");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region GetUsers Tests
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetUsers_ReturnsAllUsers()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
using var dbContext = CreateDbContext();
|
||||||
|
var user1 = CreateTestUser("user1", "user1@test.com");
|
||||||
|
var user2 = CreateTestUser("user2", "user2@test.com");
|
||||||
|
var user3 = CreateTestUser("user3", "user3@test.com");
|
||||||
|
dbContext.Users.AddRange(user1, user2, user3);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
var service = CreateService(dbContext, authClient);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await service.GetUsers().ToListAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().HaveCount(3);
|
||||||
|
result.Select(u => u.Username).Should().BeEquivalentTo(new[] { "user1", "user2", "user3" });
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetUsers_WithEmptyDb_ReturnsEmptyQueryable()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
using var dbContext = CreateDbContext();
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
var service = CreateService(dbContext, authClient);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await service.GetUsers().ToListAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().BeEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -22,6 +22,12 @@
|
|||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Folder Include="Models\IntegrationEvents\" />
|
||||||
|
<Folder Include="Services\EventHandlers\" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,38 +1,53 @@
|
|||||||
using FictionArchive.Service.Shared.Constants;
|
using System.Security.Claims;
|
||||||
using FictionArchive.Service.UserService.Models.DTOs;
|
using FictionArchive.Service.UserService.Models.DTOs;
|
||||||
using FictionArchive.Service.UserService.Services;
|
using FictionArchive.Service.UserService.Services;
|
||||||
using HotChocolate.Authorization;
|
using HotChocolate.Authorization;
|
||||||
|
using HotChocolate.Types;
|
||||||
|
|
||||||
namespace FictionArchive.Service.UserService.GraphQL;
|
namespace FictionArchive.Service.UserService.GraphQL;
|
||||||
|
|
||||||
public class Mutation
|
public class Mutation
|
||||||
{
|
{
|
||||||
[Authorize(Roles = [AuthorizationConstants.Roles.Admin])]
|
[Authorize]
|
||||||
public async Task<UserDto> RegisterUser(string username, string email, string oAuthProviderId,
|
[Error<InvalidOperationException>]
|
||||||
string? inviterOAuthProviderId, UserManagementService userManagementService)
|
public async Task<UserDto> InviteUser(
|
||||||
|
string email,
|
||||||
|
string username,
|
||||||
|
UserManagementService userManagementService,
|
||||||
|
ClaimsPrincipal claimsPrincipal)
|
||||||
{
|
{
|
||||||
var user = await userManagementService.RegisterUser(username, email, oAuthProviderId, inviterOAuthProviderId);
|
// Get the current user's OAuth provider ID from claims
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Unable to determine current user identity");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the inviter from the database
|
||||||
|
var inviter = await userManagementService.GetUserByOAuthProviderIdAsync(oAuthProviderId);
|
||||||
|
if (inviter == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Current user not found in the system");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invite the new user
|
||||||
|
var newUser = await userManagementService.InviteUserAsync(inviter, email, username);
|
||||||
|
if (newUser == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
"Failed to invite user. Either you have no available invites, or the email/username is already in use.");
|
||||||
|
}
|
||||||
|
|
||||||
return new UserDto
|
return new UserDto
|
||||||
{
|
{
|
||||||
Id = user.Id,
|
Id = newUser.Id,
|
||||||
CreatedTime = user.CreatedTime,
|
CreatedTime = newUser.CreatedTime,
|
||||||
LastUpdatedTime = user.LastUpdatedTime,
|
LastUpdatedTime = newUser.LastUpdatedTime,
|
||||||
Username = user.Username,
|
Username = newUser.Username,
|
||||||
Email = user.Email,
|
Email = newUser.Email,
|
||||||
Disabled = user.Disabled,
|
Disabled = newUser.Disabled,
|
||||||
Inviter = user.Inviter != null
|
AvailableInvites = newUser.AvailableInvites,
|
||||||
? new UserDto
|
InviterId = newUser.InviterId
|
||||||
{
|
|
||||||
Id = user.Inviter.Id,
|
|
||||||
CreatedTime = user.Inviter.CreatedTime,
|
|
||||||
LastUpdatedTime = user.Inviter.LastUpdatedTime,
|
|
||||||
Username = user.Inviter.Username,
|
|
||||||
Email = user.Inviter.Email,
|
|
||||||
Disabled = user.Inviter.Disabled,
|
|
||||||
Inviter = null // Limit recursion to one level
|
|
||||||
}
|
|
||||||
: null
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,34 +1,43 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
using FictionArchive.Service.UserService.Models.DTOs;
|
using FictionArchive.Service.UserService.Models.DTOs;
|
||||||
using FictionArchive.Service.UserService.Services;
|
using FictionArchive.Service.UserService.Services;
|
||||||
using HotChocolate.Authorization;
|
using HotChocolate.Authorization;
|
||||||
|
using HotChocolate.Data;
|
||||||
|
|
||||||
namespace FictionArchive.Service.UserService.GraphQL;
|
namespace FictionArchive.Service.UserService.GraphQL;
|
||||||
|
|
||||||
public class Query
|
public class Query
|
||||||
{
|
{
|
||||||
[Authorize]
|
[Authorize]
|
||||||
public IQueryable<UserDto> GetUsers(UserManagementService userManagementService)
|
[UseProjection]
|
||||||
|
[UseFirstOrDefault]
|
||||||
|
public IQueryable<UserDto> GetCurrentUser(
|
||||||
|
UserServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal)
|
||||||
{
|
{
|
||||||
return userManagementService.GetUsers().Select(user => new UserDto
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
{
|
{
|
||||||
Id = user.Id,
|
return Enumerable.Empty<UserDto>().AsQueryable();
|
||||||
CreatedTime = user.CreatedTime,
|
}
|
||||||
LastUpdatedTime = user.LastUpdatedTime,
|
|
||||||
Username = user.Username,
|
return dbContext.Users
|
||||||
Email = user.Email,
|
.Where(u => u.OAuthProviderId == oAuthProviderId)
|
||||||
Disabled = user.Disabled,
|
.Select(u => new UserDto
|
||||||
Inviter = user.Inviter != null
|
{
|
||||||
? new UserDto
|
Id = u.Id,
|
||||||
|
CreatedTime = u.CreatedTime,
|
||||||
|
LastUpdatedTime = u.LastUpdatedTime,
|
||||||
|
Username = u.Username,
|
||||||
|
Email = u.Email,
|
||||||
|
Disabled = u.Disabled,
|
||||||
|
AvailableInvites = u.AvailableInvites,
|
||||||
|
InviterId = u.InviterId,
|
||||||
|
InvitedUsers = u.InvitedUsers.Select(iu => new InvitedUserDto
|
||||||
{
|
{
|
||||||
Id = user.Inviter.Id,
|
Username = iu.Username,
|
||||||
CreatedTime = user.Inviter.CreatedTime,
|
Email = iu.Email
|
||||||
LastUpdatedTime = user.Inviter.LastUpdatedTime,
|
}).ToList()
|
||||||
Username = user.Inviter.Username,
|
});
|
||||||
Email = user.Inviter.Email,
|
|
||||||
Disabled = user.Inviter.Disabled,
|
|
||||||
Inviter = null // Limit recursion to one level
|
|
||||||
}
|
|
||||||
: null
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
83
FictionArchive.Service.UserService/Migrations/20251229151921_AddAvailableInvites.Designer.cs
generated
Normal file
83
FictionArchive.Service.UserService/Migrations/20251229151921_AddAvailableInvites.Designer.cs
generated
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using FictionArchive.Service.UserService.Services;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
using NodaTime;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserService.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(UserServiceDbContext))]
|
||||||
|
[Migration("20251229151921_AddAvailableInvites")]
|
||||||
|
partial class AddAvailableInvites
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder
|
||||||
|
.HasAnnotation("ProductVersion", "9.0.11")
|
||||||
|
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||||
|
|
||||||
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<int>("AvailableInvites")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<bool>("Disabled")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<string>("Email")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Guid?>("InviterId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("OAuthProviderId")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("Username")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("InviterId");
|
||||||
|
|
||||||
|
b.HasIndex("OAuthProviderId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("Users");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserService.Models.Database.User", "Inviter")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("InviterId");
|
||||||
|
|
||||||
|
b.Navigation("Inviter");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserService.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddAvailableInvites : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<int>(
|
||||||
|
name: "AvailableInvites",
|
||||||
|
table: "Users",
|
||||||
|
type: "integer",
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "AvailableInvites",
|
||||||
|
table: "Users");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,6 +29,9 @@ namespace FictionArchive.Service.UserService.Migrations
|
|||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
.HasColumnType("uuid");
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<int>("AvailableInvites")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
b.Property<Instant>("CreatedTime")
|
b.Property<Instant>("CreatedTime")
|
||||||
.HasColumnType("timestamp with time zone");
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace FictionArchive.Service.UserService.Models.DTOs;
|
||||||
|
|
||||||
|
public class InvitedUserDto
|
||||||
|
{
|
||||||
|
public required string Username { get; init; }
|
||||||
|
public required string Email { get; init; }
|
||||||
|
}
|
||||||
@@ -7,9 +7,11 @@ public class UserDto
|
|||||||
public Guid Id { get; init; }
|
public Guid Id { get; init; }
|
||||||
public Instant CreatedTime { get; init; }
|
public Instant CreatedTime { get; init; }
|
||||||
public Instant LastUpdatedTime { get; init; }
|
public Instant LastUpdatedTime { get; init; }
|
||||||
|
|
||||||
public required string Username { get; init; }
|
public required string Username { get; init; }
|
||||||
public required string Email { get; init; }
|
public required string Email { get; init; }
|
||||||
// OAuthProviderId intentionally omitted for security
|
|
||||||
public bool Disabled { get; init; }
|
public bool Disabled { get; init; }
|
||||||
public UserDto? Inviter { get; init; }
|
public int AvailableInvites { get; init; }
|
||||||
|
public Guid? InviterId { get; init; }
|
||||||
|
public List<InvitedUserDto>? InvitedUsers { get; init; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,15 +6,14 @@ namespace FictionArchive.Service.UserService.Models.Database;
|
|||||||
[Index(nameof(OAuthProviderId), IsUnique = true)]
|
[Index(nameof(OAuthProviderId), IsUnique = true)]
|
||||||
public class User : BaseEntity<Guid>
|
public class User : BaseEntity<Guid>
|
||||||
{
|
{
|
||||||
public string Username { get; set; }
|
public required string Username { get; set; }
|
||||||
public string Email { get; set; }
|
public required string Email { get; set; }
|
||||||
public string OAuthProviderId { get; set; }
|
public required string OAuthProviderId { get; set; }
|
||||||
|
|
||||||
|
|
||||||
public bool Disabled { get; set; }
|
public bool Disabled { get; set; }
|
||||||
|
public int AvailableInvites { get; set; } = 0;
|
||||||
/// <summary>
|
|
||||||
/// The user that generated an invite used by this user.
|
// Navigation properties
|
||||||
/// </summary>
|
public Guid? InviterId { get; set; }
|
||||||
public User? Inviter { get; set; }
|
public User? Inviter { get; set; }
|
||||||
|
public ICollection<User> InvitedUsers { get; set; } = new List<User>();
|
||||||
}
|
}
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.UserService.Models.IntegrationEvents;
|
|
||||||
|
|
||||||
public class AuthUserAddedEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
public string OAuthProviderId { get; set; }
|
|
||||||
|
|
||||||
public string InviterOAuthProviderId { get; set; }
|
|
||||||
|
|
||||||
// The email of the user that created the event
|
|
||||||
public string EventUserEmail { get; set; }
|
|
||||||
|
|
||||||
// The username of the user that created the event
|
|
||||||
public string EventUserUsername { get; set; }
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserService.Models.IntegrationEvents;
|
||||||
|
|
||||||
|
public class UserInvitedEvent : IIntegrationEvent
|
||||||
|
{
|
||||||
|
// Invited user info
|
||||||
|
public Guid InvitedUserId { get; set; }
|
||||||
|
public required string InvitedUsername { get; set; }
|
||||||
|
public required string InvitedEmail { get; set; }
|
||||||
|
public required string InvitedOAuthProviderId { get; set; }
|
||||||
|
|
||||||
|
// Inviter info
|
||||||
|
public Guid InviterId { get; set; }
|
||||||
|
public required string InviterUsername { get; set; }
|
||||||
|
public required string InviterOAuthProviderId { get; set; }
|
||||||
|
}
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
|
using System.Net.Http.Headers;
|
||||||
using FictionArchive.Common.Extensions;
|
using FictionArchive.Common.Extensions;
|
||||||
using FictionArchive.Service.Shared;
|
using FictionArchive.Service.Shared;
|
||||||
using FictionArchive.Service.Shared.Extensions;
|
using FictionArchive.Service.Shared.Extensions;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
||||||
using FictionArchive.Service.UserService.GraphQL;
|
using FictionArchive.Service.UserService.GraphQL;
|
||||||
using FictionArchive.Service.UserService.Models.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.UserService.Services;
|
using FictionArchive.Service.UserService.Services;
|
||||||
using FictionArchive.Service.UserService.Services.EventHandlers;
|
using FictionArchive.Service.UserService.Services.AuthenticationClient;
|
||||||
|
using FictionArchive.Service.UserService.Services.AuthenticationClient.Authentik;
|
||||||
|
|
||||||
namespace FictionArchive.Service.UserService;
|
namespace FictionArchive.Service.UserService;
|
||||||
|
|
||||||
@@ -25,19 +26,34 @@ public class Program
|
|||||||
builder.Services.AddRabbitMQ(opt =>
|
builder.Services.AddRabbitMQ(opt =>
|
||||||
{
|
{
|
||||||
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
|
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
|
||||||
})
|
});
|
||||||
.Subscribe<AuthUserAddedEvent, AuthUserAddedEventHandler>();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region GraphQL
|
#region GraphQL
|
||||||
|
|
||||||
builder.Services.AddDefaultGraphQl<Query, Mutation>()
|
builder.Services.AddDefaultGraphQl<Query, Mutation>()
|
||||||
.AddAuthorization();
|
.AddAuthorization();
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
#region Authentik Client
|
||||||
|
|
||||||
|
builder.Services.Configure<AuthentikConfiguration>(
|
||||||
|
builder.Configuration.GetSection("Authentik"));
|
||||||
|
|
||||||
|
var authentikConfig = builder.Configuration.GetSection("Authentik").Get<AuthentikConfiguration>();
|
||||||
|
builder.Services.AddHttpClient<IAuthenticationServiceClient, AuthentikClient>(client =>
|
||||||
|
{
|
||||||
|
client.BaseAddress = new Uri(authentikConfig?.BaseUrl ?? "https://localhost");
|
||||||
|
client.DefaultRequestHeaders.Authorization =
|
||||||
|
new AuthenticationHeaderValue("Bearer", authentikConfig?.ApiToken ?? "");
|
||||||
|
})
|
||||||
|
.AddStandardResilienceHandler();
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
builder.Services.RegisterDbContext<UserServiceDbContext>(
|
builder.Services.RegisterDbContext<UserServiceDbContext>(
|
||||||
builder.Configuration.GetConnectionString("DefaultConnection"),
|
builder.Configuration.GetConnectionString("DefaultConnection"),
|
||||||
skipInfrastructure: isSchemaExport);
|
skipInfrastructure: isSchemaExport);
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserService.Services.AuthenticationClient.Authentik;
|
||||||
|
|
||||||
|
public class AuthentikAddUserRequest
|
||||||
|
{
|
||||||
|
[JsonProperty("username")]
|
||||||
|
public required string Username { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("name")]
|
||||||
|
public required string DisplayName { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("email")]
|
||||||
|
public required string Email { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("is_active")]
|
||||||
|
public bool IsActive { get; set; } = true;
|
||||||
|
|
||||||
|
[JsonProperty("type")]
|
||||||
|
public string Type { get; } = "external";
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserService.Services.AuthenticationClient.Authentik;
|
||||||
|
|
||||||
|
public class AuthentikClient : IAuthenticationServiceClient
|
||||||
|
{
|
||||||
|
private readonly HttpClient _httpClient;
|
||||||
|
private readonly ILogger<AuthentikClient> _logger;
|
||||||
|
private readonly AuthentikConfiguration _configuration;
|
||||||
|
|
||||||
|
public AuthentikClient(
|
||||||
|
HttpClient httpClient,
|
||||||
|
ILogger<AuthentikClient> logger,
|
||||||
|
IOptions<AuthentikConfiguration> configuration)
|
||||||
|
{
|
||||||
|
_httpClient = httpClient;
|
||||||
|
_logger = logger;
|
||||||
|
_configuration = configuration.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AuthentikUserResponse?> CreateUserAsync(string username, string email, string displayName)
|
||||||
|
{
|
||||||
|
var request = new AuthentikAddUserRequest
|
||||||
|
{
|
||||||
|
Username = username,
|
||||||
|
Email = email,
|
||||||
|
DisplayName = displayName,
|
||||||
|
IsActive = true
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var json = JsonConvert.SerializeObject(request);
|
||||||
|
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||||
|
var response = await _httpClient.PostAsync("/api/v3/core/users/", content);
|
||||||
|
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
var errorContent = await response.Content.ReadAsStringAsync();
|
||||||
|
_logger.LogError(
|
||||||
|
"Failed to create user in Authentik. Status: {StatusCode}, Error: {Error}",
|
||||||
|
response.StatusCode, errorContent);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var responseJson = await response.Content.ReadAsStringAsync();
|
||||||
|
var userResponse = JsonConvert.DeserializeObject<AuthentikUserResponse>(responseJson);
|
||||||
|
_logger.LogInformation("Successfully created user {Username} in Authentik with pk {Pk}",
|
||||||
|
username, userResponse?.Pk);
|
||||||
|
|
||||||
|
return userResponse;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Exception while creating user {Username} in Authentik", username);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> SendRecoveryEmailAsync(int authentikUserId)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var response = await _httpClient.PostAsync(
|
||||||
|
$"/api/v3/core/users/{authentikUserId}/recovery_email/?email_stage={_configuration.EmailStageId}",
|
||||||
|
null);
|
||||||
|
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
var errorContent = await response.Content.ReadAsStringAsync();
|
||||||
|
_logger.LogError(
|
||||||
|
"Failed to send recovery email for user {UserId}. Status: {StatusCode}, Error: {Error}",
|
||||||
|
authentikUserId, response.StatusCode, errorContent);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("Successfully sent recovery email to Authentik user {UserId}", authentikUserId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Exception while sending recovery email to Authentik user {UserId}", authentikUserId);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace FictionArchive.Service.UserService.Services.AuthenticationClient.Authentik;
|
||||||
|
|
||||||
|
public class AuthentikConfiguration
|
||||||
|
{
|
||||||
|
public string BaseUrl { get; set; } = string.Empty;
|
||||||
|
public string ApiToken { get; set; } = string.Empty;
|
||||||
|
public string EmailStageId { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserService.Services.AuthenticationClient.Authentik;
|
||||||
|
|
||||||
|
public class AuthentikUserResponse
|
||||||
|
{
|
||||||
|
[JsonProperty("pk")]
|
||||||
|
public int Pk { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("username")]
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonProperty("name")]
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonProperty("email")]
|
||||||
|
public string Email { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonProperty("is_active")]
|
||||||
|
public bool IsActive { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("is_superuser")]
|
||||||
|
public bool IsSuperuser { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("uid")]
|
||||||
|
public string Uid { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using FictionArchive.Service.UserService.Services.AuthenticationClient.Authentik;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserService.Services.AuthenticationClient;
|
||||||
|
|
||||||
|
public interface IAuthenticationServiceClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a new user in the authentication provider.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="username">The username for the new user</param>
|
||||||
|
/// <param name="email">The email address for the new user</param>
|
||||||
|
/// <param name="displayName">The display name for the new user</param>
|
||||||
|
/// <returns>The created user response, or null if creation failed</returns>
|
||||||
|
Task<AuthentikUserResponse?> CreateUserAsync(string username, string email, string displayName);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sends a password recovery email to the user.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="authentikUserId">The Authentik user ID (pk)</param>
|
||||||
|
/// <returns>True if the email was sent successfully, false otherwise</returns>
|
||||||
|
Task<bool> SendRecoveryEmailAsync(int authentikUserId);
|
||||||
|
}
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
using FictionArchive.Service.UserService.Models.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.UserService.Models.Database;
|
|
||||||
using Microsoft.EntityFrameworkCore; // Add this line to include the UserModel
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.UserService.Services.EventHandlers;
|
|
||||||
|
|
||||||
public class AuthUserAddedEventHandler : IIntegrationEventHandler<AuthUserAddedEvent>
|
|
||||||
{
|
|
||||||
private readonly UserManagementService _userManagementService;
|
|
||||||
private readonly ILogger<AuthUserAddedEventHandler> _logger;
|
|
||||||
|
|
||||||
public AuthUserAddedEventHandler(UserServiceDbContext dbContext, ILogger<AuthUserAddedEventHandler> logger, UserManagementService userManagementService)
|
|
||||||
{
|
|
||||||
_logger = logger;
|
|
||||||
_userManagementService = userManagementService;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Handle(AuthUserAddedEvent @event)
|
|
||||||
{
|
|
||||||
await _userManagementService.RegisterUser(@event.EventUserUsername, @event.EventUserEmail, @event.OAuthProviderId, @event.InviterOAuthProviderId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
using FictionArchive.Service.UserService.Models.Database;
|
using FictionArchive.Service.UserService.Models.Database;
|
||||||
|
using FictionArchive.Service.UserService.Models.IntegrationEvents;
|
||||||
|
using FictionArchive.Service.UserService.Services.AuthenticationClient;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace FictionArchive.Service.UserService.Services;
|
namespace FictionArchive.Service.UserService.Services;
|
||||||
@@ -7,39 +10,142 @@ public class UserManagementService
|
|||||||
{
|
{
|
||||||
private readonly ILogger<UserManagementService> _logger;
|
private readonly ILogger<UserManagementService> _logger;
|
||||||
private readonly UserServiceDbContext _dbContext;
|
private readonly UserServiceDbContext _dbContext;
|
||||||
|
private readonly IAuthenticationServiceClient _authClient;
|
||||||
|
private readonly IEventBus _eventBus;
|
||||||
|
|
||||||
public UserManagementService(UserServiceDbContext dbContext, ILogger<UserManagementService> logger)
|
public UserManagementService(
|
||||||
|
UserServiceDbContext dbContext,
|
||||||
|
ILogger<UserManagementService> logger,
|
||||||
|
IAuthenticationServiceClient authClient,
|
||||||
|
IEventBus eventBus)
|
||||||
{
|
{
|
||||||
_dbContext = dbContext;
|
_dbContext = dbContext;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
_authClient = authClient;
|
||||||
|
_eventBus = eventBus;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<User> RegisterUser(string username, string email, string oAuthProviderId,
|
/// <summary>
|
||||||
string? inviterOAuthProviderId)
|
/// Invites a new user by creating them in Authentik, saving to the database, and sending a recovery email.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="inviter">The user sending the invite</param>
|
||||||
|
/// <param name="email">Email address of the invitee</param>
|
||||||
|
/// <param name="username">Username for the invitee</param>
|
||||||
|
/// <returns>The created user, or null if the invite failed</returns>
|
||||||
|
public async Task<User?> InviteUserAsync(User inviter, string email, string username)
|
||||||
{
|
{
|
||||||
var newUser = new User();
|
// Check if inviter has available invites
|
||||||
User? inviter =
|
if (inviter.AvailableInvites <= 0)
|
||||||
await _dbContext.Users.FirstOrDefaultAsync(user => user.OAuthProviderId == inviterOAuthProviderId);
|
|
||||||
if (inviter == null && inviterOAuthProviderId != null)
|
|
||||||
{
|
{
|
||||||
_logger.LogCritical(
|
_logger.LogWarning("User {InviterId} has no available invites", inviter.Id);
|
||||||
"A user with OAuthProviderId {OAuthProviderId} was marked as having inviter with OAuthProviderId {inviterOAuthProviderId}, but no user was found with that value.",
|
return null;
|
||||||
inviterOAuthProviderId, inviterOAuthProviderId);
|
|
||||||
newUser.Disabled = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
newUser.Username = username;
|
// Check if email is already in use
|
||||||
newUser.Email = email;
|
var existingUser = await _dbContext.Users
|
||||||
newUser.OAuthProviderId = oAuthProviderId;
|
.AsQueryable()
|
||||||
|
.FirstOrDefaultAsync(u => u.Email == email);
|
||||||
|
|
||||||
|
if (existingUser != null)
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Email {Email} is already in use", email);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if username is already in use
|
||||||
|
var existingUsername = await _dbContext.Users
|
||||||
|
.AsQueryable()
|
||||||
|
.FirstOrDefaultAsync(u => u.Username == username);
|
||||||
|
|
||||||
|
if (existingUsername != null)
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Username {Username} is already in use", username);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create user in Authentik
|
||||||
|
var authentikUser = await _authClient.CreateUserAsync(username, email, username);
|
||||||
|
if (authentikUser == null)
|
||||||
|
{
|
||||||
|
_logger.LogError("Failed to create user {Username} in Authentik", username);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send recovery email via Authentik
|
||||||
|
var emailSent = await _authClient.SendRecoveryEmailAsync(authentikUser.Pk);
|
||||||
|
if (!emailSent)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(
|
||||||
|
"User {Username} was created in Authentik but recovery email failed to send. Authentik pk: {Pk}",
|
||||||
|
username, authentikUser.Pk);
|
||||||
|
// Continue anyway - the user is created, admin can resend email manually
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create user in local database
|
||||||
|
var newUser = new User
|
||||||
|
{
|
||||||
|
Username = username,
|
||||||
|
Email = email,
|
||||||
|
OAuthProviderId = authentikUser.Uid,
|
||||||
|
Disabled = false,
|
||||||
|
AvailableInvites = 0,
|
||||||
|
InviterId = inviter.Id
|
||||||
|
};
|
||||||
|
|
||||||
|
_dbContext.Users.Add(newUser);
|
||||||
|
|
||||||
|
// Decrement inviter's available invites
|
||||||
|
inviter.AvailableInvites--;
|
||||||
|
|
||||||
|
await _dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
await _eventBus.Publish(new UserInvitedEvent
|
||||||
|
{
|
||||||
|
InvitedUserId = newUser.Id,
|
||||||
|
InvitedUsername = newUser.Username,
|
||||||
|
InvitedEmail = newUser.Email,
|
||||||
|
InvitedOAuthProviderId = newUser.OAuthProviderId,
|
||||||
|
InviterId = inviter.Id,
|
||||||
|
InviterUsername = inviter.Username,
|
||||||
|
InviterOAuthProviderId = inviter.OAuthProviderId
|
||||||
|
});
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"User {Username} was successfully invited by {InviterId}. New user id: {NewUserId}",
|
||||||
|
username, inviter.Id, newUser.Id);
|
||||||
|
|
||||||
_dbContext.Users.Add(newUser); // Add the new user to the DbContext
|
|
||||||
await _dbContext.SaveChangesAsync(); // Save changes to the database
|
|
||||||
|
|
||||||
return newUser;
|
return newUser;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets a user by their OAuth provider ID (Authentik UID).
|
||||||
|
/// </summary>
|
||||||
|
public async Task<User?> GetUserByOAuthProviderIdAsync(string oAuthProviderId)
|
||||||
|
{
|
||||||
|
return await _dbContext.Users
|
||||||
|
.AsQueryable()
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets all users as a queryable for GraphQL.
|
||||||
|
/// </summary>
|
||||||
public IQueryable<User> GetUsers()
|
public IQueryable<User> GetUsers()
|
||||||
{
|
{
|
||||||
return _dbContext.Users.AsQueryable();
|
return _dbContext.Users.AsQueryable();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets all users invited by a specific user.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="inviterId">The ID of the user who sent the invites</param>
|
||||||
|
/// <returns>List of users invited by the specified user</returns>
|
||||||
|
public async Task<List<User>> GetInvitedByUserAsync(Guid inviterId)
|
||||||
|
{
|
||||||
|
return await _dbContext.Users
|
||||||
|
.AsQueryable()
|
||||||
|
.Where(u => u.InviterId == inviterId)
|
||||||
|
.OrderByDescending(u => u.CreatedTime)
|
||||||
|
.ToListAsync();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,7 @@ namespace FictionArchive.Service.UserService.Services;
|
|||||||
public class UserServiceDbContext : FictionArchiveDbContext
|
public class UserServiceDbContext : FictionArchiveDbContext
|
||||||
{
|
{
|
||||||
public DbSet<User> Users { get; set; }
|
public DbSet<User> Users { get; set; }
|
||||||
|
|
||||||
public UserServiceDbContext(DbContextOptions options, ILogger<UserServiceDbContext> logger) : base(options, logger)
|
public UserServiceDbContext(DbContextOptions options, ILogger<UserServiceDbContext> logger) : base(options, logger)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,11 @@
|
|||||||
"ConnectionString": "amqp://localhost",
|
"ConnectionString": "amqp://localhost",
|
||||||
"ClientIdentifier": "UserService"
|
"ClientIdentifier": "UserService"
|
||||||
},
|
},
|
||||||
|
"Authentik": {
|
||||||
|
"BaseUrl": "https://auth.orfl.xyz",
|
||||||
|
"ApiToken": "REPLACE_ME",
|
||||||
|
"EmailStageId": "10df0c18-8802-4ec7-852e-3cdd355514d3"
|
||||||
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
"OIDC": {
|
"OIDC": {
|
||||||
"Authority": "https://auth.orfl.xyz/application/o/fiction-archive/",
|
"Authority": "https://auth.orfl.xyz/application/o/fiction-archive/",
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
|
#
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Common", "FictionArchive.Common\FictionArchive.Common.csproj", "{ABF1BA10-9E76-45BE-9947-E20445A68147}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Common", "FictionArchive.Common\FictionArchive.Common.csproj", "{ABF1BA10-9E76-45BE-9947-E20445A68147}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.API", "FictionArchive.API\FictionArchive.API.csproj", "{420CC1A1-9DBC-40EC-B9E3-D4B25D71B9A9}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.API", "FictionArchive.API\FictionArchive.API.csproj", "{420CC1A1-9DBC-40EC-B9E3-D4B25D71B9A9}"
|
||||||
@@ -14,12 +15,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.Sche
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.UserService", "FictionArchive.Service.UserService\FictionArchive.Service.UserService.csproj", "{EE4D4795-2F79-4614-886D-AF8DA77120AC}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.UserService", "FictionArchive.Service.UserService\FictionArchive.Service.UserService.csproj", "{EE4D4795-2F79-4614-886D-AF8DA77120AC}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.AuthenticationService", "FictionArchive.Service.AuthenticationService\FictionArchive.Service.AuthenticationService.csproj", "{70C4AE82-B01E-421D-B590-C0F47E63CD0C}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.FileService", "FictionArchive.Service.FileService\FictionArchive.Service.FileService.csproj", "{EC64A336-F8A0-4BED-9CA3-1B05AD00631D}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.FileService", "FictionArchive.Service.FileService\FictionArchive.Service.FileService.csproj", "{EC64A336-F8A0-4BED-9CA3-1B05AD00631D}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.NovelService.Tests", "FictionArchive.Service.NovelService.Tests\FictionArchive.Service.NovelService.Tests.csproj", "{166E645E-9DFB-44E8-8CC8-FA249A11679F}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.NovelService.Tests", "FictionArchive.Service.NovelService.Tests\FictionArchive.Service.NovelService.Tests.csproj", "{166E645E-9DFB-44E8-8CC8-FA249A11679F}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.UserService.Tests", "FictionArchive.Service.UserService.Tests\FictionArchive.Service.UserService.Tests.csproj", "{10C38C89-983D-4544-8911-F03099F66AB8}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -54,10 +55,6 @@ Global
|
|||||||
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Release|Any CPU.Build.0 = Release|Any CPU
|
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{EC64A336-F8A0-4BED-9CA3-1B05AD00631D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{EC64A336-F8A0-4BED-9CA3-1B05AD00631D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{EC64A336-F8A0-4BED-9CA3-1B05AD00631D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{EC64A336-F8A0-4BED-9CA3-1B05AD00631D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{EC64A336-F8A0-4BED-9CA3-1B05AD00631D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{EC64A336-F8A0-4BED-9CA3-1B05AD00631D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
@@ -66,5 +63,9 @@ Global
|
|||||||
{166E645E-9DFB-44E8-8CC8-FA249A11679F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{166E645E-9DFB-44E8-8CC8-FA249A11679F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{166E645E-9DFB-44E8-8CC8-FA249A11679F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{166E645E-9DFB-44E8-8CC8-FA249A11679F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{166E645E-9DFB-44E8-8CC8-FA249A11679F}.Release|Any CPU.Build.0 = Release|Any CPU
|
{166E645E-9DFB-44E8-8CC8-FA249A11679F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{10C38C89-983D-4544-8911-F03099F66AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{10C38C89-983D-4544-8911-F03099F66AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{10C38C89-983D-4544-8911-F03099F66AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{10C38C89-983D-4544-8911-F03099F66AB8}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
EndGlobal
|
EndGlobal
|
||||||
|
|||||||
@@ -44,6 +44,12 @@
|
|||||||
<div
|
<div
|
||||||
class="absolute right-0 z-50 mt-2 w-48 rounded-md bg-white p-2 shadow-lg dark:bg-gray-800"
|
class="absolute right-0 z-50 mt-2 w-48 rounded-md bg-white p-2 shadow-lg dark:bg-gray-800"
|
||||||
>
|
>
|
||||||
|
<a
|
||||||
|
href="/settings"
|
||||||
|
class="flex w-full items-center justify-start rounded-md px-4 py-2 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||||
|
>
|
||||||
|
Settings
|
||||||
|
</a>
|
||||||
<Button variant="ghost" class="w-full justify-start" onclick={handleLogout}>
|
<Button variant="ghost" class="w-full justify-start" onclick={handleLogout}>
|
||||||
Sign out
|
Sign out
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -74,6 +74,8 @@
|
|||||||
|
|
||||||
if (result.data?.chapter) {
|
if (result.data?.chapter) {
|
||||||
chapter = result.data.chapter;
|
chapter = result.data.chapter;
|
||||||
|
// Update the page title with chapter info
|
||||||
|
document.title = `${chapter.novelName} - ${chapter.order}`;
|
||||||
} else {
|
} else {
|
||||||
error = 'Chapter not found';
|
error = 'Chapter not found';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { Input } from '$lib/components/ui/input';
|
|
||||||
import * as NavigationMenu from '$lib/components/ui/navigation-menu';
|
import * as NavigationMenu from '$lib/components/ui/navigation-menu';
|
||||||
import AuthenticationDisplay from './AuthenticationDisplay.svelte';
|
import AuthenticationDisplay from './AuthenticationDisplay.svelte';
|
||||||
|
import SearchBar from './SearchBar.svelte';
|
||||||
|
|
||||||
let pathname = $state(typeof window !== 'undefined' ? window.location.pathname : '/');
|
let pathname = $state(typeof window !== 'undefined' ? window.location.pathname : '/');
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@
|
|||||||
</NavigationMenu.List>
|
</NavigationMenu.List>
|
||||||
</NavigationMenu.Root>
|
</NavigationMenu.Root>
|
||||||
<div class="flex-1"></div>
|
<div class="flex-1"></div>
|
||||||
<Input type="search" placeholder="Search..." class="max-w-xs" />
|
<SearchBar />
|
||||||
<AuthenticationDisplay />
|
<AuthenticationDisplay />
|
||||||
</nav>
|
</nav>
|
||||||
</header>
|
</header>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
<script lang="ts" module>
|
<script lang="ts" module>
|
||||||
import type { NovelsQuery, NovelStatus } from '$lib/graphql/__generated__/graphql';
|
import type { NovelsQuery, NovelStatus } from '$lib/graphql/__generated__/graphql';
|
||||||
|
import { SystemTags } from '$lib/constants/systemTags';
|
||||||
|
|
||||||
export type NovelNode = NonNullable<NonNullable<NovelsQuery['novels']>['edges']>[number]['node'];
|
export type NovelNode = NonNullable<NonNullable<NovelsQuery['novels']>['edges']>[number]['node'];
|
||||||
|
|
||||||
@@ -55,6 +56,8 @@
|
|||||||
const status = $derived(novel.rawStatus ?? 'UNKNOWN');
|
const status = $derived(novel.rawStatus ?? 'UNKNOWN');
|
||||||
const statusColor = $derived(statusColors[status]);
|
const statusColor = $derived(statusColors[status]);
|
||||||
const statusLabel = $derived(statusLabels[status]);
|
const statusLabel = $derived(statusLabels[status]);
|
||||||
|
|
||||||
|
const isNsfw = $derived(novel.tags?.some((tag) => tag.key === SystemTags.Nsfw) ?? false);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<a
|
<a
|
||||||
@@ -76,6 +79,9 @@
|
|||||||
>
|
>
|
||||||
{statusLabel}
|
{statusLabel}
|
||||||
</Badge>
|
</Badge>
|
||||||
|
{#if isNsfw}
|
||||||
|
<Badge class="absolute top-9 right-2 bg-red-600 text-white shadow-sm">NSFW</Badge>
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
<CardHeader class="space-y-2 pt-4">
|
<CardHeader class="space-y-2 pt-4">
|
||||||
<CardTitle class="line-clamp-2 text-lg leading-tight" title={title}>
|
<CardTitle class="line-clamp-2 text-lg leading-tight" title={title}>
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
<script lang="ts" module>
|
<script lang="ts" module>
|
||||||
import type { NovelQuery, NovelStatus, Language } from '$lib/graphql/__generated__/graphql';
|
import type { NovelQuery, NovelStatus, Language } from '$lib/graphql/__generated__/graphql';
|
||||||
|
import { TagType } from '$lib/graphql/__generated__/graphql';
|
||||||
|
import { SystemTags } from '$lib/constants/systemTags';
|
||||||
|
|
||||||
export type NovelNode = NonNullable<NonNullable<NovelQuery['novels']>['nodes']>[number];
|
export type NovelNode = NonNullable<NonNullable<NovelQuery['novels']>['nodes']>[number];
|
||||||
|
|
||||||
@@ -30,7 +32,7 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import { client } from '$lib/graphql/client';
|
import { client } from '$lib/graphql/client';
|
||||||
import { NovelDocument, ImportNovelDocument } from '$lib/graphql/__generated__/graphql';
|
import { NovelDocument, ImportNovelDocument, DeleteNovelDocument } from '$lib/graphql/__generated__/graphql';
|
||||||
import { isAuthenticated } from '$lib/auth/authStore';
|
import { isAuthenticated } from '$lib/auth/authStore';
|
||||||
import { Card, CardContent, CardHeader } from '$lib/components/ui/card';
|
import { Card, CardContent, CardHeader } from '$lib/components/ui/card';
|
||||||
import { Badge } from '$lib/components/ui/badge';
|
import { Badge } from '$lib/components/ui/badge';
|
||||||
@@ -51,6 +53,7 @@
|
|||||||
import ChevronDown from '@lucide/svelte/icons/chevron-down';
|
import ChevronDown from '@lucide/svelte/icons/chevron-down';
|
||||||
import ChevronUp from '@lucide/svelte/icons/chevron-up';
|
import ChevronUp from '@lucide/svelte/icons/chevron-up';
|
||||||
import RefreshCw from '@lucide/svelte/icons/refresh-cw';
|
import RefreshCw from '@lucide/svelte/icons/refresh-cw';
|
||||||
|
import Trash2 from '@lucide/svelte/icons/trash-2';
|
||||||
import X from '@lucide/svelte/icons/x';
|
import X from '@lucide/svelte/icons/x';
|
||||||
import ChevronLeft from '@lucide/svelte/icons/chevron-left';
|
import ChevronLeft from '@lucide/svelte/icons/chevron-left';
|
||||||
import ChevronRight from '@lucide/svelte/icons/chevron-right';
|
import ChevronRight from '@lucide/svelte/icons/chevron-right';
|
||||||
@@ -69,6 +72,11 @@
|
|||||||
let refreshError: string | null = $state(null);
|
let refreshError: string | null = $state(null);
|
||||||
let refreshSuccess = $state(false);
|
let refreshSuccess = $state(false);
|
||||||
|
|
||||||
|
// Delete state
|
||||||
|
let showDeleteConfirm = $state(false);
|
||||||
|
let deleting = $state(false);
|
||||||
|
let deleteError: string | null = $state(null);
|
||||||
|
|
||||||
// Image viewer state
|
// Image viewer state
|
||||||
type GalleryImage = {
|
type GalleryImage = {
|
||||||
src: string;
|
src: string;
|
||||||
@@ -80,6 +88,8 @@
|
|||||||
};
|
};
|
||||||
let viewerOpen = $state(false);
|
let viewerOpen = $state(false);
|
||||||
let viewerIndex = $state(0);
|
let viewerIndex = $state(0);
|
||||||
|
let activeTab = $state('chapters');
|
||||||
|
let galleryLoaded = $state(false);
|
||||||
|
|
||||||
const DESCRIPTION_PREVIEW_LENGTH = 300;
|
const DESCRIPTION_PREVIEW_LENGTH = 300;
|
||||||
|
|
||||||
@@ -110,8 +120,11 @@
|
|||||||
|
|
||||||
const chapterCount = $derived(novel?.chapters?.length ?? 0);
|
const chapterCount = $derived(novel?.chapters?.length ?? 0);
|
||||||
|
|
||||||
|
// Filter out system tags for display, check for NSFW
|
||||||
|
const displayTags = $derived(novel?.tags?.filter((tag) => tag.tagType !== TagType.System) ?? []);
|
||||||
|
const isNsfw = $derived(novel?.tags?.some((tag) => tag.key === SystemTags.Nsfw) ?? false);
|
||||||
|
|
||||||
const canRefresh = $derived(() => {
|
const canRefresh = $derived(() => {
|
||||||
if (status === 'COMPLETED') return false;
|
|
||||||
if (!lastUpdated) return true;
|
if (!lastUpdated) return true;
|
||||||
const sixHoursAgo = Date.now() - 6 * 60 * 60 * 1000;
|
const sixHoursAgo = Date.now() - 6 * 60 * 60 * 1000;
|
||||||
return lastUpdated.getTime() < sixHoursAgo;
|
return lastUpdated.getTime() < sixHoursAgo;
|
||||||
@@ -146,6 +159,14 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
const currentImage = $derived(galleryImages[viewerIndex]);
|
const currentImage = $derived(galleryImages[viewerIndex]);
|
||||||
|
const imageCount = $derived(galleryImages.length);
|
||||||
|
|
||||||
|
// Load gallery images when tab is first activated
|
||||||
|
$effect(() => {
|
||||||
|
if (activeTab === 'gallery' && !galleryLoaded) {
|
||||||
|
galleryLoaded = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Image viewer functions
|
// Image viewer functions
|
||||||
function openImageViewer(index: number) {
|
function openImageViewer(index: number) {
|
||||||
@@ -199,6 +220,7 @@
|
|||||||
const nodes = result.data?.novels?.nodes;
|
const nodes = result.data?.novels?.nodes;
|
||||||
if (nodes && nodes.length > 0) {
|
if (nodes && nodes.length > 0) {
|
||||||
novel = nodes[0];
|
novel = nodes[0];
|
||||||
|
document.title = novel.name;
|
||||||
} else {
|
} else {
|
||||||
error = 'Novel not found';
|
error = 'Novel not found';
|
||||||
}
|
}
|
||||||
@@ -234,6 +256,32 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function deleteNovel() {
|
||||||
|
if (!novel) return;
|
||||||
|
|
||||||
|
deleting = true;
|
||||||
|
deleteError = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await client
|
||||||
|
.mutation(DeleteNovelDocument, { input: { novelId: novel.id } })
|
||||||
|
.toPromise();
|
||||||
|
|
||||||
|
if (result.error) {
|
||||||
|
deleteError = result.error.message;
|
||||||
|
} else if (result.data?.deleteNovel?.errors?.length) {
|
||||||
|
deleteError = result.data.deleteNovel.errors[0].message;
|
||||||
|
} else {
|
||||||
|
// Successfully deleted - redirect to novels list
|
||||||
|
window.location.href = '/novels';
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
deleteError = e instanceof Error ? e.message : 'Failed to delete';
|
||||||
|
} finally {
|
||||||
|
deleting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
fetchNovel();
|
fetchNovel();
|
||||||
});
|
});
|
||||||
@@ -321,6 +369,9 @@
|
|||||||
<!-- Badges -->
|
<!-- Badges -->
|
||||||
<div class="flex flex-wrap gap-2 items-center">
|
<div class="flex flex-wrap gap-2 items-center">
|
||||||
<Badge class={statusColor}>{statusLabel}</Badge>
|
<Badge class={statusColor}>{statusLabel}</Badge>
|
||||||
|
{#if isNsfw}
|
||||||
|
<Badge class="bg-red-600 text-white">NSFW</Badge>
|
||||||
|
{/if}
|
||||||
<Badge variant="outline">{languageLabel}</Badge>
|
<Badge variant="outline">{languageLabel}</Badge>
|
||||||
{#if $isAuthenticated}
|
{#if $isAuthenticated}
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
@@ -339,11 +390,20 @@
|
|||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
{#if !canRefresh()}
|
{#if !canRefresh()}
|
||||||
<TooltipContent>
|
<TooltipContent>
|
||||||
{status === 'COMPLETED' ? 'Cannot refresh completed novels' : 'Updated less than 6 hours ago'}
|
Updated less than 6 hours ago
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
{/if}
|
{/if}
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
size="sm"
|
||||||
|
onclick={() => (showDeleteConfirm = true)}
|
||||||
|
class="gap-1.5 h-6 text-xs"
|
||||||
|
>
|
||||||
|
<Trash2 class="h-3 w-3" />
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
{/if}
|
{/if}
|
||||||
{#if refreshSuccess}
|
{#if refreshSuccess}
|
||||||
<Badge variant="outline" class="bg-green-500/10 text-green-600 border-green-500/30">
|
<Badge variant="outline" class="bg-green-500/10 text-green-600 border-green-500/30">
|
||||||
@@ -390,9 +450,9 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Tags -->
|
<!-- Tags -->
|
||||||
{#if novel.tags && novel.tags.length > 0}
|
{#if displayTags.length > 0}
|
||||||
<div class="flex flex-wrap gap-1.5 pt-1">
|
<div class="flex flex-wrap gap-1.5 pt-1">
|
||||||
{#each novel.tags as tag (tag.key)}
|
{#each displayTags as tag (tag.key)}
|
||||||
<Badge
|
<Badge
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
href="/novels?tags={tag.key}"
|
href="/novels?tags={tag.key}"
|
||||||
@@ -435,20 +495,20 @@
|
|||||||
|
|
||||||
<!-- Tabbed Content -->
|
<!-- Tabbed Content -->
|
||||||
<Card>
|
<Card>
|
||||||
<Tabs value="chapters" class="w-full">
|
<Tabs bind:value={activeTab} class="w-full">
|
||||||
<CardHeader class="pb-0">
|
<CardHeader class="pb-0">
|
||||||
<TabsList class="grid w-full grid-cols-3 bg-muted/50 p-1 rounded-lg">
|
<TabsList class="grid w-full grid-cols-3 bg-muted/50 p-1 rounded-lg">
|
||||||
<TabsTrigger
|
<TabsTrigger
|
||||||
value="chapters"
|
value="chapters"
|
||||||
class="rounded-md data-[state=active]:bg-background data-[state=active]:shadow-sm px-3 py-1.5 text-sm font-medium transition-all"
|
class="rounded-md data-[state=active]:bg-background data-[state=active]:shadow-sm px-3 py-1.5 text-sm font-medium transition-all"
|
||||||
>
|
>
|
||||||
Chapters
|
Chapters ({chapterCount})
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
<TabsTrigger
|
<TabsTrigger
|
||||||
value="gallery"
|
value="gallery"
|
||||||
class="rounded-md data-[state=active]:bg-background data-[state=active]:shadow-sm px-3 py-1.5 text-sm font-medium transition-all"
|
class="rounded-md data-[state=active]:bg-background data-[state=active]:shadow-sm px-3 py-1.5 text-sm font-medium transition-all"
|
||||||
>
|
>
|
||||||
Gallery
|
Gallery ({imageCount})
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
<TabsTrigger
|
<TabsTrigger
|
||||||
value="bookmarks"
|
value="bookmarks"
|
||||||
@@ -498,7 +558,7 @@
|
|||||||
<p class="text-muted-foreground text-sm py-4 text-center">
|
<p class="text-muted-foreground text-sm py-4 text-center">
|
||||||
No images available.
|
No images available.
|
||||||
</p>
|
</p>
|
||||||
{:else}
|
{:else if galleryLoaded}
|
||||||
<div class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2">
|
<div class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2">
|
||||||
{#each galleryImages as image, index (image.src)}
|
{#each galleryImages as image, index (image.src)}
|
||||||
<button
|
<button
|
||||||
@@ -506,13 +566,20 @@
|
|||||||
onclick={() => openImageViewer(index)}
|
onclick={() => openImageViewer(index)}
|
||||||
class="relative aspect-square overflow-hidden rounded-md bg-muted/50 hover:ring-2 ring-primary transition-all"
|
class="relative aspect-square overflow-hidden rounded-md bg-muted/50 hover:ring-2 ring-primary transition-all"
|
||||||
>
|
>
|
||||||
<img src={image.src} alt={image.alt} class="h-full w-full object-cover" />
|
<img src={image.src} alt={image.alt} class="h-full w-full object-cover" loading="lazy" />
|
||||||
{#if image.isCover}
|
{#if image.isCover}
|
||||||
<Badge class="absolute top-1 left-1 text-xs">Cover</Badge>
|
<Badge class="absolute top-1 left-1 text-xs">Cover</Badge>
|
||||||
{/if}
|
{/if}
|
||||||
</button>
|
</button>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="flex items-center justify-center py-8">
|
||||||
|
<div
|
||||||
|
class="border-primary h-8 w-8 animate-spin rounded-full border-2 border-t-transparent"
|
||||||
|
aria-label="Loading gallery"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
@@ -595,3 +662,53 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
<!-- Delete Confirmation Modal -->
|
||||||
|
{#if showDeleteConfirm && novel}
|
||||||
|
<div
|
||||||
|
class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm"
|
||||||
|
onclick={() => !deleting && (showDeleteConfirm = false)}
|
||||||
|
onkeydown={(e) => e.key === 'Escape' && !deleting && (showDeleteConfirm = false)}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby="delete-modal-title"
|
||||||
|
tabindex="-1"
|
||||||
|
>
|
||||||
|
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
|
<div onclick={(e: MouseEvent) => e.stopPropagation()}>
|
||||||
|
<Card class="w-full max-w-md mx-4 shadow-xl">
|
||||||
|
<CardHeader>
|
||||||
|
<h2 id="delete-modal-title" class="text-lg font-semibold">Delete Novel</h2>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent class="space-y-4">
|
||||||
|
<p class="text-muted-foreground">
|
||||||
|
Are you sure you want to delete <strong class="text-foreground">{novel.name}</strong>?
|
||||||
|
</p>
|
||||||
|
<p class="text-sm text-muted-foreground">
|
||||||
|
This will permanently delete the novel, all chapters, images, and translations. This action cannot be undone.
|
||||||
|
</p>
|
||||||
|
{#if deleteError}
|
||||||
|
<p class="text-sm text-destructive">{deleteError}</p>
|
||||||
|
{/if}
|
||||||
|
<div class="flex justify-end gap-2 pt-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onclick={() => (showDeleteConfirm = false)}
|
||||||
|
disabled={deleting}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
onclick={deleteNovel}
|
||||||
|
disabled={deleting}
|
||||||
|
>
|
||||||
|
{deleting ? 'Deleting...' : 'Delete'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
import { Input } from '$lib/components/ui/input';
|
import { Input } from '$lib/components/ui/input';
|
||||||
import { Button } from '$lib/components/ui/button';
|
import { Button } from '$lib/components/ui/button';
|
||||||
import { Badge } from '$lib/components/ui/badge';
|
import { Badge } from '$lib/components/ui/badge';
|
||||||
import { type NovelFilters, hasActiveFilters, EMPTY_FILTERS } from '$lib/utils/filterParams';
|
import { type NovelFilters, type SortField, type SortDirection, hasActiveFilters, EMPTY_FILTERS } from '$lib/utils/filterParams';
|
||||||
import { NovelStatus, type NovelTagDto } from '$lib/graphql/__generated__/graphql';
|
import { NovelStatus, type NovelTagDto } from '$lib/graphql/__generated__/graphql';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -34,6 +34,19 @@
|
|||||||
{ value: NovelStatus.Unknown, label: 'Unknown' }
|
{ value: NovelStatus.Unknown, label: 'Unknown' }
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Sort options
|
||||||
|
const sortOptions: { value: `${SortField}-${SortDirection}`; label: string }[] = [
|
||||||
|
{ value: 'lastUpdatedTime-DESC', label: 'Recently Updated' },
|
||||||
|
{ value: 'lastUpdatedTime-ASC', label: 'Oldest Updated' },
|
||||||
|
{ value: 'createdTime-DESC', label: 'Recently Added' },
|
||||||
|
{ value: 'createdTime-ASC', label: 'Oldest Added' },
|
||||||
|
{ value: 'name-ASC', label: 'Name (A-Z)' },
|
||||||
|
{ value: 'name-DESC', label: 'Name (Z-A)' }
|
||||||
|
];
|
||||||
|
|
||||||
|
// Current sort value as combined string for the select
|
||||||
|
const currentSortValue = $derived(`${filters.sort.field}-${filters.sort.direction}` as const);
|
||||||
|
|
||||||
// Derived state for display
|
// Derived state for display
|
||||||
const selectedStatusLabels = $derived(
|
const selectedStatusLabels = $derived(
|
||||||
filters.statuses.map((s) => statusOptions.find((o) => o.value === s)?.label ?? s).join(', ')
|
filters.statuses.map((s) => statusOptions.find((o) => o.value === s)?.label ?? s).join(', ')
|
||||||
@@ -71,6 +84,12 @@
|
|||||||
onFilterChange({ ...filters, tags: selected });
|
onFilterChange({ ...filters, tags: selected });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sort selection handler
|
||||||
|
function handleSortChange(value: string) {
|
||||||
|
const [field, direction] = value.split('-') as [SortField, SortDirection];
|
||||||
|
onFilterChange({ ...filters, sort: { field, direction } });
|
||||||
|
}
|
||||||
|
|
||||||
// Clear all filters
|
// Clear all filters
|
||||||
function clearFilters() {
|
function clearFilters() {
|
||||||
searchInput = '';
|
searchInput = '';
|
||||||
@@ -196,6 +215,41 @@
|
|||||||
</Select.Root>
|
</Select.Root>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
<!-- Sort Dropdown -->
|
||||||
|
<Select.Root
|
||||||
|
type="single"
|
||||||
|
value={currentSortValue}
|
||||||
|
onValueChange={(v) => v && handleSortChange(v)}
|
||||||
|
>
|
||||||
|
<Select.Trigger
|
||||||
|
class="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus:ring-ring flex h-9 min-w-[160px] items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1 disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<span class="truncate text-left">
|
||||||
|
{sortOptions.find((o) => o.value === currentSortValue)?.label ?? 'Sort by'}
|
||||||
|
</span>
|
||||||
|
<ChevronDown class="h-4 w-4 opacity-50" />
|
||||||
|
</Select.Trigger>
|
||||||
|
<Select.Content
|
||||||
|
class="bg-popover text-popover-foreground z-50 max-h-60 min-w-[160px] overflow-auto rounded-md border p-1 shadow-md"
|
||||||
|
>
|
||||||
|
{#each sortOptions as option (option.value)}
|
||||||
|
<Select.Item
|
||||||
|
value={option.value}
|
||||||
|
class="hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground relative flex cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
|
||||||
|
>
|
||||||
|
{#snippet children({ selected })}
|
||||||
|
<div class="flex h-4 w-4 items-center justify-center">
|
||||||
|
{#if selected}
|
||||||
|
<Check class="h-3 w-3" />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<span>{option.label}</span>
|
||||||
|
{/snippet}
|
||||||
|
</Select.Item>
|
||||||
|
{/each}
|
||||||
|
</Select.Content>
|
||||||
|
</Select.Root>
|
||||||
|
|
||||||
<!-- Clear Filters Button -->
|
<!-- Clear Filters Button -->
|
||||||
{#if hasActiveFilters(filters)}
|
{#if hasActiveFilters(filters)}
|
||||||
<Button variant="outline" size="sm" onclick={clearFilters} class="gap-1">
|
<Button variant="outline" size="sm" onclick={clearFilters} class="gap-1">
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
parseFiltersFromURL,
|
parseFiltersFromURL,
|
||||||
syncFiltersToURL,
|
syncFiltersToURL,
|
||||||
filtersToGraphQLWhere,
|
filtersToGraphQLWhere,
|
||||||
|
sortToGraphQLOrder,
|
||||||
hasActiveFilters,
|
hasActiveFilters,
|
||||||
EMPTY_FILTERS
|
EMPTY_FILTERS
|
||||||
} from '$lib/utils/filterParams';
|
} from '$lib/utils/filterParams';
|
||||||
@@ -52,8 +53,9 @@
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const where = filtersToGraphQLWhere(filters);
|
const where = filtersToGraphQLWhere(filters);
|
||||||
|
const order = sortToGraphQLOrder(filters.sort);
|
||||||
const result = await client
|
const result = await client
|
||||||
.query(NovelsDocument, { first: PAGE_SIZE, after, where })
|
.query(NovelsDocument, { first: PAGE_SIZE, after, where, order })
|
||||||
.toPromise();
|
.toPromise();
|
||||||
|
|
||||||
if (result.error) {
|
if (result.error) {
|
||||||
@@ -116,20 +118,13 @@
|
|||||||
<Card class="shadow-md shadow-primary/10">
|
<Card class="shadow-md shadow-primary/10">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div class="flex items-center justify-between">
|
<div class="flex items-center justify-between">
|
||||||
<CardTitle>Novels</CardTitle>
|
<CardTitle>Controls</CardTitle>
|
||||||
{#if $isAuthenticated}
|
{#if $isAuthenticated}
|
||||||
<Button variant="outline" onclick={() => (showImportModal = true)}>
|
<Button variant="outline" onclick={() => (showImportModal = true)}>
|
||||||
Import Novel
|
Import Novel
|
||||||
</Button>
|
</Button>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
<p class="text-muted-foreground text-sm">
|
|
||||||
{#if hasActiveFilters(filters)}
|
|
||||||
Showing filtered results
|
|
||||||
{:else}
|
|
||||||
Browse all novels
|
|
||||||
{/if}
|
|
||||||
</p>
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<NovelFilters {filters} onFilterChange={handleFilterChange} availableTags={availableTags()} />
|
<NovelFilters {filters} onFilterChange={handleFilterChange} availableTags={availableTags()} />
|
||||||
|
|||||||
@@ -18,7 +18,12 @@
|
|||||||
error = null;
|
error = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await client.query(NovelsDocument, { first: 5 }).toPromise();
|
const result = await client
|
||||||
|
.query(NovelsDocument, {
|
||||||
|
first: 5,
|
||||||
|
order: [{ lastUpdatedTime: 'DESC' }]
|
||||||
|
})
|
||||||
|
.toPromise();
|
||||||
|
|
||||||
if (result.error) {
|
if (result.error) {
|
||||||
error = result.error.message;
|
error = result.error.message;
|
||||||
|
|||||||
141
fictionarchive-web-astro/src/lib/components/SearchBar.svelte
Normal file
141
fictionarchive-web-astro/src/lib/components/SearchBar.svelte
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import Search from '@lucide/svelte/icons/search';
|
||||||
|
import { Input } from '$lib/components/ui/input';
|
||||||
|
import { NovelsDocument, type NovelDto } from '$lib/graphql/__generated__/graphql';
|
||||||
|
import { client } from '$lib/graphql/client';
|
||||||
|
|
||||||
|
let searchTerm = $state('');
|
||||||
|
let results = $state<NovelDto[]>([]);
|
||||||
|
let isOpen = $state(false);
|
||||||
|
let fetching = $state(false);
|
||||||
|
let searchTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
let containerRef: HTMLDivElement;
|
||||||
|
|
||||||
|
async function fetchResults(term: string) {
|
||||||
|
if (!term.trim()) {
|
||||||
|
results = [];
|
||||||
|
isOpen = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetching = true;
|
||||||
|
try {
|
||||||
|
const result = await client
|
||||||
|
.query(NovelsDocument, {
|
||||||
|
first: 4,
|
||||||
|
where: { name: { contains: term } }
|
||||||
|
})
|
||||||
|
.toPromise();
|
||||||
|
|
||||||
|
if (result.data?.novels?.edges) {
|
||||||
|
results = result.data.novels.edges.map((edge) => edge.node);
|
||||||
|
isOpen = results.length > 0;
|
||||||
|
} else {
|
||||||
|
results = [];
|
||||||
|
isOpen = false;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Search error:', error);
|
||||||
|
results = [];
|
||||||
|
isOpen = false;
|
||||||
|
} finally {
|
||||||
|
fetching = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleInput(value: string) {
|
||||||
|
searchTerm = value;
|
||||||
|
if (searchTimeout) clearTimeout(searchTimeout);
|
||||||
|
searchTimeout = setTimeout(() => {
|
||||||
|
fetchResults(value);
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleKeydown(event: KeyboardEvent) {
|
||||||
|
if (event.key === 'Enter' && searchTerm.trim()) {
|
||||||
|
event.preventDefault();
|
||||||
|
isOpen = false;
|
||||||
|
window.location.href = `/novels?search=${encodeURIComponent(searchTerm.trim())}`;
|
||||||
|
} else if (event.key === 'Escape') {
|
||||||
|
isOpen = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleResultClick() {
|
||||||
|
isOpen = false;
|
||||||
|
searchTerm = '';
|
||||||
|
results = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleFocus() {
|
||||||
|
if (results.length > 0) {
|
||||||
|
isOpen = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClickOutside(event: MouseEvent) {
|
||||||
|
if (containerRef && !containerRef.contains(event.target as Node)) {
|
||||||
|
isOpen = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCoverSrc(novel: NovelDto): string | undefined {
|
||||||
|
return novel.coverImage?.newPath ?? novel.coverImage?.originalPath ?? undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
document.addEventListener('click', handleClickOutside);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('click', handleClickOutside);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="relative max-w-xs" bind:this={containerRef}>
|
||||||
|
<div class="relative">
|
||||||
|
<Search class="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
type="search"
|
||||||
|
placeholder="Search..."
|
||||||
|
class="pl-8"
|
||||||
|
value={searchTerm}
|
||||||
|
oninput={(e) => handleInput(e.currentTarget.value)}
|
||||||
|
onkeydown={handleKeydown}
|
||||||
|
onfocus={handleFocus}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if isOpen}
|
||||||
|
<div
|
||||||
|
class="absolute top-full left-0 right-0 z-50 mt-1 overflow-hidden rounded-md border bg-white shadow-lg dark:bg-gray-900"
|
||||||
|
>
|
||||||
|
{#if fetching}
|
||||||
|
<div class="px-4 py-3 text-sm text-muted-foreground">Searching...</div>
|
||||||
|
{:else if results.length === 0}
|
||||||
|
<div class="px-4 py-3 text-sm text-muted-foreground">No results found</div>
|
||||||
|
{:else}
|
||||||
|
{#each results as novel (novel.id)}
|
||||||
|
<a
|
||||||
|
href="/novels/{novel.id}"
|
||||||
|
class="flex items-center gap-3 px-3 py-2 hover:bg-muted transition-colors"
|
||||||
|
onclick={handleResultClick}
|
||||||
|
>
|
||||||
|
{#if getCoverSrc(novel)}
|
||||||
|
<img
|
||||||
|
src={getCoverSrc(novel)}
|
||||||
|
alt=""
|
||||||
|
class="h-12 w-9 rounded object-cover flex-shrink-0"
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<div class="h-12 w-9 rounded bg-muted flex-shrink-0"></div>
|
||||||
|
{/if}
|
||||||
|
<span class="text-sm font-medium truncate">{novel.name}</span>
|
||||||
|
</a>
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
211
fictionarchive-web-astro/src/lib/components/SettingsPage.svelte
Normal file
211
fictionarchive-web-astro/src/lib/components/SettingsPage.svelte
Normal file
@@ -0,0 +1,211 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { client } from '$lib/graphql/client';
|
||||||
|
import {
|
||||||
|
GetSettingsPageDataDocument,
|
||||||
|
InviteUserDocument,
|
||||||
|
type GetSettingsPageDataQuery
|
||||||
|
} from '$lib/graphql/__generated__/graphql';
|
||||||
|
import * as Tabs from '$lib/components/ui/tabs';
|
||||||
|
import { Button } from '$lib/components/ui/button';
|
||||||
|
import { Input } from '$lib/components/ui/input';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '$lib/components/ui/card';
|
||||||
|
import { Badge } from '$lib/components/ui/badge';
|
||||||
|
|
||||||
|
let currentUser: GetSettingsPageDataQuery['currentUser'] | null = $state(null);
|
||||||
|
let fetching = $state(true);
|
||||||
|
let error: string | null = $state(null);
|
||||||
|
|
||||||
|
// Form state
|
||||||
|
let email = $state('');
|
||||||
|
let username = $state('');
|
||||||
|
let submitting = $state(false);
|
||||||
|
let formError: string | null = $state(null);
|
||||||
|
let formSuccess = $state(false);
|
||||||
|
|
||||||
|
const availableInvites = $derived(currentUser?.availableInvites ?? 0);
|
||||||
|
const canInvite = $derived(availableInvites > 0 && !submitting && !formSuccess);
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
fetching = true;
|
||||||
|
error = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await client.query(GetSettingsPageDataDocument, {}).toPromise();
|
||||||
|
|
||||||
|
if (result.error) {
|
||||||
|
error = result.error.message;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.data) {
|
||||||
|
currentUser = result.data.currentUser;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
error = e instanceof Error ? e.message : 'Unknown error';
|
||||||
|
} finally {
|
||||||
|
fetching = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleInvite(e: Event) {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
if (!email.trim() || !username.trim()) {
|
||||||
|
formError = 'Please fill in all fields';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
submitting = true;
|
||||||
|
formError = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await client
|
||||||
|
.mutation(InviteUserDocument, {
|
||||||
|
input: { email: email.trim(), username: username.trim() }
|
||||||
|
})
|
||||||
|
.toPromise();
|
||||||
|
|
||||||
|
if (result.error) {
|
||||||
|
formError = result.error.message;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.data?.inviteUser?.errors?.length) {
|
||||||
|
formError = result.data.inviteUser.errors[0].message;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.data?.inviteUser?.userDto) {
|
||||||
|
formSuccess = true;
|
||||||
|
// Refresh data to update invite count and list
|
||||||
|
await fetchData();
|
||||||
|
// Reset form after delay
|
||||||
|
setTimeout(() => {
|
||||||
|
email = '';
|
||||||
|
username = '';
|
||||||
|
formSuccess = false;
|
||||||
|
}, 2000);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
formError = e instanceof Error ? e.message : 'Unknown error occurred';
|
||||||
|
} finally {
|
||||||
|
submitting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
fetchData();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-3xl font-bold">Settings</h1>
|
||||||
|
<p class="text-muted-foreground">Manage your account settings</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if fetching}
|
||||||
|
<div class="flex items-center justify-center py-12">
|
||||||
|
<div class="text-muted-foreground">Loading...</div>
|
||||||
|
</div>
|
||||||
|
{:else if error}
|
||||||
|
<Card>
|
||||||
|
<CardContent class="py-6">
|
||||||
|
<p class="text-destructive">{error}</p>
|
||||||
|
<Button class="mt-4" onclick={fetchData}>Try Again</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
{:else}
|
||||||
|
<Tabs.Root value="invites">
|
||||||
|
<Tabs.List class="mb-6">
|
||||||
|
<Tabs.Trigger value="invites">Invites</Tabs.Trigger>
|
||||||
|
</Tabs.List>
|
||||||
|
|
||||||
|
<Tabs.Content value="invites" class="space-y-6">
|
||||||
|
<!-- Invite Form -->
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle class="flex items-center gap-3">
|
||||||
|
Invite a User
|
||||||
|
<Badge variant={availableInvites > 0 ? 'default' : 'secondary'}>
|
||||||
|
{availableInvites} remaining
|
||||||
|
</Badge>
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onsubmit={handleInvite} class="space-y-4">
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label for="invite-email" class="text-sm font-medium">Email</label>
|
||||||
|
<Input
|
||||||
|
id="invite-email"
|
||||||
|
type="email"
|
||||||
|
placeholder="user@example.com"
|
||||||
|
bind:value={email}
|
||||||
|
disabled={!canInvite}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label for="invite-username" class="text-sm font-medium">Username</label>
|
||||||
|
<Input
|
||||||
|
id="invite-username"
|
||||||
|
type="text"
|
||||||
|
placeholder="username"
|
||||||
|
bind:value={username}
|
||||||
|
disabled={!canInvite}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if formError}
|
||||||
|
<p class="text-destructive text-sm">{formError}</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if formSuccess}
|
||||||
|
<p class="text-green-600 dark:text-green-400 text-sm">
|
||||||
|
Invitation sent successfully! The user will receive an email to set up their account.
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<Button type="submit" disabled={!canInvite || !email.trim() || !username.trim()}>
|
||||||
|
{#if submitting}
|
||||||
|
Sending...
|
||||||
|
{:else if formSuccess}
|
||||||
|
Sent!
|
||||||
|
{:else}
|
||||||
|
Send Invite
|
||||||
|
{/if}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<!-- Invited Users List -->
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Invited Users</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{#if !currentUser?.invitedUsers?.length}
|
||||||
|
<p class="text-muted-foreground text-sm">
|
||||||
|
You haven't invited anyone yet.
|
||||||
|
</p>
|
||||||
|
{:else}
|
||||||
|
<div class="divide-y">
|
||||||
|
{#each currentUser.invitedUsers as user (user.username)}
|
||||||
|
<div class="flex items-center justify-between py-3 first:pt-0 last:pb-0">
|
||||||
|
<div>
|
||||||
|
<p class="font-medium">{user.username}</p>
|
||||||
|
<p class="text-muted-foreground text-sm">{user.email}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</Tabs.Content>
|
||||||
|
</Tabs.Root>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
3
fictionarchive-web-astro/src/lib/constants/systemTags.ts
Normal file
3
fictionarchive-web-astro/src/lib/constants/systemTags.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export const SystemTags = {
|
||||||
|
Nsfw: 'Nsfw'
|
||||||
|
} as const;
|
||||||
@@ -88,6 +88,17 @@ export type DeleteJobPayload = {
|
|||||||
errors: Maybe<Array<DeleteJobError>>;
|
errors: Maybe<Array<DeleteJobError>>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type DeleteNovelError = KeyNotFoundError;
|
||||||
|
|
||||||
|
export type DeleteNovelInput = {
|
||||||
|
novelId: Scalars['UnsignedInt']['input'];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DeleteNovelPayload = {
|
||||||
|
boolean: Maybe<Scalars['Boolean']['output']>;
|
||||||
|
errors: Maybe<Array<DeleteNovelError>>;
|
||||||
|
};
|
||||||
|
|
||||||
export type DuplicateNameError = Error & {
|
export type DuplicateNameError = Error & {
|
||||||
message: Scalars['String']['output'];
|
message: Scalars['String']['output'];
|
||||||
};
|
};
|
||||||
@@ -145,6 +156,27 @@ export type InstantFilterInput = {
|
|||||||
or?: InputMaybe<Array<InstantFilterInput>>;
|
or?: InputMaybe<Array<InstantFilterInput>>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type InvalidOperationError = Error & {
|
||||||
|
message: Scalars['String']['output'];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type InviteUserError = InvalidOperationError;
|
||||||
|
|
||||||
|
export type InviteUserInput = {
|
||||||
|
email: Scalars['String']['input'];
|
||||||
|
username: Scalars['String']['input'];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type InviteUserPayload = {
|
||||||
|
errors: Maybe<Array<InviteUserError>>;
|
||||||
|
userDto: Maybe<UserDto>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type InvitedUserDto = {
|
||||||
|
email: Scalars['String']['output'];
|
||||||
|
username: Scalars['String']['output'];
|
||||||
|
};
|
||||||
|
|
||||||
export type JobKey = {
|
export type JobKey = {
|
||||||
group: Scalars['String']['output'];
|
group: Scalars['String']['output'];
|
||||||
name: Scalars['String']['output'];
|
name: Scalars['String']['output'];
|
||||||
@@ -201,9 +233,10 @@ export type ListFilterInputTypeOfNovelTagDtoFilterInput = {
|
|||||||
|
|
||||||
export type Mutation = {
|
export type Mutation = {
|
||||||
deleteJob: DeleteJobPayload;
|
deleteJob: DeleteJobPayload;
|
||||||
|
deleteNovel: DeleteNovelPayload;
|
||||||
fetchChapterContents: FetchChapterContentsPayload;
|
fetchChapterContents: FetchChapterContentsPayload;
|
||||||
importNovel: ImportNovelPayload;
|
importNovel: ImportNovelPayload;
|
||||||
registerUser: RegisterUserPayload;
|
inviteUser: InviteUserPayload;
|
||||||
runJob: RunJobPayload;
|
runJob: RunJobPayload;
|
||||||
scheduleEventJob: ScheduleEventJobPayload;
|
scheduleEventJob: ScheduleEventJobPayload;
|
||||||
translateText: TranslateTextPayload;
|
translateText: TranslateTextPayload;
|
||||||
@@ -215,6 +248,11 @@ export type MutationDeleteJobArgs = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
export type MutationDeleteNovelArgs = {
|
||||||
|
input: DeleteNovelInput;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
export type MutationFetchChapterContentsArgs = {
|
export type MutationFetchChapterContentsArgs = {
|
||||||
input: FetchChapterContentsInput;
|
input: FetchChapterContentsInput;
|
||||||
};
|
};
|
||||||
@@ -225,8 +263,8 @@ export type MutationImportNovelArgs = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
export type MutationRegisterUserArgs = {
|
export type MutationInviteUserArgs = {
|
||||||
input: RegisterUserInput;
|
input: InviteUserInput;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
@@ -405,11 +443,11 @@ export type PersonDtoSortInput = {
|
|||||||
|
|
||||||
export type Query = {
|
export type Query = {
|
||||||
chapter: Maybe<ChapterReaderDto>;
|
chapter: Maybe<ChapterReaderDto>;
|
||||||
|
currentUser: Array<UserDto>;
|
||||||
jobs: Array<SchedulerJob>;
|
jobs: Array<SchedulerJob>;
|
||||||
novels: Maybe<NovelsConnection>;
|
novels: Maybe<NovelsConnection>;
|
||||||
translationEngines: Array<TranslationEngineDescriptor>;
|
translationEngines: Array<TranslationEngineDescriptor>;
|
||||||
translationRequests: Maybe<TranslationRequestsConnection>;
|
translationRequests: Maybe<TranslationRequestsConnection>;
|
||||||
users: Array<UserDto>;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
@@ -446,17 +484,6 @@ export type QueryTranslationRequestsArgs = {
|
|||||||
where?: InputMaybe<TranslationRequestDtoFilterInput>;
|
where?: InputMaybe<TranslationRequestDtoFilterInput>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type RegisterUserInput = {
|
|
||||||
email: Scalars['String']['input'];
|
|
||||||
inviterOAuthProviderId?: InputMaybe<Scalars['String']['input']>;
|
|
||||||
oAuthProviderId: Scalars['String']['input'];
|
|
||||||
username: Scalars['String']['input'];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type RegisterUserPayload = {
|
|
||||||
userDto: Maybe<UserDto>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type RunJobError = JobPersistenceError;
|
export type RunJobError = JobPersistenceError;
|
||||||
|
|
||||||
export type RunJobInput = {
|
export type RunJobInput = {
|
||||||
@@ -683,11 +710,13 @@ export type UnsignedIntOperationFilterInputType = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type UserDto = {
|
export type UserDto = {
|
||||||
|
availableInvites: Scalars['Int']['output'];
|
||||||
createdTime: Scalars['Instant']['output'];
|
createdTime: Scalars['Instant']['output'];
|
||||||
disabled: Scalars['Boolean']['output'];
|
disabled: Scalars['Boolean']['output'];
|
||||||
email: Scalars['String']['output'];
|
email: Scalars['String']['output'];
|
||||||
id: Scalars['UUID']['output'];
|
id: Scalars['UUID']['output'];
|
||||||
inviter: Maybe<UserDto>;
|
invitedUsers: Maybe<Array<InvitedUserDto>>;
|
||||||
|
inviterId: Maybe<Scalars['UUID']['output']>;
|
||||||
lastUpdatedTime: Scalars['Instant']['output'];
|
lastUpdatedTime: Scalars['Instant']['output'];
|
||||||
username: Scalars['String']['output'];
|
username: Scalars['String']['output'];
|
||||||
};
|
};
|
||||||
@@ -707,6 +736,13 @@ export type UuidOperationFilterInput = {
|
|||||||
nlte?: InputMaybe<Scalars['UUID']['input']>;
|
nlte?: InputMaybe<Scalars['UUID']['input']>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type DeleteNovelMutationVariables = Exact<{
|
||||||
|
input: DeleteNovelInput;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
|
||||||
|
export type DeleteNovelMutation = { deleteNovel: { boolean: boolean | null, errors: Array<{ message: string }> | null } };
|
||||||
|
|
||||||
export type ImportNovelMutationVariables = Exact<{
|
export type ImportNovelMutationVariables = Exact<{
|
||||||
input: ImportNovelInput;
|
input: ImportNovelInput;
|
||||||
}>;
|
}>;
|
||||||
@@ -714,6 +750,13 @@ export type ImportNovelMutationVariables = Exact<{
|
|||||||
|
|
||||||
export type ImportNovelMutation = { importNovel: { novelUpdateRequestedEvent: { novelUrl: string } | null } };
|
export type ImportNovelMutation = { importNovel: { novelUpdateRequestedEvent: { novelUrl: string } | null } };
|
||||||
|
|
||||||
|
export type InviteUserMutationVariables = Exact<{
|
||||||
|
input: InviteUserInput;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
|
||||||
|
export type InviteUserMutation = { inviteUser: { userDto: { id: any, username: string, email: string } | null, errors: Array<{ message: string }> | null } };
|
||||||
|
|
||||||
export type GetChapterQueryVariables = Exact<{
|
export type GetChapterQueryVariables = Exact<{
|
||||||
novelId: Scalars['UnsignedInt']['input'];
|
novelId: Scalars['UnsignedInt']['input'];
|
||||||
chapterOrder: Scalars['UnsignedInt']['input'];
|
chapterOrder: Scalars['UnsignedInt']['input'];
|
||||||
@@ -733,13 +776,22 @@ export type NovelsQueryVariables = Exact<{
|
|||||||
first?: InputMaybe<Scalars['Int']['input']>;
|
first?: InputMaybe<Scalars['Int']['input']>;
|
||||||
after?: InputMaybe<Scalars['String']['input']>;
|
after?: InputMaybe<Scalars['String']['input']>;
|
||||||
where?: InputMaybe<NovelDtoFilterInput>;
|
where?: InputMaybe<NovelDtoFilterInput>;
|
||||||
|
order?: InputMaybe<Array<NovelDtoSortInput> | NovelDtoSortInput>;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
|
|
||||||
export type NovelsQuery = { novels: { edges: Array<{ cursor: string, node: { id: any, url: string, name: string, description: string, rawStatus: NovelStatus, lastUpdatedTime: any, coverImage: { newPath: string | null } | null, chapters: Array<{ order: any, name: string }>, tags: Array<{ key: string, displayName: string }> } }> | null, pageInfo: { hasNextPage: boolean, endCursor: string | null } } | null };
|
export type NovelsQuery = { novels: { edges: Array<{ cursor: string, node: { id: any, url: string, name: string, description: string, rawStatus: NovelStatus, lastUpdatedTime: any, coverImage: { newPath: string | null } | null, chapters: Array<{ order: any, name: string }>, tags: Array<{ key: string, displayName: string, tagType: TagType }> } }> | null, pageInfo: { hasNextPage: boolean, endCursor: string | null } } | null };
|
||||||
|
|
||||||
|
export type GetSettingsPageDataQueryVariables = Exact<{ [key: string]: never; }>;
|
||||||
|
|
||||||
|
|
||||||
|
export type GetSettingsPageDataQuery = { currentUser: Array<{ id: any, username: string, availableInvites: number, invitedUsers: Array<{ username: string, email: string }> | null }> };
|
||||||
|
|
||||||
|
|
||||||
|
export const DeleteNovelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteNovel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"DeleteNovelInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteNovel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"boolean"}},{"kind":"Field","name":{"kind":"Name","value":"errors"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Error"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"message"}}]}}]}}]}}]}}]} as unknown as DocumentNode<DeleteNovelMutation, DeleteNovelMutationVariables>;
|
||||||
export const ImportNovelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ImportNovel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ImportNovelInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"importNovel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novelUpdateRequestedEvent"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novelUrl"}}]}}]}}]}}]} as unknown as DocumentNode<ImportNovelMutation, ImportNovelMutationVariables>;
|
export const ImportNovelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ImportNovel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ImportNovelInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"importNovel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novelUpdateRequestedEvent"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novelUrl"}}]}}]}}]}}]} as unknown as DocumentNode<ImportNovelMutation, ImportNovelMutationVariables>;
|
||||||
|
export const InviteUserDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"InviteUser"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"InviteUserInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"inviteUser"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userDto"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"username"}},{"kind":"Field","name":{"kind":"Name","value":"email"}}]}},{"kind":"Field","name":{"kind":"Name","value":"errors"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"InvalidOperationError"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"message"}}]}}]}}]}}]}}]} as unknown as DocumentNode<InviteUserMutation, InviteUserMutationVariables>;
|
||||||
export const GetChapterDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetChapter"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"novelId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UnsignedInt"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"chapterOrder"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UnsignedInt"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"chapter"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"novelId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"novelId"}}},{"kind":"Argument","name":{"kind":"Name","value":"chapterOrder"},"value":{"kind":"Variable","name":{"kind":"Name","value":"chapterOrder"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"order"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"body"}},{"kind":"Field","name":{"kind":"Name","value":"url"}},{"kind":"Field","name":{"kind":"Name","value":"revision"}},{"kind":"Field","name":{"kind":"Name","value":"createdTime"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}},{"kind":"Field","name":{"kind":"Name","value":"images"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"newPath"}}]}},{"kind":"Field","name":{"kind":"Name","value":"novelId"}},{"kind":"Field","name":{"kind":"Name","value":"novelName"}},{"kind":"Field","name":{"kind":"Name","value":"totalChapters"}},{"kind":"Field","name":{"kind":"Name","value":"prevChapterOrder"}},{"kind":"Field","name":{"kind":"Name","value":"nextChapterOrder"}}]}}]}}]} as unknown as DocumentNode<GetChapterQuery, GetChapterQueryVariables>;
|
export const GetChapterDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetChapter"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"novelId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UnsignedInt"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"chapterOrder"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UnsignedInt"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"chapter"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"novelId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"novelId"}}},{"kind":"Argument","name":{"kind":"Name","value":"chapterOrder"},"value":{"kind":"Variable","name":{"kind":"Name","value":"chapterOrder"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"order"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"body"}},{"kind":"Field","name":{"kind":"Name","value":"url"}},{"kind":"Field","name":{"kind":"Name","value":"revision"}},{"kind":"Field","name":{"kind":"Name","value":"createdTime"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}},{"kind":"Field","name":{"kind":"Name","value":"images"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"newPath"}}]}},{"kind":"Field","name":{"kind":"Name","value":"novelId"}},{"kind":"Field","name":{"kind":"Name","value":"novelName"}},{"kind":"Field","name":{"kind":"Name","value":"totalChapters"}},{"kind":"Field","name":{"kind":"Name","value":"prevChapterOrder"}},{"kind":"Field","name":{"kind":"Name","value":"nextChapterOrder"}}]}}]}}]} as unknown as DocumentNode<GetChapterQuery, GetChapterQueryVariables>;
|
||||||
export const NovelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Novel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UnsignedInt"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novels"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"where"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"id"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"eq"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}]}}]}},{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"IntValue","value":"1"}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"nodes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"url"}},{"kind":"Field","name":{"kind":"Name","value":"rawLanguage"}},{"kind":"Field","name":{"kind":"Name","value":"rawStatus"}},{"kind":"Field","name":{"kind":"Name","value":"statusOverride"}},{"kind":"Field","name":{"kind":"Name","value":"externalId"}},{"kind":"Field","name":{"kind":"Name","value":"createdTime"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}},{"kind":"Field","name":{"kind":"Name","value":"author"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"externalUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"source"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"url"}}]}},{"kind":"Field","name":{"kind":"Name","value":"coverImage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"newPath"}}]}},{"kind":"Field","name":{"kind":"Name","value":"tags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"tagType"}}]}},{"kind":"Field","name":{"kind":"Name","value":"chapters"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"order"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}},{"kind":"Field","name":{"kind":"Name","value":"images"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"newPath"}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<NovelQuery, NovelQueryVariables>;
|
export const NovelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Novel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UnsignedInt"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novels"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"where"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"id"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"eq"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}]}}]}},{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"IntValue","value":"1"}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"nodes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"url"}},{"kind":"Field","name":{"kind":"Name","value":"rawLanguage"}},{"kind":"Field","name":{"kind":"Name","value":"rawStatus"}},{"kind":"Field","name":{"kind":"Name","value":"statusOverride"}},{"kind":"Field","name":{"kind":"Name","value":"externalId"}},{"kind":"Field","name":{"kind":"Name","value":"createdTime"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}},{"kind":"Field","name":{"kind":"Name","value":"author"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"externalUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"source"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"url"}}]}},{"kind":"Field","name":{"kind":"Name","value":"coverImage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"newPath"}}]}},{"kind":"Field","name":{"kind":"Name","value":"tags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"tagType"}}]}},{"kind":"Field","name":{"kind":"Name","value":"chapters"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"order"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}},{"kind":"Field","name":{"kind":"Name","value":"images"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"newPath"}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<NovelQuery, NovelQueryVariables>;
|
||||||
export const NovelsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Novels"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"where"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"NovelDtoFilterInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novels"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}},{"kind":"Argument","name":{"kind":"Name","value":"where"},"value":{"kind":"Variable","name":{"kind":"Name","value":"where"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"url"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"coverImage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"newPath"}}]}},{"kind":"Field","name":{"kind":"Name","value":"rawStatus"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}},{"kind":"Field","name":{"kind":"Name","value":"chapters"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"order"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"tags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode<NovelsQuery, NovelsQueryVariables>;
|
export const NovelsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Novels"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"where"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"NovelDtoFilterInput"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"order"}},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"NovelDtoSortInput"}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novels"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}},{"kind":"Argument","name":{"kind":"Name","value":"where"},"value":{"kind":"Variable","name":{"kind":"Name","value":"where"}}},{"kind":"Argument","name":{"kind":"Name","value":"order"},"value":{"kind":"Variable","name":{"kind":"Name","value":"order"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"url"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"coverImage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"newPath"}}]}},{"kind":"Field","name":{"kind":"Name","value":"rawStatus"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}},{"kind":"Field","name":{"kind":"Name","value":"chapters"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"order"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"tags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"tagType"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode<NovelsQuery, NovelsQueryVariables>;
|
||||||
|
export const GetSettingsPageDataDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetSettingsPageData"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"currentUser"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"username"}},{"kind":"Field","name":{"kind":"Name","value":"availableInvites"}},{"kind":"Field","name":{"kind":"Name","value":"invitedUsers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"username"}},{"kind":"Field","name":{"kind":"Name","value":"email"}}]}}]}}]}}]} as unknown as DocumentNode<GetSettingsPageDataQuery, GetSettingsPageDataQueryVariables>;
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
mutation DeleteNovel($input: DeleteNovelInput!) {
|
||||||
|
deleteNovel(input: $input) {
|
||||||
|
boolean
|
||||||
|
errors {
|
||||||
|
... on Error {
|
||||||
|
message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
mutation InviteUser($input: InviteUserInput!) {
|
||||||
|
inviteUser(input: $input) {
|
||||||
|
userDto {
|
||||||
|
id
|
||||||
|
username
|
||||||
|
email
|
||||||
|
}
|
||||||
|
errors {
|
||||||
|
... on InvalidOperationError {
|
||||||
|
message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
query Novels($first: Int, $after: String, $where: NovelDtoFilterInput) {
|
query Novels($first: Int, $after: String, $where: NovelDtoFilterInput, $order: [NovelDtoSortInput!]) {
|
||||||
novels(first: $first, after: $after, where: $where) {
|
novels(first: $first, after: $after, where: $where, order: $order) {
|
||||||
edges {
|
edges {
|
||||||
cursor
|
cursor
|
||||||
node {
|
node {
|
||||||
@@ -19,6 +19,7 @@ query Novels($first: Int, $after: String, $where: NovelDtoFilterInput) {
|
|||||||
tags {
|
tags {
|
||||||
key
|
key
|
||||||
displayName
|
displayName
|
||||||
|
tagType
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
query GetSettingsPageData {
|
||||||
|
currentUser {
|
||||||
|
id
|
||||||
|
username
|
||||||
|
availableInvites
|
||||||
|
invitedUsers {
|
||||||
|
username
|
||||||
|
email
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,20 +1,37 @@
|
|||||||
import type { NovelDtoFilterInput, NovelStatus } from '$lib/graphql/__generated__/graphql';
|
import type { NovelDtoFilterInput, NovelDtoSortInput, NovelStatus, SortEnumType } from '$lib/graphql/__generated__/graphql';
|
||||||
|
|
||||||
|
export type SortField = 'lastUpdatedTime' | 'createdTime' | 'name';
|
||||||
|
export type SortDirection = SortEnumType;
|
||||||
|
|
||||||
|
export interface NovelSort {
|
||||||
|
field: SortField;
|
||||||
|
direction: SortDirection;
|
||||||
|
}
|
||||||
|
|
||||||
export interface NovelFilters {
|
export interface NovelFilters {
|
||||||
search: string;
|
search: string;
|
||||||
statuses: NovelStatus[];
|
statuses: NovelStatus[];
|
||||||
tags: string[];
|
tags: string[];
|
||||||
authorName: string;
|
authorName: string;
|
||||||
|
sort: NovelSort;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_SORT: NovelSort = {
|
||||||
|
field: 'lastUpdatedTime',
|
||||||
|
direction: 'DESC'
|
||||||
|
};
|
||||||
|
|
||||||
export const EMPTY_FILTERS: NovelFilters = {
|
export const EMPTY_FILTERS: NovelFilters = {
|
||||||
search: '',
|
search: '',
|
||||||
statuses: [],
|
statuses: [],
|
||||||
tags: [],
|
tags: [],
|
||||||
authorName: ''
|
authorName: '',
|
||||||
|
sort: DEFAULT_SORT
|
||||||
};
|
};
|
||||||
|
|
||||||
const VALID_STATUSES: NovelStatus[] = ['ABANDONED', 'COMPLETED', 'HIATUS', 'IN_PROGRESS', 'UNKNOWN'];
|
const VALID_STATUSES: NovelStatus[] = ['ABANDONED', 'COMPLETED', 'HIATUS', 'IN_PROGRESS', 'UNKNOWN'];
|
||||||
|
const VALID_SORT_FIELDS: SortField[] = ['lastUpdatedTime', 'createdTime', 'name'];
|
||||||
|
const VALID_SORT_DIRECTIONS: SortDirection[] = ['ASC', 'DESC'];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse filter state from URL search parameters
|
* Parse filter state from URL search parameters
|
||||||
@@ -34,7 +51,15 @@ export function parseFiltersFromURL(searchParams?: URLSearchParams): NovelFilter
|
|||||||
|
|
||||||
const authorName = params.get('author') ?? '';
|
const authorName = params.get('author') ?? '';
|
||||||
|
|
||||||
return { search, statuses, tags, authorName };
|
// Parse sort parameters
|
||||||
|
const sortField = params.get('sortBy') as SortField | null;
|
||||||
|
const sortDir = params.get('sortDir') as SortDirection | null;
|
||||||
|
const sort: NovelSort = {
|
||||||
|
field: sortField && VALID_SORT_FIELDS.includes(sortField) ? sortField : DEFAULT_SORT.field,
|
||||||
|
direction: sortDir && VALID_SORT_DIRECTIONS.includes(sortDir) ? sortDir : DEFAULT_SORT.direction
|
||||||
|
};
|
||||||
|
|
||||||
|
return { search, statuses, tags, authorName, sort };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,6 +84,12 @@ export function filtersToURLParams(filters: NovelFilters): string {
|
|||||||
params.set('author', filters.authorName.trim());
|
params.set('author', filters.authorName.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Only include sort params if different from default
|
||||||
|
if (filters.sort.field !== DEFAULT_SORT.field || filters.sort.direction !== DEFAULT_SORT.direction) {
|
||||||
|
params.set('sortBy', filters.sort.field);
|
||||||
|
params.set('sortDir', filters.sort.direction);
|
||||||
|
}
|
||||||
|
|
||||||
return params.toString();
|
return params.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,3 +166,10 @@ export function hasActiveFilters(filters: NovelFilters): boolean {
|
|||||||
filters.authorName.trim().length > 0
|
filters.authorName.trim().length > 0
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert sort state to GraphQL order input
|
||||||
|
*/
|
||||||
|
export function sortToGraphQLOrder(sort: NovelSort): NovelDtoSortInput[] {
|
||||||
|
return [{ [sort.field]: sort.direction }];
|
||||||
|
}
|
||||||
|
|||||||
8
fictionarchive-web-astro/src/pages/settings/index.astro
Normal file
8
fictionarchive-web-astro/src/pages/settings/index.astro
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
---
|
||||||
|
import AppLayout from '../../layouts/AppLayout.astro';
|
||||||
|
import SettingsPage from '../../lib/components/SettingsPage.svelte';
|
||||||
|
---
|
||||||
|
|
||||||
|
<AppLayout title="Settings - FictionArchive">
|
||||||
|
<SettingsPage client:load />
|
||||||
|
</AppLayout>
|
||||||
Reference in New Issue
Block a user