Compare commits
47 Commits
feature/FA
...
v1.3.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 98ae4ea4f2 | |||
|
|
15e1a84f55 | ||
|
|
70d4ba201a | ||
|
|
b69bcd6bf4 | ||
|
|
c97654631b | ||
|
|
1ecfd9cc99 | ||
|
|
19ae4a8089 | ||
|
|
f8a45ad891 | ||
|
|
f67c5c610c | ||
| b5d4694f12 | |||
|
|
6d47153a42 | ||
| dbbc2fd8dc | |||
|
|
176c94297b | ||
|
|
8b3faa8f6c | ||
|
|
d87bd81190 | ||
|
|
bee805c441 | ||
|
|
5013da69c2 | ||
| d8e3ec7ec9 | |||
|
|
3612c89b99 | ||
|
|
ebb2e6e7fc | ||
|
|
01d3b94050 | ||
|
|
c0290cc5af | ||
| 1d950b7721 | |||
|
|
7738bcf438 | ||
| 61e0cb69d8 | |||
|
|
02525d611a | ||
| c21fe0fbd5 | |||
|
|
bbc0b5ec7d | ||
| 5527c15ae7 | |||
|
|
1e374e6eeb | ||
| c710f14257 | |||
|
|
6c10077505 | ||
| fecb3e6f43 | |||
|
|
f0ea71e00e | ||
| 45afb57df5 | |||
|
|
6fd76f6787 | ||
| baad092f07 | |||
|
|
4fb34bdef7 | ||
| 89a2cf6db1 | |||
|
|
f830773af5 | ||
| 7185b95c65 | |||
|
|
8b44cf2f0c | ||
| ac48889f4c | |||
|
|
5c52d29da9 | ||
| 16004ad938 | |||
|
|
d109db2155 | ||
| 89dff0980b |
@@ -28,6 +28,9 @@ jobs:
|
|||||||
- name: user-service
|
- name: user-service
|
||||||
project: FictionArchive.Service.UserService
|
project: FictionArchive.Service.UserService
|
||||||
subgraph: User
|
subgraph: User
|
||||||
|
- name: usernoveldata-service
|
||||||
|
project: FictionArchive.Service.UserNovelDataService
|
||||||
|
subgraph: UserNovelData
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@@ -110,6 +113,12 @@ jobs:
|
|||||||
name: user-service-subgraph
|
name: user-service-subgraph
|
||||||
path: subgraphs/user
|
path: subgraphs/user
|
||||||
|
|
||||||
|
- name: Download UserNovelData Service subgraph
|
||||||
|
uses: christopherhx/gitea-download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: usernoveldata-service-subgraph
|
||||||
|
path: subgraphs/usernoveldata
|
||||||
|
|
||||||
- name: Configure subgraph URLs for Docker
|
- name: Configure subgraph URLs for Docker
|
||||||
run: |
|
run: |
|
||||||
for fsp in subgraphs/*/*.fsp; do
|
for fsp in subgraphs/*/*.fsp; do
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ jobs:
|
|||||||
dockerfile: FictionArchive.Service.SchedulerService/Dockerfile
|
dockerfile: FictionArchive.Service.SchedulerService/Dockerfile
|
||||||
- name: authentication-service
|
- name: authentication-service
|
||||||
dockerfile: FictionArchive.Service.AuthenticationService/Dockerfile
|
dockerfile: FictionArchive.Service.AuthenticationService/Dockerfile
|
||||||
|
- name: usernoveldata-service
|
||||||
|
dockerfile: FictionArchive.Service.UserNovelDataService/Dockerfile
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|||||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -139,4 +139,7 @@ appsettings.Local.json
|
|||||||
# Fusion Builds
|
# Fusion Builds
|
||||||
schema.graphql
|
schema.graphql
|
||||||
*.fsp
|
*.fsp
|
||||||
gateway.fgp
|
gateway.fgp
|
||||||
|
|
||||||
|
# Git worktrees
|
||||||
|
.worktrees/
|
||||||
9977
Documentation/sample_novel_page.html
Normal file
9977
Documentation/sample_novel_page.html
Normal file
File diff suppressed because it is too large
Load Diff
@@ -24,6 +24,8 @@ RUN dotnet build "./FictionArchive.API.csproj" -c $BUILD_CONFIGURATION -o /app/b
|
|||||||
FROM build AS publish
|
FROM build AS publish
|
||||||
ARG BUILD_CONFIGURATION=Release
|
ARG BUILD_CONFIGURATION=Release
|
||||||
RUN dotnet publish "./FictionArchive.API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false /p:SkipFusionBuild=true
|
RUN dotnet publish "./FictionArchive.API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false /p:SkipFusionBuild=true
|
||||||
|
# Copy pre-composed gateway.fgp from CI build
|
||||||
|
COPY FictionArchive.API/gateway.fgp /app/publish/
|
||||||
|
|
||||||
FROM base AS final
|
FROM base AS final
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|||||||
@@ -25,8 +25,6 @@ public class Program
|
|||||||
.ConfigureFromFile("gateway.fgp")
|
.ConfigureFromFile("gateway.fgp")
|
||||||
.CoreBuilder.ApplySaneDefaults();
|
.CoreBuilder.ApplySaneDefaults();
|
||||||
|
|
||||||
builder.Services.AddOidcAuthentication(builder.Configuration);
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
var allowedOrigin = builder.Configuration["Cors:AllowedOrigin"] ?? "http://localhost:4321";
|
var allowedOrigin = builder.Configuration["Cors:AllowedOrigin"] ?? "http://localhost:4321";
|
||||||
|
|||||||
@@ -35,8 +35,16 @@ namespace FictionArchive.Service.FileService.Controllers
|
|||||||
BucketName = _s3Configuration.Bucket,
|
BucketName = _s3Configuration.Bucket,
|
||||||
Key = decodedPath
|
Key = decodedPath
|
||||||
});
|
});
|
||||||
|
|
||||||
return new FileStreamResult(s3Response.ResponseStream, s3Response.Headers.ContentType);
|
Response.Headers.CacheControl = "public, max-age=604800"; // 7 days
|
||||||
|
Response.Headers.LastModified = s3Response.LastModified?.ToString("R");
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(s3Response.ETag))
|
||||||
|
{
|
||||||
|
Response.Headers.ETag = s3Response.ETag;
|
||||||
|
}
|
||||||
|
|
||||||
|
return File(s3Response.ResponseStream, s3Response.Headers.ContentType);
|
||||||
}
|
}
|
||||||
catch (AmazonS3Exception e)
|
catch (AmazonS3Exception e)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -42,6 +42,13 @@ public class NovelUpdateServiceTests
|
|||||||
Images = new List<Image>()
|
Images = new List<Image>()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
var volume = new Volume
|
||||||
|
{
|
||||||
|
Order = 1,
|
||||||
|
Name = LocalizationKey.CreateFromText("Main Story", Language.En),
|
||||||
|
Chapters = new List<Chapter> { chapter }
|
||||||
|
};
|
||||||
|
|
||||||
var novel = new Novel
|
var novel = new Novel
|
||||||
{
|
{
|
||||||
Url = "http://demo/novel",
|
Url = "http://demo/novel",
|
||||||
@@ -52,14 +59,14 @@ public class NovelUpdateServiceTests
|
|||||||
Source = source,
|
Source = source,
|
||||||
Name = LocalizationKey.CreateFromText("Demo Novel", Language.En),
|
Name = LocalizationKey.CreateFromText("Demo Novel", Language.En),
|
||||||
Description = LocalizationKey.CreateFromText("Description", Language.En),
|
Description = LocalizationKey.CreateFromText("Description", Language.En),
|
||||||
Chapters = new List<Chapter> { chapter },
|
Volumes = new List<Volume> { volume },
|
||||||
Tags = new List<NovelTag>()
|
Tags = new List<NovelTag>()
|
||||||
};
|
};
|
||||||
|
|
||||||
dbContext.Novels.Add(novel);
|
dbContext.Novels.Add(novel);
|
||||||
dbContext.SaveChanges();
|
dbContext.SaveChanges();
|
||||||
|
|
||||||
return new NovelCreateResult(novel, chapter);
|
return new NovelCreateResult(novel, volume, chapter);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static NovelUpdateService CreateService(
|
private static NovelUpdateService CreateService(
|
||||||
@@ -81,7 +88,7 @@ public class NovelUpdateServiceTests
|
|||||||
{
|
{
|
||||||
using var dbContext = CreateDbContext();
|
using var dbContext = CreateDbContext();
|
||||||
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
|
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
|
||||||
var (novel, chapter) = CreateNovelWithSingleChapter(dbContext, source);
|
var (novel, volume, chapter) = CreateNovelWithSingleChapter(dbContext, source);
|
||||||
|
|
||||||
var rawHtml = "<p>Hello</p><img src=\"http://img/x1.jpg\" alt=\"first\" /><img src=\"http://img/x2.jpg\" alt=\"second\" />";
|
var rawHtml = "<p>Hello</p><img src=\"http://img/x1.jpg\" alt=\"first\" /><img src=\"http://img/x2.jpg\" alt=\"second\" />";
|
||||||
var image1 = new ImageData { Url = "http://img/x1.jpg", Data = new byte[] { 1, 2, 3 } };
|
var image1 = new ImageData { Url = "http://img/x1.jpg", Data = new byte[] { 1, 2, 3 } };
|
||||||
@@ -103,7 +110,7 @@ public class NovelUpdateServiceTests
|
|||||||
var pendingImageUrl = "https://pending/placeholder.jpg";
|
var pendingImageUrl = "https://pending/placeholder.jpg";
|
||||||
var service = CreateService(dbContext, adapter, eventBus, pendingImageUrl);
|
var service = CreateService(dbContext, adapter, eventBus, pendingImageUrl);
|
||||||
|
|
||||||
var updatedChapter = await service.PullChapterContents(novel.Id, chapter.Order);
|
var updatedChapter = await service.PullChapterContents(novel.Id, volume.Id, chapter.Order);
|
||||||
|
|
||||||
updatedChapter.Images.Should().HaveCount(2);
|
updatedChapter.Images.Should().HaveCount(2);
|
||||||
updatedChapter.Images.Select(i => i.OriginalPath).Should().BeEquivalentTo(new[] { image1.Url, image2.Url });
|
updatedChapter.Images.Select(i => i.OriginalPath).Should().BeEquivalentTo(new[] { image1.Url, image2.Url });
|
||||||
@@ -131,7 +138,7 @@ public class NovelUpdateServiceTests
|
|||||||
{
|
{
|
||||||
using var dbContext = CreateDbContext();
|
using var dbContext = CreateDbContext();
|
||||||
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
|
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
|
||||||
var (novel, chapter) = CreateNovelWithSingleChapter(dbContext, source);
|
var (novel, volume, chapter) = CreateNovelWithSingleChapter(dbContext, source);
|
||||||
|
|
||||||
var rawHtml = "<p>Hi</p><img src=\"http://img/x1.jpg\">";
|
var rawHtml = "<p>Hi</p><img src=\"http://img/x1.jpg\">";
|
||||||
var image = new ImageData { Url = "http://img/x1.jpg", Data = new byte[] { 7, 8, 9 } };
|
var image = new ImageData { Url = "http://img/x1.jpg", Data = new byte[] { 7, 8, 9 } };
|
||||||
@@ -150,7 +157,7 @@ public class NovelUpdateServiceTests
|
|||||||
|
|
||||||
var service = CreateService(dbContext, adapter, eventBus);
|
var service = CreateService(dbContext, adapter, eventBus);
|
||||||
|
|
||||||
var updatedChapter = await service.PullChapterContents(novel.Id, chapter.Order);
|
var updatedChapter = await service.PullChapterContents(novel.Id, volume.Id, chapter.Order);
|
||||||
|
|
||||||
var storedHtml = updatedChapter.Body.Texts.Single().Text;
|
var storedHtml = updatedChapter.Body.Texts.Single().Text;
|
||||||
var doc = new HtmlDocument();
|
var doc = new HtmlDocument();
|
||||||
@@ -161,7 +168,7 @@ public class NovelUpdateServiceTests
|
|||||||
imgNode.GetAttributeValue("src", string.Empty).Should().Be("https://pending/placeholder.jpg");
|
imgNode.GetAttributeValue("src", string.Empty).Should().Be("https://pending/placeholder.jpg");
|
||||||
}
|
}
|
||||||
|
|
||||||
private record NovelCreateResult(Novel Novel, Chapter Chapter);
|
private record NovelCreateResult(Novel Novel, Volume Volume, Chapter Chapter);
|
||||||
|
|
||||||
#region UpdateImage Tests
|
#region UpdateImage Tests
|
||||||
|
|
||||||
@@ -199,7 +206,7 @@ public class NovelUpdateServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
using var dbContext = CreateDbContext();
|
using var dbContext = CreateDbContext();
|
||||||
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
|
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
|
||||||
var (novel, chapter) = CreateNovelWithSingleChapter(dbContext, source);
|
var (novel, _, chapter) = CreateNovelWithSingleChapter(dbContext, source);
|
||||||
|
|
||||||
var image = new Image
|
var image = new Image
|
||||||
{
|
{
|
||||||
@@ -252,7 +259,7 @@ public class NovelUpdateServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
using var dbContext = CreateDbContext();
|
using var dbContext = CreateDbContext();
|
||||||
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
|
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
|
||||||
var (novel, chapter) = CreateNovelWithSingleChapter(dbContext, source);
|
var (_, _, chapter) = CreateNovelWithSingleChapter(dbContext, source);
|
||||||
|
|
||||||
var image1 = new Image { OriginalPath = "http://original/img1.jpg", Chapter = chapter };
|
var image1 = new Image { OriginalPath = "http://original/img1.jpg", Chapter = chapter };
|
||||||
var image2 = new Image { OriginalPath = "http://original/img2.jpg", Chapter = chapter };
|
var image2 = new Image { OriginalPath = "http://original/img2.jpg", Chapter = chapter };
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -20,10 +21,20 @@ public class Mutation
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Authorize]
|
[Authorize]
|
||||||
public async Task<ChapterPullRequestedEvent> FetchChapterContents(uint novelId,
|
public async Task<ChapterPullRequestedEvent> FetchChapterContents(
|
||||||
uint chapterNumber,
|
uint novelId,
|
||||||
|
uint volumeId,
|
||||||
|
uint chapterOrder,
|
||||||
NovelUpdateService service)
|
NovelUpdateService service)
|
||||||
{
|
{
|
||||||
return await service.QueueChapterPull(novelId, chapterNumber);
|
return await service.QueueChapterPull(novelId, volumeId, chapterOrder);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Error<KeyNotFoundException>]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<bool> DeleteNovel(uint novelId, NovelUpdateService service)
|
||||||
|
{
|
||||||
|
await service.DeleteNovel(novelId);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -77,32 +77,45 @@ public class Query
|
|||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
|
|
||||||
Chapters = novel.Chapters.Select(chapter => new ChapterDto
|
Volumes = novel.Volumes.OrderBy(v => v.Order).Select(volume => new VolumeDto
|
||||||
{
|
{
|
||||||
Id = chapter.Id,
|
Id = volume.Id,
|
||||||
CreatedTime = chapter.CreatedTime,
|
CreatedTime = volume.CreatedTime,
|
||||||
LastUpdatedTime = chapter.LastUpdatedTime,
|
LastUpdatedTime = volume.LastUpdatedTime,
|
||||||
Revision = chapter.Revision,
|
Order = volume.Order,
|
||||||
Order = chapter.Order,
|
Name = volume.Name.Texts
|
||||||
Url = chapter.Url,
|
|
||||||
Name = chapter.Name.Texts
|
|
||||||
.Where(t => t.Language == preferredLanguage)
|
.Where(t => t.Language == preferredLanguage)
|
||||||
.Select(t => t.Text)
|
.Select(t => t.Text)
|
||||||
.FirstOrDefault()
|
.FirstOrDefault()
|
||||||
?? chapter.Name.Texts.Select(t => t.Text).FirstOrDefault()
|
?? volume.Name.Texts.Select(t => t.Text).FirstOrDefault()
|
||||||
?? "",
|
?? "",
|
||||||
Body = chapter.Body.Texts
|
Chapters = volume.Chapters.OrderBy(c => c.Order).Select(chapter => new ChapterDto
|
||||||
.Where(t => t.Language == preferredLanguage)
|
|
||||||
.Select(t => t.Text)
|
|
||||||
.FirstOrDefault()
|
|
||||||
?? chapter.Body.Texts.Select(t => t.Text).FirstOrDefault()
|
|
||||||
?? "",
|
|
||||||
Images = chapter.Images.Select(image => new ImageDto
|
|
||||||
{
|
{
|
||||||
Id = image.Id,
|
Id = chapter.Id,
|
||||||
CreatedTime = image.CreatedTime,
|
CreatedTime = chapter.CreatedTime,
|
||||||
LastUpdatedTime = image.LastUpdatedTime,
|
LastUpdatedTime = chapter.LastUpdatedTime,
|
||||||
NewPath = image.NewPath
|
Revision = chapter.Revision,
|
||||||
|
Order = chapter.Order,
|
||||||
|
Url = chapter.Url,
|
||||||
|
Name = chapter.Name.Texts
|
||||||
|
.Where(t => t.Language == preferredLanguage)
|
||||||
|
.Select(t => t.Text)
|
||||||
|
.FirstOrDefault()
|
||||||
|
?? chapter.Name.Texts.Select(t => t.Text).FirstOrDefault()
|
||||||
|
?? "",
|
||||||
|
Body = chapter.Body.Texts
|
||||||
|
.Where(t => t.Language == preferredLanguage)
|
||||||
|
.Select(t => t.Text)
|
||||||
|
.FirstOrDefault()
|
||||||
|
?? chapter.Body.Texts.Select(t => t.Text).FirstOrDefault()
|
||||||
|
?? "",
|
||||||
|
Images = chapter.Images.Select(image => new ImageDto
|
||||||
|
{
|
||||||
|
Id = image.Id,
|
||||||
|
CreatedTime = image.CreatedTime,
|
||||||
|
LastUpdatedTime = image.LastUpdatedTime,
|
||||||
|
NewPath = image.NewPath
|
||||||
|
}).ToList()
|
||||||
}).ToList()
|
}).ToList()
|
||||||
}).ToList(),
|
}).ToList(),
|
||||||
|
|
||||||
@@ -140,11 +153,12 @@ public class Query
|
|||||||
public IQueryable<ChapterReaderDto> GetChapter(
|
public IQueryable<ChapterReaderDto> GetChapter(
|
||||||
NovelServiceDbContext dbContext,
|
NovelServiceDbContext dbContext,
|
||||||
uint novelId,
|
uint novelId,
|
||||||
|
uint volumeOrder,
|
||||||
uint chapterOrder,
|
uint chapterOrder,
|
||||||
Language preferredLanguage = Language.En)
|
Language preferredLanguage = Language.En)
|
||||||
{
|
{
|
||||||
return dbContext.Chapters
|
return dbContext.Chapters
|
||||||
.Where(c => c.Novel.Id == novelId && c.Order == chapterOrder)
|
.Where(c => c.Volume.Novel.Id == novelId && c.Volume.Order == volumeOrder && c.Order == chapterOrder)
|
||||||
.Select(chapter => new ChapterReaderDto
|
.Select(chapter => new ChapterReaderDto
|
||||||
{
|
{
|
||||||
Id = chapter.Id,
|
Id = chapter.Id,
|
||||||
@@ -176,24 +190,74 @@ public class Query
|
|||||||
NewPath = image.NewPath
|
NewPath = image.NewPath
|
||||||
}).ToList(),
|
}).ToList(),
|
||||||
|
|
||||||
NovelId = chapter.Novel.Id,
|
NovelId = chapter.Volume.Novel.Id,
|
||||||
NovelName = chapter.Novel.Name.Texts
|
NovelName = chapter.Volume.Novel.Name.Texts
|
||||||
.Where(t => t.Language == preferredLanguage)
|
.Where(t => t.Language == preferredLanguage)
|
||||||
.Select(t => t.Text)
|
.Select(t => t.Text)
|
||||||
.FirstOrDefault()
|
.FirstOrDefault()
|
||||||
?? chapter.Novel.Name.Texts.Select(t => t.Text).FirstOrDefault()
|
?? chapter.Volume.Novel.Name.Texts.Select(t => t.Text).FirstOrDefault()
|
||||||
?? "",
|
?? "",
|
||||||
TotalChapters = chapter.Novel.Chapters.Count,
|
|
||||||
PrevChapterOrder = chapter.Novel.Chapters
|
// Volume context
|
||||||
|
VolumeId = chapter.Volume.Id,
|
||||||
|
VolumeName = chapter.Volume.Name.Texts
|
||||||
|
.Where(t => t.Language == preferredLanguage)
|
||||||
|
.Select(t => t.Text)
|
||||||
|
.FirstOrDefault()
|
||||||
|
?? chapter.Volume.Name.Texts.Select(t => t.Text).FirstOrDefault()
|
||||||
|
?? "",
|
||||||
|
VolumeOrder = chapter.Volume.Order,
|
||||||
|
TotalChaptersInVolume = chapter.Volume.Chapters.Count,
|
||||||
|
|
||||||
|
// Previous chapter: first try same volume, then last chapter of previous volume
|
||||||
|
PrevChapterVolumeOrder = chapter.Volume.Chapters
|
||||||
|
.Where(c => c.Order < chapterOrder)
|
||||||
|
.OrderByDescending(c => c.Order)
|
||||||
|
.Select(c => (int?)chapter.Volume.Order)
|
||||||
|
.FirstOrDefault()
|
||||||
|
?? chapter.Volume.Novel.Volumes
|
||||||
|
.Where(v => v.Order < chapter.Volume.Order)
|
||||||
|
.OrderByDescending(v => v.Order)
|
||||||
|
.SelectMany(v => v.Chapters.OrderByDescending(c => c.Order).Take(1))
|
||||||
|
.Select(c => (int?)c.Volume.Order)
|
||||||
|
.FirstOrDefault(),
|
||||||
|
|
||||||
|
PrevChapterOrder = chapter.Volume.Chapters
|
||||||
.Where(c => c.Order < chapterOrder)
|
.Where(c => c.Order < chapterOrder)
|
||||||
.OrderByDescending(c => c.Order)
|
.OrderByDescending(c => c.Order)
|
||||||
.Select(c => (uint?)c.Order)
|
.Select(c => (uint?)c.Order)
|
||||||
.FirstOrDefault(),
|
.FirstOrDefault()
|
||||||
NextChapterOrder = chapter.Novel.Chapters
|
?? chapter.Volume.Novel.Volumes
|
||||||
|
.Where(v => v.Order < chapter.Volume.Order)
|
||||||
|
.OrderByDescending(v => v.Order)
|
||||||
|
.SelectMany(v => v.Chapters.OrderByDescending(c => c.Order).Take(1))
|
||||||
|
.Select(c => (uint?)c.Order)
|
||||||
|
.FirstOrDefault(),
|
||||||
|
|
||||||
|
// Next chapter: first try same volume, then first chapter of next volume
|
||||||
|
NextChapterVolumeOrder = chapter.Volume.Chapters
|
||||||
|
.Where(c => c.Order > chapterOrder)
|
||||||
|
.OrderBy(c => c.Order)
|
||||||
|
.Select(c => (int?)chapter.Volume.Order)
|
||||||
|
.FirstOrDefault()
|
||||||
|
?? chapter.Volume.Novel.Volumes
|
||||||
|
.Where(v => v.Order > chapter.Volume.Order)
|
||||||
|
.OrderBy(v => v.Order)
|
||||||
|
.SelectMany(v => v.Chapters.OrderBy(c => c.Order).Take(1))
|
||||||
|
.Select(c => (int?)c.Volume.Order)
|
||||||
|
.FirstOrDefault(),
|
||||||
|
|
||||||
|
NextChapterOrder = chapter.Volume.Chapters
|
||||||
.Where(c => c.Order > chapterOrder)
|
.Where(c => c.Order > chapterOrder)
|
||||||
.OrderBy(c => c.Order)
|
.OrderBy(c => c.Order)
|
||||||
.Select(c => (uint?)c.Order)
|
.Select(c => (uint?)c.Order)
|
||||||
.FirstOrDefault()
|
.FirstOrDefault()
|
||||||
|
?? chapter.Volume.Novel.Volumes
|
||||||
|
.Where(v => v.Order > chapter.Volume.Order)
|
||||||
|
.OrderBy(v => v.Order)
|
||||||
|
.SelectMany(v => v.Chapters.OrderBy(c => c.Order).Take(1))
|
||||||
|
.Select(c => (uint?)c.Order)
|
||||||
|
.FirstOrDefault()
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
605
FictionArchive.Service.NovelService/Migrations/20251229203027_AddVolumes.Designer.cs
generated
Normal file
605
FictionArchive.Service.NovelService/Migrations/20251229203027_AddVolumes.Designer.cs
generated
Normal file
@@ -0,0 +1,605 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using FictionArchive.Service.NovelService.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.NovelService.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(NovelServiceDbContext))]
|
||||||
|
[Migration("20251229203027_AddVolumes")]
|
||||||
|
partial class AddVolumes
|
||||||
|
{
|
||||||
|
/// <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.NovelService.Models.Images.Image", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<long?>("ChapterId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("NewPath")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("OriginalPath")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("ChapterId");
|
||||||
|
|
||||||
|
b.ToTable("Images");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("LocalizationKeys");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Localization.LocalizationRequest", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("EngineId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<Guid>("KeyRequestedForTranslationId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<int>("TranslateTo")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("EngineId");
|
||||||
|
|
||||||
|
b.HasIndex("KeyRequestedForTranslationId");
|
||||||
|
|
||||||
|
b.ToTable("LocalizationRequests");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Localization.LocalizationText", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<int>("Language")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Guid?>("LocalizationKeyId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("Text")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<long?>("TranslationEngineId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("LocalizationKeyId");
|
||||||
|
|
||||||
|
b.HasIndex("TranslationEngineId");
|
||||||
|
|
||||||
|
b.ToTable("LocalizationText");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Chapter", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Guid>("BodyId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Guid>("NameId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<long>("Order")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<long>("Revision")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<string>("Url")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<long>("VolumeId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("BodyId");
|
||||||
|
|
||||||
|
b.HasIndex("NameId");
|
||||||
|
|
||||||
|
b.HasIndex("VolumeId", "Order")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("Chapter");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Novel", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<long>("AuthorId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<Guid?>("CoverImageId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Guid>("DescriptionId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("ExternalId")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Guid>("NameId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<int>("RawLanguage")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<int>("RawStatus")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<long>("SourceId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<int?>("StatusOverride")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<string>("Url")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("AuthorId");
|
||||||
|
|
||||||
|
b.HasIndex("CoverImageId");
|
||||||
|
|
||||||
|
b.HasIndex("DescriptionId");
|
||||||
|
|
||||||
|
b.HasIndex("NameId");
|
||||||
|
|
||||||
|
b.HasIndex("SourceId");
|
||||||
|
|
||||||
|
b.HasIndex("ExternalId", "SourceId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("Novels");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.NovelTag", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Guid>("DisplayNameId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<string>("Key")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long?>("SourceId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<int>("TagType")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("DisplayNameId");
|
||||||
|
|
||||||
|
b.HasIndex("SourceId");
|
||||||
|
|
||||||
|
b.ToTable("Tags");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Person", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("ExternalUrl")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Guid>("NameId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("NameId");
|
||||||
|
|
||||||
|
b.ToTable("Person");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Source", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Key")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<string>("Url")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Sources");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.TranslationEngine", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Key")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("TranslationEngines");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Volume", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Guid>("NameId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<long>("NovelId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<int>("Order")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("NameId");
|
||||||
|
|
||||||
|
b.HasIndex("NovelId", "Order")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("Volume");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("NovelNovelTag", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("NovelsId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<long>("TagsId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.HasKey("NovelsId", "TagsId");
|
||||||
|
|
||||||
|
b.HasIndex("TagsId");
|
||||||
|
|
||||||
|
b.ToTable("NovelNovelTag");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Images.Image", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Chapter", "Chapter")
|
||||||
|
.WithMany("Images")
|
||||||
|
.HasForeignKey("ChapterId");
|
||||||
|
|
||||||
|
b.Navigation("Chapter");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Localization.LocalizationRequest", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.TranslationEngine", "Engine")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("EngineId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", "KeyRequestedForTranslation")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("KeyRequestedForTranslationId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Engine");
|
||||||
|
|
||||||
|
b.Navigation("KeyRequestedForTranslation");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Localization.LocalizationText", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", null)
|
||||||
|
.WithMany("Texts")
|
||||||
|
.HasForeignKey("LocalizationKeyId");
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.TranslationEngine", "TranslationEngine")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("TranslationEngineId");
|
||||||
|
|
||||||
|
b.Navigation("TranslationEngine");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Chapter", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", "Body")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("BodyId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", "Name")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("NameId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Volume", "Volume")
|
||||||
|
.WithMany("Chapters")
|
||||||
|
.HasForeignKey("VolumeId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Body");
|
||||||
|
|
||||||
|
b.Navigation("Name");
|
||||||
|
|
||||||
|
b.Navigation("Volume");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Novel", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Person", "Author")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("AuthorId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Images.Image", "CoverImage")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("CoverImageId");
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", "Description")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("DescriptionId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", "Name")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("NameId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Source", "Source")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("SourceId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Author");
|
||||||
|
|
||||||
|
b.Navigation("CoverImage");
|
||||||
|
|
||||||
|
b.Navigation("Description");
|
||||||
|
|
||||||
|
b.Navigation("Name");
|
||||||
|
|
||||||
|
b.Navigation("Source");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.NovelTag", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", "DisplayName")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("DisplayNameId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Source", "Source")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("SourceId");
|
||||||
|
|
||||||
|
b.Navigation("DisplayName");
|
||||||
|
|
||||||
|
b.Navigation("Source");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Person", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", "Name")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("NameId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Name");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Volume", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", "Name")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("NameId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Novel", "Novel")
|
||||||
|
.WithMany("Volumes")
|
||||||
|
.HasForeignKey("NovelId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Name");
|
||||||
|
|
||||||
|
b.Navigation("Novel");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("NovelNovelTag", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Novel", null)
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("NovelsId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.NovelTag", null)
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("TagsId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Texts");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Chapter", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Images");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Novel", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Volumes");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Volume", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Chapters");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using NodaTime;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.NovelService.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddVolumes : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
// 1. Create the Volume table
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "Volume",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "bigint", nullable: false)
|
||||||
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
|
Order = table.Column<int>(type: "integer", nullable: false),
|
||||||
|
NameId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
NovelId = table.Column<long>(type: "bigint", nullable: false),
|
||||||
|
CreatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
|
||||||
|
LastUpdatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_Volume", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_Volume_LocalizationKeys_NameId",
|
||||||
|
column: x => x.NameId,
|
||||||
|
principalTable: "LocalizationKeys",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_Volume_Novels_NovelId",
|
||||||
|
column: x => x.NovelId,
|
||||||
|
principalTable: "Novels",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_Volume_NameId",
|
||||||
|
table: "Volume",
|
||||||
|
column: "NameId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_Volume_NovelId_Order",
|
||||||
|
table: "Volume",
|
||||||
|
columns: new[] { "NovelId", "Order" },
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
// 2. Add nullable VolumeId column to Chapter (keep NovelId for now)
|
||||||
|
migrationBuilder.AddColumn<long>(
|
||||||
|
name: "VolumeId",
|
||||||
|
table: "Chapter",
|
||||||
|
type: "bigint",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
// 3. Data migration: Create volumes and link chapters for each novel
|
||||||
|
migrationBuilder.Sql(@"
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
novel_rec RECORD;
|
||||||
|
loc_key_id uuid;
|
||||||
|
volume_id bigint;
|
||||||
|
BEGIN
|
||||||
|
FOR novel_rec IN SELECT ""Id"", ""RawLanguage"" FROM ""Novels"" LOOP
|
||||||
|
-- Create LocalizationKey for volume name
|
||||||
|
loc_key_id := gen_random_uuid();
|
||||||
|
INSERT INTO ""LocalizationKeys"" (""Id"", ""CreatedTime"", ""LastUpdatedTime"")
|
||||||
|
VALUES (loc_key_id, NOW(), NOW());
|
||||||
|
|
||||||
|
-- Create LocalizationText for 'Main Story' in novel's raw language
|
||||||
|
INSERT INTO ""LocalizationText"" (""Id"", ""LocalizationKeyId"", ""Language"", ""Text"", ""CreatedTime"", ""LastUpdatedTime"")
|
||||||
|
VALUES (gen_random_uuid(), loc_key_id, novel_rec.""RawLanguage"", 'Main Story', NOW(), NOW());
|
||||||
|
|
||||||
|
-- Create Volume for this novel
|
||||||
|
INSERT INTO ""Volume"" (""Order"", ""NameId"", ""NovelId"", ""CreatedTime"", ""LastUpdatedTime"")
|
||||||
|
VALUES (1, loc_key_id, novel_rec.""Id"", NOW(), NOW())
|
||||||
|
RETURNING ""Id"" INTO volume_id;
|
||||||
|
|
||||||
|
-- Link all chapters of this novel to the new volume
|
||||||
|
UPDATE ""Chapter"" SET ""VolumeId"" = volume_id WHERE ""NovelId"" = novel_rec.""Id"";
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
");
|
||||||
|
|
||||||
|
// 4. Drop old FK and index for NovelId
|
||||||
|
migrationBuilder.DropForeignKey(
|
||||||
|
name: "FK_Chapter_Novels_NovelId",
|
||||||
|
table: "Chapter");
|
||||||
|
|
||||||
|
migrationBuilder.DropIndex(
|
||||||
|
name: "IX_Chapter_NovelId",
|
||||||
|
table: "Chapter");
|
||||||
|
|
||||||
|
// 5. Drop NovelId column from Chapter
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "NovelId",
|
||||||
|
table: "Chapter");
|
||||||
|
|
||||||
|
// 6. Make VolumeId non-nullable
|
||||||
|
migrationBuilder.AlterColumn<long>(
|
||||||
|
name: "VolumeId",
|
||||||
|
table: "Chapter",
|
||||||
|
type: "bigint",
|
||||||
|
nullable: false,
|
||||||
|
oldClrType: typeof(long),
|
||||||
|
oldType: "bigint",
|
||||||
|
oldNullable: true);
|
||||||
|
|
||||||
|
// 7. Add unique index and FK for VolumeId
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_Chapter_VolumeId_Order",
|
||||||
|
table: "Chapter",
|
||||||
|
columns: new[] { "VolumeId", "Order" },
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddForeignKey(
|
||||||
|
name: "FK_Chapter_Volume_VolumeId",
|
||||||
|
table: "Chapter",
|
||||||
|
column: "VolumeId",
|
||||||
|
principalTable: "Volume",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
// Add back NovelId column
|
||||||
|
migrationBuilder.AddColumn<long>(
|
||||||
|
name: "NovelId",
|
||||||
|
table: "Chapter",
|
||||||
|
type: "bigint",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
// Migrate data back: set NovelId from Volume
|
||||||
|
migrationBuilder.Sql(@"
|
||||||
|
UPDATE ""Chapter"" c
|
||||||
|
SET ""NovelId"" = v.""NovelId""
|
||||||
|
FROM ""Volume"" v
|
||||||
|
WHERE c.""VolumeId"" = v.""Id"";
|
||||||
|
");
|
||||||
|
|
||||||
|
// Make NovelId non-nullable
|
||||||
|
migrationBuilder.AlterColumn<long>(
|
||||||
|
name: "NovelId",
|
||||||
|
table: "Chapter",
|
||||||
|
type: "bigint",
|
||||||
|
nullable: false,
|
||||||
|
oldClrType: typeof(long),
|
||||||
|
oldType: "bigint",
|
||||||
|
oldNullable: true);
|
||||||
|
|
||||||
|
// Drop VolumeId FK and index
|
||||||
|
migrationBuilder.DropForeignKey(
|
||||||
|
name: "FK_Chapter_Volume_VolumeId",
|
||||||
|
table: "Chapter");
|
||||||
|
|
||||||
|
migrationBuilder.DropIndex(
|
||||||
|
name: "IX_Chapter_VolumeId_Order",
|
||||||
|
table: "Chapter");
|
||||||
|
|
||||||
|
// Drop VolumeId column
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "VolumeId",
|
||||||
|
table: "Chapter");
|
||||||
|
|
||||||
|
// Recreate NovelId index and FK
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_Chapter_NovelId",
|
||||||
|
table: "Chapter",
|
||||||
|
column: "NovelId");
|
||||||
|
|
||||||
|
migrationBuilder.AddForeignKey(
|
||||||
|
name: "FK_Chapter_Novels_NovelId",
|
||||||
|
table: "Chapter",
|
||||||
|
column: "NovelId",
|
||||||
|
principalTable: "Novels",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
|
||||||
|
// Note: Volume LocalizationKeys are not cleaned up in Down migration
|
||||||
|
// as they may have been modified. Manual cleanup may be needed.
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "Volume");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -153,9 +153,6 @@ namespace FictionArchive.Service.NovelService.Migrations
|
|||||||
b.Property<Guid>("NameId")
|
b.Property<Guid>("NameId")
|
||||||
.HasColumnType("uuid");
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
b.Property<long>("NovelId")
|
|
||||||
.HasColumnType("bigint");
|
|
||||||
|
|
||||||
b.Property<long>("Order")
|
b.Property<long>("Order")
|
||||||
.HasColumnType("bigint");
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
@@ -165,13 +162,17 @@ namespace FictionArchive.Service.NovelService.Migrations
|
|||||||
b.Property<string>("Url")
|
b.Property<string>("Url")
|
||||||
.HasColumnType("text");
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<long>("VolumeId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
b.HasKey("Id");
|
b.HasKey("Id");
|
||||||
|
|
||||||
b.HasIndex("BodyId");
|
b.HasIndex("BodyId");
|
||||||
|
|
||||||
b.HasIndex("NameId");
|
b.HasIndex("NameId");
|
||||||
|
|
||||||
b.HasIndex("NovelId");
|
b.HasIndex("VolumeId", "Order")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
b.ToTable("Chapter");
|
b.ToTable("Chapter");
|
||||||
});
|
});
|
||||||
@@ -357,6 +358,39 @@ namespace FictionArchive.Service.NovelService.Migrations
|
|||||||
b.ToTable("TranslationEngines");
|
b.ToTable("TranslationEngines");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Volume", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Guid>("NameId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<long>("NovelId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<int>("Order")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("NameId");
|
||||||
|
|
||||||
|
b.HasIndex("NovelId", "Order")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("Volume");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("NovelNovelTag", b =>
|
modelBuilder.Entity("NovelNovelTag", b =>
|
||||||
{
|
{
|
||||||
b.Property<long>("NovelsId")
|
b.Property<long>("NovelsId")
|
||||||
@@ -427,9 +461,9 @@ namespace FictionArchive.Service.NovelService.Migrations
|
|||||||
.OnDelete(DeleteBehavior.Cascade)
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
.IsRequired();
|
.IsRequired();
|
||||||
|
|
||||||
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Novel", "Novel")
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Volume", "Volume")
|
||||||
.WithMany("Chapters")
|
.WithMany("Chapters")
|
||||||
.HasForeignKey("NovelId")
|
.HasForeignKey("VolumeId")
|
||||||
.OnDelete(DeleteBehavior.Cascade)
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
.IsRequired();
|
.IsRequired();
|
||||||
|
|
||||||
@@ -437,7 +471,7 @@ namespace FictionArchive.Service.NovelService.Migrations
|
|||||||
|
|
||||||
b.Navigation("Name");
|
b.Navigation("Name");
|
||||||
|
|
||||||
b.Navigation("Novel");
|
b.Navigation("Volume");
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Novel", b =>
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Novel", b =>
|
||||||
@@ -509,6 +543,25 @@ namespace FictionArchive.Service.NovelService.Migrations
|
|||||||
b.Navigation("Name");
|
b.Navigation("Name");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Volume", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Localization.LocalizationKey", "Name")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("NameId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Novel", "Novel")
|
||||||
|
.WithMany("Volumes")
|
||||||
|
.HasForeignKey("NovelId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Name");
|
||||||
|
|
||||||
|
b.Navigation("Novel");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("NovelNovelTag", b =>
|
modelBuilder.Entity("NovelNovelTag", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Novel", null)
|
b.HasOne("FictionArchive.Service.NovelService.Models.Novels.Novel", null)
|
||||||
@@ -535,6 +588,11 @@ namespace FictionArchive.Service.NovelService.Migrations
|
|||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Novel", b =>
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Novel", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Volumes");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.NovelService.Models.Novels.Volume", b =>
|
||||||
{
|
{
|
||||||
b.Navigation("Chapters");
|
b.Navigation("Chapters");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -12,7 +12,16 @@ public class ChapterReaderDto : BaseDto<uint>
|
|||||||
// Navigation context
|
// Navigation context
|
||||||
public uint NovelId { get; init; }
|
public uint NovelId { get; init; }
|
||||||
public required string NovelName { get; init; }
|
public required string NovelName { get; init; }
|
||||||
public int TotalChapters { get; init; }
|
|
||||||
|
// Volume context
|
||||||
|
public uint VolumeId { get; init; }
|
||||||
|
public required string VolumeName { get; init; }
|
||||||
|
public int VolumeOrder { get; init; }
|
||||||
|
public int TotalChaptersInVolume { get; init; }
|
||||||
|
|
||||||
|
// Cross-volume navigation (VolumeOrder + ChapterOrder identify a chapter)
|
||||||
|
public int? PrevChapterVolumeOrder { get; init; }
|
||||||
public uint? PrevChapterOrder { get; init; }
|
public uint? PrevChapterOrder { get; init; }
|
||||||
|
public int? NextChapterVolumeOrder { get; init; }
|
||||||
public uint? NextChapterOrder { get; init; }
|
public uint? NextChapterOrder { get; init; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ public class NovelDto : BaseDto<uint>
|
|||||||
public required string ExternalId { get; init; }
|
public required string ExternalId { get; init; }
|
||||||
public required string Name { get; init; }
|
public required string Name { get; init; }
|
||||||
public required string Description { get; init; }
|
public required string Description { get; init; }
|
||||||
public required List<ChapterDto> Chapters { get; init; }
|
public required List<VolumeDto> Volumes { get; init; }
|
||||||
public required List<NovelTagDto> Tags { get; init; }
|
public required List<NovelTagDto> Tags { get; init; }
|
||||||
public ImageDto? CoverImage { get; init; }
|
public ImageDto? CoverImage { get; init; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace FictionArchive.Service.NovelService.Models.DTOs;
|
||||||
|
|
||||||
|
public class VolumeDto : BaseDto<uint>
|
||||||
|
{
|
||||||
|
public int Order { get; init; }
|
||||||
|
public required string Name { get; init; }
|
||||||
|
public required List<ChapterDto> Chapters { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
||||||
|
|
||||||
|
public class ChapterCreatedEvent : IIntegrationEvent
|
||||||
|
{
|
||||||
|
public required uint ChapterId { get; init; }
|
||||||
|
public required uint NovelId { get; init; }
|
||||||
|
public required uint VolumeId { get; init; }
|
||||||
|
public required int VolumeOrder { get; init; }
|
||||||
|
public required uint ChapterOrder { get; init; }
|
||||||
|
public required string ChapterTitle { get; init; }
|
||||||
|
}
|
||||||
@@ -5,5 +5,6 @@ namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
|||||||
public class ChapterPullRequestedEvent : IIntegrationEvent
|
public class ChapterPullRequestedEvent : IIntegrationEvent
|
||||||
{
|
{
|
||||||
public uint NovelId { get; set; }
|
public uint NovelId { get; set; }
|
||||||
public uint ChapterNumber { get; set; }
|
public uint VolumeId { get; set; }
|
||||||
|
public uint ChapterOrder { get; set; }
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using FictionArchive.Common.Enums;
|
||||||
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
||||||
|
|
||||||
|
public class NovelCreatedEvent : IIntegrationEvent
|
||||||
|
{
|
||||||
|
public required uint NovelId { get; init; }
|
||||||
|
public required string Title { get; init; }
|
||||||
|
public required Language OriginalLanguage { get; init; }
|
||||||
|
public required string Source { get; init; }
|
||||||
|
public required string AuthorName { get; init; }
|
||||||
|
}
|
||||||
@@ -19,8 +19,8 @@ public class Chapter : BaseEntity<uint>
|
|||||||
public List<Image> Images { get; set; }
|
public List<Image> Images { get; set; }
|
||||||
|
|
||||||
#region Navigation Properties
|
#region Navigation Properties
|
||||||
|
|
||||||
public Novel Novel { get; set; }
|
public Volume Volume { get; set; }
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
@@ -21,7 +21,7 @@ public class Novel : BaseEntity<uint>
|
|||||||
public LocalizationKey Name { get; set; }
|
public LocalizationKey Name { get; set; }
|
||||||
public LocalizationKey Description { get; set; }
|
public LocalizationKey Description { get; set; }
|
||||||
|
|
||||||
public List<Chapter> Chapters { get; set; }
|
public List<Volume> Volumes { get; set; }
|
||||||
public List<NovelTag> Tags { get; set; }
|
public List<NovelTag> Tags { get; set; }
|
||||||
public Image? CoverImage { get; set; }
|
public Image? CoverImage { get; set; }
|
||||||
}
|
}
|
||||||
24
FictionArchive.Service.NovelService/Models/Novels/Volume.cs
Normal file
24
FictionArchive.Service.NovelService/Models/Novels/Volume.cs
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
|
using FictionArchive.Service.NovelService.Models.Localization;
|
||||||
|
using FictionArchive.Service.Shared.Models;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.NovelService.Models.Novels;
|
||||||
|
|
||||||
|
[Table("Volume")]
|
||||||
|
public class Volume : BaseEntity<uint>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Signed int to allow special ordering like -1 for "Author Notes" at top.
|
||||||
|
/// </summary>
|
||||||
|
public int Order { get; set; }
|
||||||
|
|
||||||
|
public LocalizationKey Name { get; set; }
|
||||||
|
|
||||||
|
public List<Chapter> Chapters { get; set; }
|
||||||
|
|
||||||
|
#region Navigation Properties
|
||||||
|
|
||||||
|
public Novel Novel { get; set; }
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -16,7 +16,7 @@ public class NovelMetadata
|
|||||||
public Language RawLanguage { get; set; }
|
public Language RawLanguage { get; set; }
|
||||||
public NovelStatus RawStatus { get; set; }
|
public NovelStatus RawStatus { get; set; }
|
||||||
|
|
||||||
public List<ChapterMetadata> Chapters { get; set; }
|
public List<VolumeMetadata> Volumes { get; set; }
|
||||||
public List<string> SourceTags { get; set; }
|
public List<string> SourceTags { get; set; }
|
||||||
public List<string> SystemTags { get; set; }
|
public List<string> SystemTags { get; set; }
|
||||||
public SourceDescriptor SourceDescriptor { get; set; }
|
public SourceDescriptor SourceDescriptor { get; set; }
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace FictionArchive.Service.NovelService.Models.SourceAdapters;
|
||||||
|
|
||||||
|
public class VolumeMetadata
|
||||||
|
{
|
||||||
|
public int Order { get; set; }
|
||||||
|
public string Name { get; set; }
|
||||||
|
public List<ChapterMetadata> Chapters { get; set; }
|
||||||
|
}
|
||||||
@@ -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>();
|
||||||
|
|||||||
@@ -14,6 +14,6 @@ public class ChapterPullRequestedEventHandler : IIntegrationEventHandler<Chapter
|
|||||||
|
|
||||||
public async Task Handle(ChapterPullRequestedEvent @event)
|
public async Task Handle(ChapterPullRequestedEvent @event)
|
||||||
{
|
{
|
||||||
await _novelUpdateService.PullChapterContents(@event.NovelId, @event.ChapterNumber);
|
await _novelUpdateService.PullChapterContents(@event.NovelId, @event.VolumeId, @event.ChapterOrder);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,6 +10,7 @@ public class NovelServiceDbContext(DbContextOptions options, ILogger<NovelServic
|
|||||||
: FictionArchiveDbContext(options, logger)
|
: FictionArchiveDbContext(options, logger)
|
||||||
{
|
{
|
||||||
public DbSet<Novel> Novels { get; set; }
|
public DbSet<Novel> Novels { get; set; }
|
||||||
|
public DbSet<Volume> Volumes { get; set; }
|
||||||
public DbSet<Chapter> Chapters { get; set; }
|
public DbSet<Chapter> Chapters { get; set; }
|
||||||
public DbSet<Source> Sources { get; set; }
|
public DbSet<Source> Sources { get; set; }
|
||||||
public DbSet<TranslationEngine> TranslationEngines { get; set; }
|
public DbSet<TranslationEngine> TranslationEngines { get; set; }
|
||||||
@@ -25,5 +26,15 @@ public class NovelServiceDbContext(DbContextOptions options, ILogger<NovelServic
|
|||||||
modelBuilder.Entity<Novel>()
|
modelBuilder.Entity<Novel>()
|
||||||
.HasIndex("ExternalId", "SourceId")
|
.HasIndex("ExternalId", "SourceId")
|
||||||
.IsUnique();
|
.IsUnique();
|
||||||
|
|
||||||
|
// Volume.Order is unique per Novel
|
||||||
|
modelBuilder.Entity<Volume>()
|
||||||
|
.HasIndex("NovelId", "Order")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
// Chapter.Order is unique per Volume
|
||||||
|
modelBuilder.Entity<Chapter>()
|
||||||
|
.HasIndex("VolumeId", "Order")
|
||||||
|
.IsUnique();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -190,6 +190,48 @@ public class NovelUpdateService
|
|||||||
return existingChapters.Concat(newChapters).ToList();
|
return existingChapters.Concat(newChapters).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static List<Volume> SynchronizeVolumes(
|
||||||
|
List<VolumeMetadata> metadataVolumes,
|
||||||
|
Language rawLanguage,
|
||||||
|
List<Volume>? existingVolumes)
|
||||||
|
{
|
||||||
|
existingVolumes ??= new List<Volume>();
|
||||||
|
var result = new List<Volume>();
|
||||||
|
|
||||||
|
foreach (var metaVolume in metadataVolumes)
|
||||||
|
{
|
||||||
|
// Match volumes by Order (unique per novel)
|
||||||
|
var existingVolume = existingVolumes.FirstOrDefault(v => v.Order == metaVolume.Order);
|
||||||
|
|
||||||
|
if (existingVolume != null)
|
||||||
|
{
|
||||||
|
// Volume exists - sync its chapters
|
||||||
|
existingVolume.Chapters = SynchronizeChapters(
|
||||||
|
metaVolume.Chapters,
|
||||||
|
rawLanguage,
|
||||||
|
existingVolume.Chapters);
|
||||||
|
result.Add(existingVolume);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// New volume - create it with synced chapters
|
||||||
|
var newVolume = new Volume
|
||||||
|
{
|
||||||
|
Order = metaVolume.Order,
|
||||||
|
Name = LocalizationKey.CreateFromText(metaVolume.Name, rawLanguage),
|
||||||
|
Chapters = SynchronizeChapters(metaVolume.Chapters, rawLanguage, null)
|
||||||
|
};
|
||||||
|
result.Add(newVolume);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep existing volumes not in metadata (user-created volumes)
|
||||||
|
var metaOrders = metadataVolumes.Select(v => v.Order).ToHashSet();
|
||||||
|
result.AddRange(existingVolumes.Where(v => !metaOrders.Contains(v.Order)));
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
private static (Image? image, bool shouldPublishEvent) HandleCoverImage(
|
private static (Image? image, bool shouldPublishEvent) HandleCoverImage(
|
||||||
ImageData? newCoverData,
|
ImageData? newCoverData,
|
||||||
Image? existingCoverImage)
|
Image? existingCoverImage)
|
||||||
@@ -232,7 +274,7 @@ public class NovelUpdateService
|
|||||||
metadata.SystemTags,
|
metadata.SystemTags,
|
||||||
metadata.RawLanguage);
|
metadata.RawLanguage);
|
||||||
|
|
||||||
var chapters = SynchronizeChapters(metadata.Chapters, metadata.RawLanguage, null);
|
var volumes = SynchronizeVolumes(metadata.Volumes, metadata.RawLanguage, null);
|
||||||
|
|
||||||
var novel = new Novel
|
var novel = new Novel
|
||||||
{
|
{
|
||||||
@@ -243,7 +285,7 @@ public class NovelUpdateService
|
|||||||
CoverImage = metadata.CoverImage != null
|
CoverImage = metadata.CoverImage != null
|
||||||
? new Image { OriginalPath = metadata.CoverImage.Url }
|
? new Image { OriginalPath = metadata.CoverImage.Url }
|
||||||
: null,
|
: null,
|
||||||
Chapters = chapters,
|
Volumes = volumes,
|
||||||
Description = LocalizationKey.CreateFromText(metadata.Description, metadata.RawLanguage),
|
Description = LocalizationKey.CreateFromText(metadata.Description, metadata.RawLanguage),
|
||||||
Name = LocalizationKey.CreateFromText(metadata.Name, metadata.RawLanguage),
|
Name = LocalizationKey.CreateFromText(metadata.Name, metadata.RawLanguage),
|
||||||
RawStatus = metadata.RawStatus,
|
RawStatus = metadata.RawStatus,
|
||||||
@@ -281,15 +323,18 @@ 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.Volumes)
|
||||||
|
.ThenInclude(volume => volume.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 &&
|
||||||
@@ -298,6 +343,12 @@ public class NovelUpdateService
|
|||||||
Novel novel;
|
Novel novel;
|
||||||
bool shouldPublishCoverEvent;
|
bool shouldPublishCoverEvent;
|
||||||
|
|
||||||
|
// Capture existing chapter IDs to detect new chapters later
|
||||||
|
var existingChapterIds = existingNovel?.Volumes
|
||||||
|
.SelectMany(v => v.Chapters)
|
||||||
|
.Select(c => c.Id)
|
||||||
|
.ToHashSet() ?? new HashSet<uint>();
|
||||||
|
|
||||||
if (existingNovel == null)
|
if (existingNovel == null)
|
||||||
{
|
{
|
||||||
// CREATE PATH: New novel
|
// CREATE PATH: New novel
|
||||||
@@ -325,11 +376,11 @@ public class NovelUpdateService
|
|||||||
metadata.SystemTags,
|
metadata.SystemTags,
|
||||||
metadata.RawLanguage);
|
metadata.RawLanguage);
|
||||||
|
|
||||||
// Synchronize chapters (add only)
|
// Synchronize volumes (and their chapters)
|
||||||
novel.Chapters = SynchronizeChapters(
|
novel.Volumes = SynchronizeVolumes(
|
||||||
metadata.Chapters,
|
metadata.Volumes,
|
||||||
metadata.RawLanguage,
|
metadata.RawLanguage,
|
||||||
existingNovel.Chapters);
|
existingNovel.Volumes);
|
||||||
|
|
||||||
// Handle cover image
|
// Handle cover image
|
||||||
(novel.CoverImage, shouldPublishCoverEvent) = HandleCoverImage(
|
(novel.CoverImage, shouldPublishCoverEvent) = HandleCoverImage(
|
||||||
@@ -339,6 +390,36 @@ public class NovelUpdateService
|
|||||||
|
|
||||||
await _dbContext.SaveChangesAsync();
|
await _dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
// Publish novel created event for new novels
|
||||||
|
if (existingNovel == null)
|
||||||
|
{
|
||||||
|
await _eventBus.Publish(new NovelCreatedEvent
|
||||||
|
{
|
||||||
|
NovelId = novel.Id,
|
||||||
|
Title = novel.Name.Texts.First(t => t.Language == novel.RawLanguage).Text,
|
||||||
|
OriginalLanguage = novel.RawLanguage,
|
||||||
|
Source = novel.Source.Key,
|
||||||
|
AuthorName = novel.Author.Name.Texts.First(t => t.Language == novel.RawLanguage).Text
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish chapter created events for new chapters
|
||||||
|
foreach (var volume in novel.Volumes)
|
||||||
|
{
|
||||||
|
foreach (var chapter in volume.Chapters.Where(c => !existingChapterIds.Contains(c.Id)))
|
||||||
|
{
|
||||||
|
await _eventBus.Publish(new ChapterCreatedEvent
|
||||||
|
{
|
||||||
|
ChapterId = chapter.Id,
|
||||||
|
NovelId = novel.Id,
|
||||||
|
VolumeId = volume.Id,
|
||||||
|
VolumeOrder = volume.Order,
|
||||||
|
ChapterOrder = chapter.Order,
|
||||||
|
ChapterTitle = chapter.Name.Texts.First(t => t.Language == novel.RawLanguage).Text
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Publish cover image event if needed
|
// Publish cover image event if needed
|
||||||
if (shouldPublishCoverEvent && novel.CoverImage != null && metadata.CoverImage != null)
|
if (shouldPublishCoverEvent && novel.CoverImage != null && metadata.CoverImage != null)
|
||||||
{
|
{
|
||||||
@@ -351,39 +432,59 @@ public class NovelUpdateService
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Publish chapter pull events for chapters without body content
|
// Publish chapter pull events for chapters without body content
|
||||||
var chaptersNeedingPull = novel.Chapters
|
foreach (var volume in novel.Volumes)
|
||||||
.Where(c => c.Body?.Texts == null || !c.Body.Texts.Any())
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
foreach (var chapter in chaptersNeedingPull)
|
|
||||||
{
|
{
|
||||||
await _eventBus.Publish(new ChapterPullRequestedEvent
|
var chaptersNeedingPull = volume.Chapters
|
||||||
|
.Where(c => c.Body?.Texts == null || !c.Body.Texts.Any())
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
foreach (var chapter in chaptersNeedingPull)
|
||||||
{
|
{
|
||||||
NovelId = novel.Id,
|
await _eventBus.Publish(new ChapterPullRequestedEvent
|
||||||
ChapterNumber = chapter.Order
|
{
|
||||||
});
|
NovelId = novel.Id,
|
||||||
|
VolumeId = volume.Id,
|
||||||
|
ChapterOrder = chapter.Order
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return novel;
|
return novel;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Chapter> PullChapterContents(uint novelId, uint chapterNumber)
|
public async Task<Chapter> PullChapterContents(uint novelId, uint volumeId, uint chapterOrder)
|
||||||
{
|
{
|
||||||
var novel = await _dbContext.Novels.Where(novel => novel.Id == novelId)
|
var novel = await _dbContext.Novels.Where(novel => novel.Id == novelId)
|
||||||
.Include(novel => novel.Chapters)
|
.Include(novel => novel.Volumes)
|
||||||
|
.ThenInclude(volume => volume.Chapters)
|
||||||
.ThenInclude(chapter => chapter.Body)
|
.ThenInclude(chapter => chapter.Body)
|
||||||
.ThenInclude(body => body.Texts)
|
.ThenInclude(body => body.Texts)
|
||||||
.Include(novel => novel.Source).Include(novel => novel.Chapters).ThenInclude(chapter => chapter.Images)
|
.Include(novel => novel.Source)
|
||||||
|
.Include(novel => novel.Volumes)
|
||||||
|
.ThenInclude(volume => volume.Chapters)
|
||||||
|
.ThenInclude(chapter => chapter.Images)
|
||||||
.FirstOrDefaultAsync();
|
.FirstOrDefaultAsync();
|
||||||
var chapter = novel.Chapters.Where(chapter => chapter.Order == chapterNumber).FirstOrDefault();
|
var volume = novel.Volumes.FirstOrDefault(v => v.Id == volumeId);
|
||||||
|
var chapter = volume.Chapters.FirstOrDefault(c => c.Order == chapterOrder);
|
||||||
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
|
||||||
@@ -466,14 +567,72 @@ public class NovelUpdateService
|
|||||||
return importNovelRequestEvent;
|
return importNovelRequestEvent;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ChapterPullRequestedEvent> QueueChapterPull(uint novelId, uint chapterNumber)
|
public async Task<ChapterPullRequestedEvent> QueueChapterPull(uint novelId, uint volumeId, uint chapterOrder)
|
||||||
{
|
{
|
||||||
var chapterPullEvent = new ChapterPullRequestedEvent()
|
var chapterPullEvent = new ChapterPullRequestedEvent()
|
||||||
{
|
{
|
||||||
NovelId = novelId,
|
NovelId = novelId,
|
||||||
ChapterNumber = chapterNumber
|
VolumeId = volumeId,
|
||||||
|
ChapterOrder = chapterOrder
|
||||||
};
|
};
|
||||||
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.Volumes).ThenInclude(v => v.Name).ThenInclude(k => k.Texts)
|
||||||
|
.Include(n => n.Volumes).ThenInclude(v => v.Chapters).ThenInclude(c => c.Images)
|
||||||
|
.Include(n => n.Volumes).ThenInclude(v => v.Chapters).ThenInclude(c => c.Name).ThenInclude(k => k.Texts)
|
||||||
|
.Include(n => n.Volumes).ThenInclude(v => v.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 };
|
||||||
|
foreach (var volume in novel.Volumes)
|
||||||
|
{
|
||||||
|
locKeyIds.Add(volume.Name.Id);
|
||||||
|
locKeyIds.AddRange(volume.Chapters.Select(c => c.Name.Id));
|
||||||
|
locKeyIds.AddRange(volume.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 volume in novel.Volumes)
|
||||||
|
{
|
||||||
|
_dbContext.RemoveRange(volume.Name.Texts);
|
||||||
|
foreach (var chapter in volume.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 volume in novel.Volumes)
|
||||||
|
{
|
||||||
|
foreach (var chapter in volume.Chapters)
|
||||||
|
_dbContext.Images.RemoveRange(chapter.Images);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Remove novel - cascades: volumes, chapters, localization keys, tag mappings
|
||||||
|
_dbContext.Novels.Remove(novel);
|
||||||
|
await _dbContext.SaveChangesAsync();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ public class NovelpiaAdapter : ISourceAdapter
|
|||||||
ExternalId = novelId.ToString(),
|
ExternalId = novelId.ToString(),
|
||||||
SystemTags = new List<string>(),
|
SystemTags = new List<string>(),
|
||||||
SourceTags = new List<string>(),
|
SourceTags = new List<string>(),
|
||||||
Chapters = new List<ChapterMetadata>(),
|
Volumes = new List<VolumeMetadata>(),
|
||||||
SourceDescriptor = SourceDescriptor
|
SourceDescriptor = SourceDescriptor
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -132,16 +132,17 @@ public class NovelpiaAdapter : ISourceAdapter
|
|||||||
{
|
{
|
||||||
novel.SourceTags.Add(tag);
|
novel.SourceTags.Add(tag);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Author's posts (from notice_table in the page HTML)
|
||||||
|
var authorsPosts = ParseAuthorsPosts(novelData);
|
||||||
|
|
||||||
// Chapters
|
// Chapters
|
||||||
uint page = 0;
|
uint page = 0;
|
||||||
List<ChapterMetadata> chapters = new List<ChapterMetadata>();
|
List<ChapterMetadata> chapters = new List<ChapterMetadata>();
|
||||||
List<uint> seenChapterIds = new List<uint>();
|
List<uint> seenChapterIds = new List<uint>();
|
||||||
uint chapterOrder = 0;
|
uint chapterOrder = 1;
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
await Task.Delay(500);
|
|
||||||
_logger.LogInformation("Next chapter batch");
|
|
||||||
var response = await _httpClient.PostAsync(EpisodeListEndpoint, new FormUrlEncodedContent(new Dictionary<string, string>
|
var response = await _httpClient.PostAsync(EpisodeListEndpoint, new FormUrlEncodedContent(new Dictionary<string, string>
|
||||||
{
|
{
|
||||||
{"novel_no", novelId.ToString()},
|
{"novel_no", novelId.ToString()},
|
||||||
@@ -170,8 +171,26 @@ public class NovelpiaAdapter : ISourceAdapter
|
|||||||
}
|
}
|
||||||
page++;
|
page++;
|
||||||
}
|
}
|
||||||
novel.Chapters = chapters;
|
|
||||||
|
// Add Author's Posts volume if there are any
|
||||||
|
if (authorsPosts.Count > 0)
|
||||||
|
{
|
||||||
|
novel.Volumes.Add(new VolumeMetadata
|
||||||
|
{
|
||||||
|
Order = 0,
|
||||||
|
Name = "Author's Posts",
|
||||||
|
Chapters = authorsPosts
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main Story volume
|
||||||
|
novel.Volumes.Add(new VolumeMetadata
|
||||||
|
{
|
||||||
|
Order = 1,
|
||||||
|
Name = "Main Story",
|
||||||
|
Chapters = chapters
|
||||||
|
});
|
||||||
|
|
||||||
return novel;
|
return novel;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,4 +262,40 @@ public class NovelpiaAdapter : ISourceAdapter
|
|||||||
}
|
}
|
||||||
return await image.Content.ReadAsByteArrayAsync();
|
return await image.Content.ReadAsByteArrayAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private List<ChapterMetadata> ParseAuthorsPosts(string novelHtml)
|
||||||
|
{
|
||||||
|
var posts = new List<ChapterMetadata>();
|
||||||
|
|
||||||
|
// Find the notice_table section
|
||||||
|
var noticeTableMatch = Regex.Match(novelHtml,
|
||||||
|
@"(?s)<table[^>]*class=""notice_table[^""]*""[^>]*>(.*?)</table>");
|
||||||
|
if (!noticeTableMatch.Success)
|
||||||
|
return posts;
|
||||||
|
|
||||||
|
var tableContent = noticeTableMatch.Groups[1].Value;
|
||||||
|
|
||||||
|
// Find all td elements with onclick containing viewer URL and extract title from <b>
|
||||||
|
// HTML structure: <td ... onclick="...location='/viewer/3330612';"><b>Title</b>
|
||||||
|
var postMatches = Regex.Matches(tableContent,
|
||||||
|
@"onclick=""[^""]*location='/viewer/(\d+)'[^""]*""[^>]*><b>([^<]+)</b>");
|
||||||
|
|
||||||
|
uint order = 1;
|
||||||
|
foreach (Match match in postMatches)
|
||||||
|
{
|
||||||
|
string viewerId = match.Groups[1].Value;
|
||||||
|
string title = WebUtility.HtmlDecode(match.Groups[2].Value.Trim());
|
||||||
|
|
||||||
|
posts.Add(new ChapterMetadata
|
||||||
|
{
|
||||||
|
Revision = 0,
|
||||||
|
Order = order,
|
||||||
|
Url = $"https://novelpia.com/viewer/{viewerId}",
|
||||||
|
Name = title
|
||||||
|
});
|
||||||
|
order++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return posts;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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>
|
||||||
|
|||||||
23
FictionArchive.Service.UserNovelDataService/Dockerfile
Normal file
23
FictionArchive.Service.UserNovelDataService/Dockerfile
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
|
||||||
|
USER $APP_UID
|
||||||
|
WORKDIR /app
|
||||||
|
EXPOSE 8080
|
||||||
|
EXPOSE 8081
|
||||||
|
|
||||||
|
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||||
|
ARG BUILD_CONFIGURATION=Release
|
||||||
|
WORKDIR /src
|
||||||
|
COPY ["FictionArchive.Service.UserNovelDataService/FictionArchive.Service.UserNovelDataService.csproj", "FictionArchive.Service.UserNovelDataService/"]
|
||||||
|
RUN dotnet restore "FictionArchive.Service.UserNovelDataService/FictionArchive.Service.UserNovelDataService.csproj"
|
||||||
|
COPY . .
|
||||||
|
WORKDIR "/src/FictionArchive.Service.UserNovelDataService"
|
||||||
|
RUN dotnet build "./FictionArchive.Service.UserNovelDataService.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||||
|
|
||||||
|
FROM build AS publish
|
||||||
|
ARG BUILD_CONFIGURATION=Release
|
||||||
|
RUN dotnet publish "./FictionArchive.Service.UserNovelDataService.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||||
|
|
||||||
|
FROM base AS final
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=publish /app/publish .
|
||||||
|
ENTRYPOINT ["dotnet", "FictionArchive.Service.UserNovelDataService.dll"]
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Content Include="..\.dockerignore">
|
||||||
|
<Link>.dockerignore</Link>
|
||||||
|
</Content>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
109
FictionArchive.Service.UserNovelDataService/GraphQL/Mutation.cs
Normal file
109
FictionArchive.Service.UserNovelDataService/GraphQL/Mutation.cs
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Services;
|
||||||
|
using HotChocolate.Authorization;
|
||||||
|
using HotChocolate.Types;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.GraphQL;
|
||||||
|
|
||||||
|
public class Mutation
|
||||||
|
{
|
||||||
|
[Authorize]
|
||||||
|
[Error<InvalidOperationException>]
|
||||||
|
public async Task<BookmarkPayload> UpsertBookmark(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal,
|
||||||
|
UpsertBookmarkInput input)
|
||||||
|
{
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Unable to determine current user identity");
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.Users
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
// Auto-create user if not exists
|
||||||
|
user = new User { OAuthProviderId = oAuthProviderId };
|
||||||
|
dbContext.Users.Add(user);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
var existingBookmark = await dbContext.Bookmarks
|
||||||
|
.FirstOrDefaultAsync(b => b.UserId == user.Id && b.ChapterId == input.ChapterId);
|
||||||
|
|
||||||
|
if (existingBookmark != null)
|
||||||
|
{
|
||||||
|
// Update existing
|
||||||
|
existingBookmark.Description = input.Description;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Create new
|
||||||
|
existingBookmark = new Bookmark
|
||||||
|
{
|
||||||
|
UserId = user.Id,
|
||||||
|
NovelId = input.NovelId,
|
||||||
|
ChapterId = input.ChapterId,
|
||||||
|
Description = input.Description
|
||||||
|
};
|
||||||
|
dbContext.Bookmarks.Add(existingBookmark);
|
||||||
|
}
|
||||||
|
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
return new BookmarkPayload
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
Bookmark = new BookmarkDto
|
||||||
|
{
|
||||||
|
Id = existingBookmark.Id,
|
||||||
|
ChapterId = existingBookmark.ChapterId,
|
||||||
|
NovelId = existingBookmark.NovelId,
|
||||||
|
Description = existingBookmark.Description,
|
||||||
|
CreatedTime = existingBookmark.CreatedTime
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
[Error<InvalidOperationException>]
|
||||||
|
public async Task<BookmarkPayload> RemoveBookmark(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal,
|
||||||
|
uint chapterId)
|
||||||
|
{
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Unable to determine current user identity");
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.Users
|
||||||
|
.AsNoTracking()
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return new BookmarkPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
var bookmark = await dbContext.Bookmarks
|
||||||
|
.FirstOrDefaultAsync(b => b.UserId == user.Id && b.ChapterId == chapterId);
|
||||||
|
|
||||||
|
if (bookmark == null)
|
||||||
|
{
|
||||||
|
return new BookmarkPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
dbContext.Bookmarks.Remove(bookmark);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
return new BookmarkPayload { Success = true };
|
||||||
|
}
|
||||||
|
}
|
||||||
45
FictionArchive.Service.UserNovelDataService/GraphQL/Query.cs
Normal file
45
FictionArchive.Service.UserNovelDataService/GraphQL/Query.cs
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Services;
|
||||||
|
using HotChocolate.Authorization;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.GraphQL;
|
||||||
|
|
||||||
|
public class Query
|
||||||
|
{
|
||||||
|
[Authorize]
|
||||||
|
public async Task<IQueryable<BookmarkDto>> GetBookmarks(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal,
|
||||||
|
uint novelId)
|
||||||
|
{
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
return new List<BookmarkDto>().AsQueryable();
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.Users
|
||||||
|
.AsNoTracking()
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return new List<BookmarkDto>().AsQueryable();
|
||||||
|
}
|
||||||
|
|
||||||
|
return dbContext.Bookmarks
|
||||||
|
.AsNoTracking()
|
||||||
|
.Where(b => b.UserId == user.Id && b.NovelId == novelId)
|
||||||
|
.OrderByDescending(b => b.CreatedTime)
|
||||||
|
.Select(b => new BookmarkDto
|
||||||
|
{
|
||||||
|
Id = b.Id,
|
||||||
|
ChapterId = b.ChapterId,
|
||||||
|
NovelId = b.NovelId,
|
||||||
|
Description = b.Description,
|
||||||
|
CreatedTime = b.CreatedTime
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
99
FictionArchive.Service.UserNovelDataService/Migrations/20251230181559_AddBookmarks.Designer.cs
generated
Normal file
99
FictionArchive.Service.UserNovelDataService/Migrations/20251230181559_AddBookmarks.Designer.cs
generated
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.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.UserNovelDataService.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(UserNovelDataServiceDbContext))]
|
||||||
|
[Migration("20251230181559_AddBookmarks")]
|
||||||
|
partial class AddBookmarks
|
||||||
|
{
|
||||||
|
/// <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.UserNovelDataService.Models.Database.Bookmark", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<long>("ChapterId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("NovelId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("UserId", "ChapterId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.HasIndex("UserId", "NovelId");
|
||||||
|
|
||||||
|
b.ToTable("Bookmarks");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.User", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("OAuthProviderId")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Users");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Bookmark", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.User", "User")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("UserId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("User");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using NodaTime;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddBookmarks : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "Users",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
OAuthProviderId = table.Column<string>(type: "text", nullable: false),
|
||||||
|
CreatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
|
||||||
|
LastUpdatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_Users", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "Bookmarks",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<int>(type: "integer", nullable: false)
|
||||||
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
|
UserId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
ChapterId = table.Column<long>(type: "bigint", nullable: false),
|
||||||
|
NovelId = table.Column<long>(type: "bigint", nullable: false),
|
||||||
|
Description = table.Column<string>(type: "text", nullable: true),
|
||||||
|
CreatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
|
||||||
|
LastUpdatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_Bookmarks", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_Bookmarks_Users_UserId",
|
||||||
|
column: x => x.UserId,
|
||||||
|
principalTable: "Users",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_Bookmarks_UserId_ChapterId",
|
||||||
|
table: "Bookmarks",
|
||||||
|
columns: new[] { "UserId", "ChapterId" },
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_Bookmarks_UserId_NovelId",
|
||||||
|
table: "Bookmarks",
|
||||||
|
columns: new[] { "UserId", "NovelId" });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "Bookmarks");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "Users");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
198
FictionArchive.Service.UserNovelDataService/Migrations/20260119184741_AddNovelVolumeChapter.Designer.cs
generated
Normal file
198
FictionArchive.Service.UserNovelDataService/Migrations/20260119184741_AddNovelVolumeChapter.Designer.cs
generated
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.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.UserNovelDataService.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(UserNovelDataServiceDbContext))]
|
||||||
|
[Migration("20260119184741_AddNovelVolumeChapter")]
|
||||||
|
partial class AddNovelVolumeChapter
|
||||||
|
{
|
||||||
|
/// <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.UserNovelDataService.Models.Database.Bookmark", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<long>("ChapterId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("NovelId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("UserId", "ChapterId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.HasIndex("UserId", "NovelId");
|
||||||
|
|
||||||
|
b.ToTable("Bookmarks");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Chapter", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("VolumeId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("VolumeId");
|
||||||
|
|
||||||
|
b.ToTable("Chapters");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Novel", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Novels");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.User", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("OAuthProviderId")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Users");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("NovelId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("NovelId");
|
||||||
|
|
||||||
|
b.ToTable("Volumes");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Bookmark", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.User", "User")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("UserId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("User");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Chapter", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", "Volume")
|
||||||
|
.WithMany("Chapters")
|
||||||
|
.HasForeignKey("VolumeId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Volume");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.Novel", "Novel")
|
||||||
|
.WithMany("Volumes")
|
||||||
|
.HasForeignKey("NovelId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Novel");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Novel", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Volumes");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Chapters");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using NodaTime;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddNovelVolumeChapter : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "Novels",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "bigint", nullable: false)
|
||||||
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
|
CreatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
|
||||||
|
LastUpdatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_Novels", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "Volumes",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "bigint", nullable: false)
|
||||||
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
|
NovelId = table.Column<long>(type: "bigint", nullable: false),
|
||||||
|
CreatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
|
||||||
|
LastUpdatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_Volumes", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_Volumes_Novels_NovelId",
|
||||||
|
column: x => x.NovelId,
|
||||||
|
principalTable: "Novels",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "Chapters",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "bigint", nullable: false)
|
||||||
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
|
VolumeId = table.Column<long>(type: "bigint", nullable: false),
|
||||||
|
CreatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
|
||||||
|
LastUpdatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_Chapters", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_Chapters_Volumes_VolumeId",
|
||||||
|
column: x => x.VolumeId,
|
||||||
|
principalTable: "Volumes",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_Chapters_VolumeId",
|
||||||
|
table: "Chapters",
|
||||||
|
column: "VolumeId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_Volumes_NovelId",
|
||||||
|
table: "Volumes",
|
||||||
|
column: "NovelId");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "Chapters");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "Volumes");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "Novels");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Services;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
using NodaTime;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(UserNovelDataServiceDbContext))]
|
||||||
|
partial class UserNovelDataServiceDbContextModelSnapshot : ModelSnapshot
|
||||||
|
{
|
||||||
|
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder
|
||||||
|
.HasAnnotation("ProductVersion", "9.0.11")
|
||||||
|
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||||
|
|
||||||
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Bookmark", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<long>("ChapterId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("NovelId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("UserId", "ChapterId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.HasIndex("UserId", "NovelId");
|
||||||
|
|
||||||
|
b.ToTable("Bookmarks");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Chapter", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("VolumeId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("VolumeId");
|
||||||
|
|
||||||
|
b.ToTable("Chapters");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Novel", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Novels");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.User", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("OAuthProviderId")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Users");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("NovelId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("NovelId");
|
||||||
|
|
||||||
|
b.ToTable("Volumes");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Bookmark", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.User", "User")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("UserId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("User");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Chapter", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", "Volume")
|
||||||
|
.WithMany("Chapters")
|
||||||
|
.HasForeignKey("VolumeId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Volume");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.Novel", "Novel")
|
||||||
|
.WithMany("Volumes")
|
||||||
|
.HasForeignKey("NovelId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Novel");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Novel", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Volumes");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Chapters");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
using NodaTime;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
|
||||||
|
public class BookmarkDto
|
||||||
|
{
|
||||||
|
public int Id { get; init; }
|
||||||
|
public uint ChapterId { get; init; }
|
||||||
|
public uint NovelId { get; init; }
|
||||||
|
public string? Description { get; init; }
|
||||||
|
public Instant CreatedTime { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
|
||||||
|
public class BookmarkPayload
|
||||||
|
{
|
||||||
|
public BookmarkDto? Bookmark { get; init; }
|
||||||
|
public bool Success { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
|
||||||
|
public record UpsertBookmarkInput(uint NovelId, uint ChapterId, string? Description);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using FictionArchive.Service.Shared.Models;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
|
||||||
|
public class Bookmark : BaseEntity<int>
|
||||||
|
{
|
||||||
|
public Guid UserId { get; set; }
|
||||||
|
public virtual User User { get; set; } = null!;
|
||||||
|
|
||||||
|
public uint ChapterId { get; set; }
|
||||||
|
public uint NovelId { get; set; }
|
||||||
|
|
||||||
|
public string? Description { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
using FictionArchive.Service.Shared.Models;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
|
||||||
|
public class Chapter : BaseEntity<uint>
|
||||||
|
{
|
||||||
|
public uint VolumeId { get; set; }
|
||||||
|
public virtual Volume Volume { get; set; } = null!;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using FictionArchive.Service.Shared.Models;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
|
||||||
|
public class Novel : BaseEntity<uint>
|
||||||
|
{
|
||||||
|
public virtual ICollection<Volume> Volumes { get; set; } = new List<Volume>();
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using FictionArchive.Service.Shared.Models;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
|
||||||
|
public class User : BaseEntity<Guid>
|
||||||
|
{
|
||||||
|
public required string OAuthProviderId { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
using FictionArchive.Service.Shared.Models;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
|
||||||
|
public class Volume : BaseEntity<uint>
|
||||||
|
{
|
||||||
|
public uint NovelId { get; set; }
|
||||||
|
public virtual Novel Novel { get; set; } = null!;
|
||||||
|
public virtual ICollection<Chapter> Chapters { get; set; } = new List<Chapter>();
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.IntegrationEvents;
|
||||||
|
|
||||||
|
public class ChapterCreatedEvent : IIntegrationEvent
|
||||||
|
{
|
||||||
|
public required uint ChapterId { get; init; }
|
||||||
|
public required uint NovelId { get; init; }
|
||||||
|
public required uint VolumeId { get; init; }
|
||||||
|
public required int VolumeOrder { get; init; }
|
||||||
|
public required uint ChapterOrder { get; init; }
|
||||||
|
public required string ChapterTitle { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using FictionArchive.Common.Enums;
|
||||||
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.IntegrationEvents;
|
||||||
|
|
||||||
|
public class NovelCreatedEvent : IIntegrationEvent
|
||||||
|
{
|
||||||
|
public required uint NovelId { get; init; }
|
||||||
|
public required string Title { get; init; }
|
||||||
|
public required Language OriginalLanguage { get; init; }
|
||||||
|
public required string Source { get; init; }
|
||||||
|
public required string AuthorName { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.IntegrationEvents;
|
||||||
|
|
||||||
|
public class UserInvitedEvent : IIntegrationEvent
|
||||||
|
{
|
||||||
|
public Guid InvitedUserId { get; set; }
|
||||||
|
public required string InvitedUsername { get; set; }
|
||||||
|
public required string InvitedEmail { get; set; }
|
||||||
|
public required string InvitedOAuthProviderId { get; set; }
|
||||||
|
|
||||||
|
public Guid InviterId { get; set; }
|
||||||
|
public required string InviterUsername { get; set; }
|
||||||
|
public required string InviterOAuthProviderId { get; set; }
|
||||||
|
}
|
||||||
80
FictionArchive.Service.UserNovelDataService/Program.cs
Normal file
80
FictionArchive.Service.UserNovelDataService/Program.cs
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
using FictionArchive.Common.Extensions;
|
||||||
|
using FictionArchive.Service.Shared;
|
||||||
|
using FictionArchive.Service.Shared.Extensions;
|
||||||
|
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.GraphQL;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.IntegrationEvents;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Services;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Services.EventHandlers;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService;
|
||||||
|
|
||||||
|
public class Program
|
||||||
|
{
|
||||||
|
public static void Main(string[] args)
|
||||||
|
{
|
||||||
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
|
var isSchemaExport = SchemaExportDetector.IsSchemaExportMode(args);
|
||||||
|
|
||||||
|
builder.AddLocalAppsettings();
|
||||||
|
|
||||||
|
builder.Services.AddMemoryCache();
|
||||||
|
builder.Services.AddHealthChecks();
|
||||||
|
|
||||||
|
#region Event Bus
|
||||||
|
|
||||||
|
if (!isSchemaExport)
|
||||||
|
{
|
||||||
|
builder.Services.AddRabbitMQ(opt =>
|
||||||
|
{
|
||||||
|
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
|
||||||
|
})
|
||||||
|
.Subscribe<NovelCreatedEvent, NovelCreatedEventHandler>()
|
||||||
|
.Subscribe<ChapterCreatedEvent, ChapterCreatedEventHandler>()
|
||||||
|
.Subscribe<UserInvitedEvent, UserInvitedEventHandler>();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region GraphQL
|
||||||
|
|
||||||
|
builder.Services.AddDefaultGraphQl<Query, Mutation>()
|
||||||
|
.AddAuthorization();
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Database
|
||||||
|
|
||||||
|
builder.Services.RegisterDbContext<UserNovelDataServiceDbContext>(
|
||||||
|
builder.Configuration.GetConnectionString("DefaultConnection"),
|
||||||
|
skipInfrastructure: isSchemaExport);
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
// Authentication & Authorization
|
||||||
|
builder.Services.AddOidcAuthentication(builder.Configuration);
|
||||||
|
builder.Services.AddFictionArchiveAuthorization();
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
|
||||||
|
// Update database (skip in schema export mode)
|
||||||
|
if (!isSchemaExport)
|
||||||
|
{
|
||||||
|
using var scope = app.Services.CreateScope();
|
||||||
|
var dbContext = scope.ServiceProvider.GetRequiredService<UserNovelDataServiceDbContext>();
|
||||||
|
dbContext.UpdateDatabase();
|
||||||
|
}
|
||||||
|
|
||||||
|
app.UseHttpsRedirection();
|
||||||
|
|
||||||
|
app.MapHealthChecks("/healthz");
|
||||||
|
|
||||||
|
app.UseAuthentication();
|
||||||
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
app.MapGraphQL();
|
||||||
|
|
||||||
|
app.RunWithGraphQLCommands(args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||||
|
"iisSettings": {
|
||||||
|
"windowsAuthentication": false,
|
||||||
|
"anonymousAuthentication": true,
|
||||||
|
"iisExpress": {
|
||||||
|
"applicationUrl": "http://localhost:26318",
|
||||||
|
"sslPort": 44303
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"profiles": {
|
||||||
|
"http": {
|
||||||
|
"commandName": "Project",
|
||||||
|
"dotnetRunMessages": true,
|
||||||
|
"launchBrowser": true,
|
||||||
|
"applicationUrl": "http://localhost:5130",
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"https": {
|
||||||
|
"commandName": "Project",
|
||||||
|
"dotnetRunMessages": true,
|
||||||
|
"launchBrowser": true,
|
||||||
|
"applicationUrl": "https://localhost:7298;http://localhost:5130",
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"IIS Express": {
|
||||||
|
"commandName": "IISExpress",
|
||||||
|
"launchBrowser": true,
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# UserNovelDataService Backfill Scripts
|
||||||
|
|
||||||
|
SQL scripts for backfilling data from UserService and NovelService into UserNovelDataService.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
1. **Run EF migrations** on the UserNovelDataService database to ensure all tables exist:
|
||||||
|
```bash
|
||||||
|
dotnet ef database update --project FictionArchive.Service.UserNovelDataService
|
||||||
|
```
|
||||||
|
|
||||||
|
This will apply the `AddNovelVolumeChapter` migration which creates:
|
||||||
|
- `Novels` table (Id, CreatedTime, LastUpdatedTime)
|
||||||
|
- `Volumes` table (Id, NovelId FK, CreatedTime, LastUpdatedTime)
|
||||||
|
- `Chapters` table (Id, VolumeId FK, CreatedTime, LastUpdatedTime)
|
||||||
|
|
||||||
|
## Execution Order
|
||||||
|
|
||||||
|
Run scripts in numeric order:
|
||||||
|
|
||||||
|
### Extraction (run against source databases)
|
||||||
|
1. `01_extract_users_from_userservice.sql` - Run against **UserService** DB
|
||||||
|
2. `02_extract_novels_from_novelservice.sql` - Run against **NovelService** DB
|
||||||
|
3. `03_extract_volumes_from_novelservice.sql` - Run against **NovelService** DB
|
||||||
|
4. `04_extract_chapters_from_novelservice.sql` - Run against **NovelService** DB
|
||||||
|
|
||||||
|
### Insertion (run against UserNovelDataService database)
|
||||||
|
5. `05_insert_users_to_usernoveldataservice.sql`
|
||||||
|
6. `06_insert_novels_to_usernoveldataservice.sql`
|
||||||
|
7. `07_insert_volumes_to_usernoveldataservice.sql`
|
||||||
|
8. `08_insert_chapters_to_usernoveldataservice.sql`
|
||||||
|
|
||||||
|
## Methods
|
||||||
|
|
||||||
|
Each script provides three options:
|
||||||
|
|
||||||
|
1. **SELECT for review** - Review data before export
|
||||||
|
2. **Generate INSERT statements** - Creates individual INSERT statements (good for small datasets)
|
||||||
|
3. **CSV export/import** - Use PostgreSQL `\copy` for bulk operations (recommended for large datasets)
|
||||||
|
|
||||||
|
## Example Workflow
|
||||||
|
|
||||||
|
### Using CSV Export/Import (Recommended)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Export from source databases
|
||||||
|
psql -h localhost -U postgres -d userservice -c "\copy (SELECT \"Id\", \"OAuthProviderId\", \"CreatedTime\", \"LastUpdatedTime\" FROM \"Users\" WHERE \"Disabled\" = false) TO '/tmp/users_export.csv' WITH CSV HEADER"
|
||||||
|
|
||||||
|
psql -h localhost -U postgres -d novelservice -c "\copy (SELECT \"Id\", \"CreatedTime\", \"LastUpdatedTime\" FROM \"Novels\") TO '/tmp/novels_export.csv' WITH CSV HEADER"
|
||||||
|
|
||||||
|
psql -h localhost -U postgres -d novelservice -c "\copy (SELECT \"Id\", \"NovelId\", \"CreatedTime\", \"LastUpdatedTime\" FROM \"Volume\" ORDER BY \"NovelId\", \"Id\") TO '/tmp/volumes_export.csv' WITH CSV HEADER"
|
||||||
|
|
||||||
|
psql -h localhost -U postgres -d novelservice -c "\copy (SELECT \"Id\", \"VolumeId\", \"CreatedTime\", \"LastUpdatedTime\" FROM \"Chapter\" ORDER BY \"VolumeId\", \"Id\") TO '/tmp/chapters_export.csv' WITH CSV HEADER"
|
||||||
|
|
||||||
|
# 2. Import into UserNovelDataService (order matters due to FK constraints!)
|
||||||
|
psql -h localhost -U postgres -d usernoveldataservice -c "\copy \"Users\" (\"Id\", \"OAuthProviderId\", \"CreatedTime\", \"LastUpdatedTime\") FROM '/tmp/users_export.csv' WITH CSV HEADER"
|
||||||
|
|
||||||
|
psql -h localhost -U postgres -d usernoveldataservice -c "\copy \"Novels\" (\"Id\", \"CreatedTime\", \"LastUpdatedTime\") FROM '/tmp/novels_export.csv' WITH CSV HEADER"
|
||||||
|
|
||||||
|
psql -h localhost -U postgres -d usernoveldataservice -c "\copy \"Volumes\" (\"Id\", \"NovelId\", \"CreatedTime\", \"LastUpdatedTime\") FROM '/tmp/volumes_export.csv' WITH CSV HEADER"
|
||||||
|
|
||||||
|
psql -h localhost -U postgres -d usernoveldataservice -c "\copy \"Chapters\" (\"Id\", \"VolumeId\", \"CreatedTime\", \"LastUpdatedTime\") FROM '/tmp/chapters_export.csv' WITH CSV HEADER"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Important**: Insert order matters due to foreign key constraints:
|
||||||
|
1. Users (no dependencies)
|
||||||
|
2. Novels (no dependencies)
|
||||||
|
3. Volumes (depends on Novels)
|
||||||
|
4. Chapters (depends on Volumes)
|
||||||
|
|
||||||
|
### Using dblink (Cross-database queries)
|
||||||
|
|
||||||
|
If both databases are on the same PostgreSQL server, you can use `dblink` extension for direct cross-database inserts. See the commented examples in each insert script.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
After running the backfill, verify counts match:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- Run on UserService DB
|
||||||
|
SELECT COUNT(*) as user_count FROM "Users" WHERE "Disabled" = false;
|
||||||
|
|
||||||
|
-- Run on NovelService DB
|
||||||
|
SELECT COUNT(*) as novel_count FROM "Novels";
|
||||||
|
SELECT COUNT(*) as volume_count FROM "Volume";
|
||||||
|
SELECT COUNT(*) as chapter_count FROM "Chapter";
|
||||||
|
|
||||||
|
-- Run on UserNovelDataService DB
|
||||||
|
SELECT COUNT(*) as user_count FROM "Users";
|
||||||
|
SELECT COUNT(*) as novel_count FROM "Novels";
|
||||||
|
SELECT COUNT(*) as volume_count FROM "Volumes";
|
||||||
|
SELECT COUNT(*) as chapter_count FROM "Chapters";
|
||||||
|
```
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
-- Extract Users from UserService database
|
||||||
|
-- Run this against: UserService PostgreSQL database
|
||||||
|
-- Output: CSV or use COPY TO for bulk export
|
||||||
|
|
||||||
|
-- Option 1: Simple SELECT for review/testing
|
||||||
|
SELECT
|
||||||
|
"Id",
|
||||||
|
"OAuthProviderId",
|
||||||
|
"CreatedTime",
|
||||||
|
"LastUpdatedTime"
|
||||||
|
FROM "Users"
|
||||||
|
WHERE "Disabled" = false
|
||||||
|
ORDER BY "CreatedTime";
|
||||||
|
|
||||||
|
-- Option 2: Generate INSERT statements (useful for small datasets)
|
||||||
|
SELECT format(
|
||||||
|
'INSERT INTO "Users" ("Id", "OAuthProviderId", "CreatedTime", "LastUpdatedTime") VALUES (%L, %L, %L, %L) ON CONFLICT ("Id") DO NOTHING;',
|
||||||
|
"Id",
|
||||||
|
"OAuthProviderId",
|
||||||
|
"CreatedTime",
|
||||||
|
"LastUpdatedTime"
|
||||||
|
)
|
||||||
|
FROM "Users"
|
||||||
|
WHERE "Disabled" = false
|
||||||
|
ORDER BY "CreatedTime";
|
||||||
|
|
||||||
|
-- Option 3: Export to CSV (run from psql)
|
||||||
|
-- \copy (SELECT "Id", "OAuthProviderId", "CreatedTime", "LastUpdatedTime" FROM "Users" WHERE "Disabled" = false ORDER BY "CreatedTime") TO '/tmp/users_export.csv' WITH CSV HEADER;
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
-- Extract Novels from NovelService database
|
||||||
|
-- Run this against: NovelService PostgreSQL database
|
||||||
|
-- Output: CSV or use COPY TO for bulk export
|
||||||
|
|
||||||
|
-- Option 1: Simple SELECT for review/testing
|
||||||
|
SELECT
|
||||||
|
"Id",
|
||||||
|
"CreatedTime",
|
||||||
|
"LastUpdatedTime"
|
||||||
|
FROM "Novels"
|
||||||
|
ORDER BY "Id";
|
||||||
|
|
||||||
|
-- Option 2: Generate INSERT statements
|
||||||
|
SELECT format(
|
||||||
|
'INSERT INTO "Novels" ("Id", "CreatedTime", "LastUpdatedTime") VALUES (%s, %L, %L) ON CONFLICT ("Id") DO NOTHING;',
|
||||||
|
"Id",
|
||||||
|
"CreatedTime",
|
||||||
|
"LastUpdatedTime"
|
||||||
|
)
|
||||||
|
FROM "Novels"
|
||||||
|
ORDER BY "Id";
|
||||||
|
|
||||||
|
-- Option 3: Export to CSV (run from psql)
|
||||||
|
-- \copy (SELECT "Id", "CreatedTime", "LastUpdatedTime" FROM "Novels" ORDER BY "Id") TO '/tmp/novels_export.csv' WITH CSV HEADER;
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
-- Extract Volumes from NovelService database
|
||||||
|
-- Run this against: NovelService PostgreSQL database
|
||||||
|
-- Output: CSV or use COPY TO for bulk export
|
||||||
|
|
||||||
|
-- Option 1: Simple SELECT for review/testing
|
||||||
|
SELECT
|
||||||
|
"Id",
|
||||||
|
"NovelId",
|
||||||
|
"CreatedTime",
|
||||||
|
"LastUpdatedTime"
|
||||||
|
FROM "Volume"
|
||||||
|
ORDER BY "NovelId", "Id";
|
||||||
|
|
||||||
|
-- Option 2: Generate INSERT statements
|
||||||
|
SELECT format(
|
||||||
|
'INSERT INTO "Volumes" ("Id", "NovelId", "CreatedTime", "LastUpdatedTime") VALUES (%s, %s, %L, %L) ON CONFLICT ("Id") DO NOTHING;',
|
||||||
|
"Id",
|
||||||
|
"NovelId",
|
||||||
|
"CreatedTime",
|
||||||
|
"LastUpdatedTime"
|
||||||
|
)
|
||||||
|
FROM "Volume"
|
||||||
|
ORDER BY "NovelId", "Id";
|
||||||
|
|
||||||
|
-- Option 3: Export to CSV (run from psql)
|
||||||
|
-- \copy (SELECT "Id", "NovelId", "CreatedTime", "LastUpdatedTime" FROM "Volume" ORDER BY "NovelId", "Id") TO '/tmp/volumes_export.csv' WITH CSV HEADER;
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
-- Extract Chapters from NovelService database
|
||||||
|
-- Run this against: NovelService PostgreSQL database
|
||||||
|
-- Output: CSV or use COPY TO for bulk export
|
||||||
|
|
||||||
|
-- Option 1: Simple SELECT for review/testing
|
||||||
|
SELECT
|
||||||
|
"Id",
|
||||||
|
"VolumeId",
|
||||||
|
"CreatedTime",
|
||||||
|
"LastUpdatedTime"
|
||||||
|
FROM "Chapter"
|
||||||
|
ORDER BY "VolumeId", "Id";
|
||||||
|
|
||||||
|
-- Option 2: Generate INSERT statements
|
||||||
|
SELECT format(
|
||||||
|
'INSERT INTO "Chapters" ("Id", "VolumeId", "CreatedTime", "LastUpdatedTime") VALUES (%s, %s, %L, %L) ON CONFLICT ("Id") DO NOTHING;',
|
||||||
|
"Id",
|
||||||
|
"VolumeId",
|
||||||
|
"CreatedTime",
|
||||||
|
"LastUpdatedTime"
|
||||||
|
)
|
||||||
|
FROM "Chapter"
|
||||||
|
ORDER BY "VolumeId", "Id";
|
||||||
|
|
||||||
|
-- Option 3: Export to CSV (run from psql)
|
||||||
|
-- \copy (SELECT "Id", "VolumeId", "CreatedTime", "LastUpdatedTime" FROM "Chapter" ORDER BY "VolumeId", "Id") TO '/tmp/chapters_export.csv' WITH CSV HEADER;
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
-- Insert Users into UserNovelDataService database
|
||||||
|
-- Run this against: UserNovelDataService PostgreSQL database
|
||||||
|
--
|
||||||
|
-- PREREQUISITE: You must have extracted users from UserService first
|
||||||
|
-- using 01_extract_users_from_userservice.sql
|
||||||
|
|
||||||
|
-- Option 1: If you have a CSV file from export
|
||||||
|
-- \copy "Users" ("Id", "OAuthProviderId", "CreatedTime", "LastUpdatedTime") FROM '/tmp/users_export.csv' WITH CSV HEADER;
|
||||||
|
|
||||||
|
-- Option 2: Direct cross-database insert using dblink
|
||||||
|
-- First, install dblink extension if not already done:
|
||||||
|
-- CREATE EXTENSION IF NOT EXISTS dblink;
|
||||||
|
|
||||||
|
-- Example using dblink (adjust connection string):
|
||||||
|
/*
|
||||||
|
INSERT INTO "Users" ("Id", "OAuthProviderId", "CreatedTime", "LastUpdatedTime")
|
||||||
|
SELECT
|
||||||
|
"Id"::uuid,
|
||||||
|
"OAuthProviderId",
|
||||||
|
"CreatedTime"::timestamp with time zone,
|
||||||
|
"LastUpdatedTime"::timestamp with time zone
|
||||||
|
FROM dblink(
|
||||||
|
'host=localhost port=5432 dbname=userservice user=postgres password=yourpassword',
|
||||||
|
'SELECT "Id", "OAuthProviderId", "CreatedTime", "LastUpdatedTime" FROM "Users" WHERE "Disabled" = false'
|
||||||
|
) AS t("Id" uuid, "OAuthProviderId" text, "CreatedTime" timestamp with time zone, "LastUpdatedTime" timestamp with time zone)
|
||||||
|
ON CONFLICT ("Id") DO UPDATE SET
|
||||||
|
"OAuthProviderId" = EXCLUDED."OAuthProviderId",
|
||||||
|
"LastUpdatedTime" = EXCLUDED."LastUpdatedTime";
|
||||||
|
*/
|
||||||
|
|
||||||
|
-- Option 3: Paste generated INSERT statements from extraction script here
|
||||||
|
-- INSERT INTO "Users" ("Id", "OAuthProviderId", "CreatedTime", "LastUpdatedTime") VALUES (...) ON CONFLICT ("Id") DO NOTHING;
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
-- Insert Novels into UserNovelDataService database
|
||||||
|
-- Run this against: UserNovelDataService PostgreSQL database
|
||||||
|
--
|
||||||
|
-- PREREQUISITE:
|
||||||
|
-- 1. Ensure the Novels table exists (run EF migrations first if needed)
|
||||||
|
-- 2. Extract novels from NovelService using 02_extract_novels_from_novelservice.sql
|
||||||
|
|
||||||
|
-- Option 1: If you have a CSV file from export
|
||||||
|
-- \copy "Novels" ("Id", "CreatedTime", "LastUpdatedTime") FROM '/tmp/novels_export.csv' WITH CSV HEADER;
|
||||||
|
|
||||||
|
-- Option 2: Direct cross-database insert using dblink
|
||||||
|
-- First, install dblink extension if not already done:
|
||||||
|
-- CREATE EXTENSION IF NOT EXISTS dblink;
|
||||||
|
|
||||||
|
-- Example using dblink (adjust connection string):
|
||||||
|
/*
|
||||||
|
INSERT INTO "Novels" ("Id", "CreatedTime", "LastUpdatedTime")
|
||||||
|
SELECT
|
||||||
|
"Id"::bigint,
|
||||||
|
"CreatedTime"::timestamp with time zone,
|
||||||
|
"LastUpdatedTime"::timestamp with time zone
|
||||||
|
FROM dblink(
|
||||||
|
'host=localhost port=5432 dbname=novelservice user=postgres password=yourpassword',
|
||||||
|
'SELECT "Id", "CreatedTime", "LastUpdatedTime" FROM "Novels"'
|
||||||
|
) AS t("Id" bigint, "CreatedTime" timestamp with time zone, "LastUpdatedTime" timestamp with time zone)
|
||||||
|
ON CONFLICT ("Id") DO UPDATE SET
|
||||||
|
"LastUpdatedTime" = EXCLUDED."LastUpdatedTime";
|
||||||
|
*/
|
||||||
|
|
||||||
|
-- Option 3: Paste generated INSERT statements from extraction script here
|
||||||
|
-- INSERT INTO "Novels" ("Id", "CreatedTime", "LastUpdatedTime") VALUES (...) ON CONFLICT ("Id") DO NOTHING;
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
-- Insert Volumes into UserNovelDataService database
|
||||||
|
-- Run this against: UserNovelDataService PostgreSQL database
|
||||||
|
--
|
||||||
|
-- PREREQUISITE:
|
||||||
|
-- 1. Ensure the Volumes table exists (run EF migrations first if needed)
|
||||||
|
-- 2. Novels must be inserted first (FK constraint)
|
||||||
|
-- 3. Extract volumes from NovelService using 03_extract_volumes_from_novelservice.sql
|
||||||
|
|
||||||
|
-- Option 1: If you have a CSV file from export
|
||||||
|
-- \copy "Volumes" ("Id", "NovelId", "CreatedTime", "LastUpdatedTime") FROM '/tmp/volumes_export.csv' WITH CSV HEADER;
|
||||||
|
|
||||||
|
-- Option 2: Direct cross-database insert using dblink
|
||||||
|
-- First, install dblink extension if not already done:
|
||||||
|
-- CREATE EXTENSION IF NOT EXISTS dblink;
|
||||||
|
|
||||||
|
-- Example using dblink (adjust connection string):
|
||||||
|
/*
|
||||||
|
INSERT INTO "Volumes" ("Id", "NovelId", "CreatedTime", "LastUpdatedTime")
|
||||||
|
SELECT
|
||||||
|
"Id"::bigint,
|
||||||
|
"NovelId"::bigint,
|
||||||
|
"CreatedTime"::timestamp with time zone,
|
||||||
|
"LastUpdatedTime"::timestamp with time zone
|
||||||
|
FROM dblink(
|
||||||
|
'host=localhost port=5432 dbname=novelservice user=postgres password=yourpassword',
|
||||||
|
'SELECT "Id", "NovelId", "CreatedTime", "LastUpdatedTime" FROM "Volume"'
|
||||||
|
) AS t("Id" bigint, "NovelId" bigint, "CreatedTime" timestamp with time zone, "LastUpdatedTime" timestamp with time zone)
|
||||||
|
ON CONFLICT ("Id") DO UPDATE SET
|
||||||
|
"NovelId" = EXCLUDED."NovelId",
|
||||||
|
"LastUpdatedTime" = EXCLUDED."LastUpdatedTime";
|
||||||
|
*/
|
||||||
|
|
||||||
|
-- Option 3: Paste generated INSERT statements from extraction script here
|
||||||
|
-- INSERT INTO "Volumes" ("Id", "NovelId", "CreatedTime", "LastUpdatedTime") VALUES (...) ON CONFLICT ("Id") DO NOTHING;
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
-- Insert Chapters into UserNovelDataService database
|
||||||
|
-- Run this against: UserNovelDataService PostgreSQL database
|
||||||
|
--
|
||||||
|
-- PREREQUISITE:
|
||||||
|
-- 1. Ensure the Chapters table exists (run EF migrations first if needed)
|
||||||
|
-- 2. Volumes must be inserted first (FK constraint)
|
||||||
|
-- 3. Extract chapters from NovelService using 04_extract_chapters_from_novelservice.sql
|
||||||
|
|
||||||
|
-- Option 1: If you have a CSV file from export
|
||||||
|
-- \copy "Chapters" ("Id", "VolumeId", "CreatedTime", "LastUpdatedTime") FROM '/tmp/chapters_export.csv' WITH CSV HEADER;
|
||||||
|
|
||||||
|
-- Option 2: Direct cross-database insert using dblink
|
||||||
|
-- First, install dblink extension if not already done:
|
||||||
|
-- CREATE EXTENSION IF NOT EXISTS dblink;
|
||||||
|
|
||||||
|
-- Example using dblink (adjust connection string):
|
||||||
|
/*
|
||||||
|
INSERT INTO "Chapters" ("Id", "VolumeId", "CreatedTime", "LastUpdatedTime")
|
||||||
|
SELECT
|
||||||
|
"Id"::bigint,
|
||||||
|
"VolumeId"::bigint,
|
||||||
|
"CreatedTime"::timestamp with time zone,
|
||||||
|
"LastUpdatedTime"::timestamp with time zone
|
||||||
|
FROM dblink(
|
||||||
|
'host=localhost port=5432 dbname=novelservice user=postgres password=yourpassword',
|
||||||
|
'SELECT "Id", "VolumeId", "CreatedTime", "LastUpdatedTime" FROM "Chapter"'
|
||||||
|
) AS t("Id" bigint, "VolumeId" bigint, "CreatedTime" timestamp with time zone, "LastUpdatedTime" timestamp with time zone)
|
||||||
|
ON CONFLICT ("Id") DO UPDATE SET
|
||||||
|
"VolumeId" = EXCLUDED."VolumeId",
|
||||||
|
"LastUpdatedTime" = EXCLUDED."LastUpdatedTime";
|
||||||
|
*/
|
||||||
|
|
||||||
|
-- Option 3: Paste generated INSERT statements from extraction script here
|
||||||
|
-- INSERT INTO "Chapters" ("Id", "VolumeId", "CreatedTime", "LastUpdatedTime") VALUES (...) ON CONFLICT ("Id") DO NOTHING;
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.IntegrationEvents;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Services.EventHandlers;
|
||||||
|
|
||||||
|
public class ChapterCreatedEventHandler : IIntegrationEventHandler<ChapterCreatedEvent>
|
||||||
|
{
|
||||||
|
private readonly UserNovelDataServiceDbContext _dbContext;
|
||||||
|
private readonly ILogger<ChapterCreatedEventHandler> _logger;
|
||||||
|
|
||||||
|
public ChapterCreatedEventHandler(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ILogger<ChapterCreatedEventHandler> logger)
|
||||||
|
{
|
||||||
|
_dbContext = dbContext;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Handle(ChapterCreatedEvent @event)
|
||||||
|
{
|
||||||
|
// Ensure novel exists
|
||||||
|
var novelExists = await _dbContext.Novels.AnyAsync(n => n.Id == @event.NovelId);
|
||||||
|
if (!novelExists)
|
||||||
|
{
|
||||||
|
var novel = new Novel { Id = @event.NovelId };
|
||||||
|
_dbContext.Novels.Add(novel);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure volume exists
|
||||||
|
var volumeExists = await _dbContext.Volumes.AnyAsync(v => v.Id == @event.VolumeId);
|
||||||
|
if (!volumeExists)
|
||||||
|
{
|
||||||
|
var volume = new Volume { Id = @event.VolumeId };
|
||||||
|
_dbContext.Volumes.Add(volume);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create chapter if not exists
|
||||||
|
var chapterExists = await _dbContext.Chapters.AnyAsync(c => c.Id == @event.ChapterId);
|
||||||
|
if (chapterExists)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("Chapter {ChapterId} already exists, skipping", @event.ChapterId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var chapter = new Chapter { Id = @event.ChapterId };
|
||||||
|
_dbContext.Chapters.Add(chapter);
|
||||||
|
await _dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
_logger.LogInformation("Created chapter stub for {ChapterId} in novel {NovelId}", @event.ChapterId, @event.NovelId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.IntegrationEvents;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Services.EventHandlers;
|
||||||
|
|
||||||
|
public class NovelCreatedEventHandler : IIntegrationEventHandler<NovelCreatedEvent>
|
||||||
|
{
|
||||||
|
private readonly UserNovelDataServiceDbContext _dbContext;
|
||||||
|
private readonly ILogger<NovelCreatedEventHandler> _logger;
|
||||||
|
|
||||||
|
public NovelCreatedEventHandler(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ILogger<NovelCreatedEventHandler> logger)
|
||||||
|
{
|
||||||
|
_dbContext = dbContext;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Handle(NovelCreatedEvent @event)
|
||||||
|
{
|
||||||
|
var exists = await _dbContext.Novels.AnyAsync(n => n.Id == @event.NovelId);
|
||||||
|
if (exists)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("Novel {NovelId} already exists, skipping", @event.NovelId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var novel = new Novel { Id = @event.NovelId };
|
||||||
|
_dbContext.Novels.Add(novel);
|
||||||
|
await _dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
_logger.LogInformation("Created novel stub for {NovelId}", @event.NovelId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
using FictionArchive.Service.Shared.Services.EventBus;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.IntegrationEvents;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Services.EventHandlers;
|
||||||
|
|
||||||
|
public class UserInvitedEventHandler : IIntegrationEventHandler<UserInvitedEvent>
|
||||||
|
{
|
||||||
|
private readonly UserNovelDataServiceDbContext _dbContext;
|
||||||
|
private readonly ILogger<UserInvitedEventHandler> _logger;
|
||||||
|
|
||||||
|
public UserInvitedEventHandler(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ILogger<UserInvitedEventHandler> logger)
|
||||||
|
{
|
||||||
|
_dbContext = dbContext;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Handle(UserInvitedEvent @event)
|
||||||
|
{
|
||||||
|
var exists = await _dbContext.Users.AnyAsync(u => u.Id == @event.InvitedUserId);
|
||||||
|
if (exists)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("User {UserId} already exists, skipping", @event.InvitedUserId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = new User
|
||||||
|
{
|
||||||
|
Id = @event.InvitedUserId,
|
||||||
|
OAuthProviderId = @event.InvitedOAuthProviderId
|
||||||
|
};
|
||||||
|
_dbContext.Users.Add(user);
|
||||||
|
await _dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
_logger.LogInformation("Created user stub for {UserId}", @event.InvitedUserId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
using FictionArchive.Service.Shared.Services.Database;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Services;
|
||||||
|
|
||||||
|
public class UserNovelDataServiceDbContext : FictionArchiveDbContext
|
||||||
|
{
|
||||||
|
public DbSet<User> Users { get; set; }
|
||||||
|
public DbSet<Bookmark> Bookmarks { get; set; }
|
||||||
|
public DbSet<Novel> Novels { get; set; }
|
||||||
|
public DbSet<Volume> Volumes { get; set; }
|
||||||
|
public DbSet<Chapter> Chapters { get; set; }
|
||||||
|
|
||||||
|
public UserNovelDataServiceDbContext(DbContextOptions options, ILogger<UserNovelDataServiceDbContext> logger) : base(options, logger)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
base.OnModelCreating(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity<Bookmark>(entity =>
|
||||||
|
{
|
||||||
|
// Unique constraint: one bookmark per chapter per user
|
||||||
|
entity.HasIndex(b => new { b.UserId, b.ChapterId }).IsUnique();
|
||||||
|
|
||||||
|
// Index for efficient "get bookmarks for novel" queries
|
||||||
|
entity.HasIndex(b => new { b.UserId, b.NovelId });
|
||||||
|
|
||||||
|
// User relationship
|
||||||
|
entity.HasOne(b => b.User)
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey(b => b.UserId)
|
||||||
|
.OnDelete(DeleteBehavior.Cascade);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
26
FictionArchive.Service.UserNovelDataService/appsettings.json
Normal file
26
FictionArchive.Service.UserNovelDataService/appsettings.json
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"DefaultConnection": "Host=localhost;Database=FictionArchive_UserNovelDataService;Username=postgres;password=postgres"
|
||||||
|
},
|
||||||
|
"RabbitMQ": {
|
||||||
|
"ConnectionString": "amqp://localhost",
|
||||||
|
"ClientIdentifier": "UserNovelDataService"
|
||||||
|
},
|
||||||
|
"OIDC": {
|
||||||
|
"Authority": "https://auth.orfl.xyz/application/o/fiction-archive/",
|
||||||
|
"ClientId": "ldi5IpEidq2WW0Ka1lehVskb2SOBjnYRaZCpEyBh",
|
||||||
|
"Audience": "ldi5IpEidq2WW0Ka1lehVskb2SOBjnYRaZCpEyBh",
|
||||||
|
"ValidIssuer": "https://auth.orfl.xyz/application/o/fiction-archive/",
|
||||||
|
"ValidateIssuer": true,
|
||||||
|
"ValidateAudience": true,
|
||||||
|
"ValidateLifetime": true,
|
||||||
|
"ValidateIssuerSigningKey": true
|
||||||
|
},
|
||||||
|
"AllowedHosts": "*"
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"subgraph": "UserNovelData",
|
||||||
|
"http": {
|
||||||
|
"baseAddress": "https://localhost:7298/graphql"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 authentikPk = 456;
|
||||||
|
var authClient = Substitute.For<IAuthenticationServiceClient>();
|
||||||
|
authClient.CreateUserAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||||
|
.Returns(new AuthentikUserResponse { Pk = authentikPk, Uid = "authentik-uid-789" });
|
||||||
|
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(authentikPk.ToString());
|
||||||
|
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.Pk.ToString(),
|
||||||
|
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,14 @@ 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
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.UserNovelDataService", "FictionArchive.Service.UserNovelDataService\FictionArchive.Service.UserNovelDataService.csproj", "{A278565B-D440-4AB9-B2E2-41BA3B3AD82A}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -54,10 +57,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 +65,13 @@ 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
|
||||||
|
{A278565B-D440-4AB9-B2E2-41BA3B3AD82A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{A278565B-D440-4AB9-B2E2-41BA3B3AD82A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{A278565B-D440-4AB9-B2E2-41BA3B3AD82A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{A278565B-D440-4AB9-B2E2-41BA3B3AD82A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
EndGlobal
|
EndGlobal
|
||||||
|
|||||||
@@ -4,25 +4,34 @@ services:
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:16-alpine
|
image: postgres:16-alpine
|
||||||
|
networks:
|
||||||
|
fictionarchive:
|
||||||
|
ipv4_address: 172.20.0.10
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_USER: ${POSTGRES_USER:-postgres}
|
POSTGRES_USER: ${POSTGRES_USER:-postgres}
|
||||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
|
||||||
volumes:
|
volumes:
|
||||||
- postgres_data:/var/lib/postgresql/data
|
- /srv/docker_volumes/fictionarchive/postgres:/var/lib/postgresql/data
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
||||||
interval: 5s
|
interval: 5s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 5
|
retries: 5
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- 4321:5432
|
||||||
|
|
||||||
rabbitmq:
|
rabbitmq:
|
||||||
image: rabbitmq:3-management-alpine
|
image: rabbitmq:3-management-alpine
|
||||||
|
networks:
|
||||||
|
fictionarchive:
|
||||||
|
ipv4_address: 172.20.0.11
|
||||||
environment:
|
environment:
|
||||||
RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-guest}
|
RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-guest}
|
||||||
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:-guest}
|
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:-guest}
|
||||||
|
RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: -rabbit max_message_size 536870912
|
||||||
volumes:
|
volumes:
|
||||||
- rabbitmq_data:/var/lib/rabbitmq
|
- /srv/docker_volumes/fictionarchive/rabbitmq:/var/lib/rabbitmq
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "rabbitmq-diagnostics", "check_running"]
|
test: ["CMD", "rabbitmq-diagnostics", "check_running"]
|
||||||
interval: 10s
|
interval: 10s
|
||||||
@@ -30,6 +39,37 @@ services:
|
|||||||
retries: 5
|
retries: 5
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
|
# ===========================================
|
||||||
|
# VPN Container
|
||||||
|
# ===========================================
|
||||||
|
vpn:
|
||||||
|
image: dperson/openvpn-client
|
||||||
|
networks:
|
||||||
|
fictionarchive:
|
||||||
|
ipv4_address: 172.20.0.20
|
||||||
|
aliases:
|
||||||
|
- novel-service
|
||||||
|
cap_add:
|
||||||
|
- NET_ADMIN
|
||||||
|
devices:
|
||||||
|
- /dev/net/tun
|
||||||
|
volumes:
|
||||||
|
- /srv/docker_volumes/korean_vpn:/vpn
|
||||||
|
dns:
|
||||||
|
- 192.168.3.1
|
||||||
|
environment:
|
||||||
|
- DNS=1.1.1.1,8.8.8.8
|
||||||
|
extra_hosts:
|
||||||
|
- "postgres:172.20.0.10"
|
||||||
|
- "rabbitmq:172.20.0.11"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "ping", "-c", "1", "-W", "5", "1.1.1.1"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 30s
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
# ===========================================
|
# ===========================================
|
||||||
# Backend Services
|
# Backend Services
|
||||||
# ===========================================
|
# ===========================================
|
||||||
@@ -37,50 +77,27 @@ services:
|
|||||||
image: git.orfl.xyz/conco/fictionarchive-novel-service:latest
|
image: git.orfl.xyz/conco/fictionarchive-novel-service:latest
|
||||||
environment:
|
environment:
|
||||||
ConnectionStrings__DefaultConnection: Host=postgres;Database=FictionArchive_NovelService;Username=${POSTGRES_USER:-postgres};Password=${POSTGRES_PASSWORD:-postgres}
|
ConnectionStrings__DefaultConnection: Host=postgres;Database=FictionArchive_NovelService;Username=${POSTGRES_USER:-postgres};Password=${POSTGRES_PASSWORD:-postgres}
|
||||||
ConnectionStrings__RabbitMQ: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
RabbitMQ__ConnectionString: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
||||||
Novelpia__Username: ${NOVELPIA_USERNAME}
|
Novelpia__Username: ${NOVELPIA_USERNAME}
|
||||||
Novelpia__Password: ${NOVELPIA_PASSWORD}
|
Novelpia__Password: ${NOVELPIA_PASSWORD}
|
||||||
NovelUpdateService__PendingImageUrl: https://files.fictionarchive.orfl.xyz/api/pendingupload.png
|
UpdateService__PendingImageUrl: https://files.fictionarchive.orfl.xyz/api/pendingupload.png
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
|
|
||||||
interval: 30s
|
|
||||||
timeout: 10s
|
|
||||||
retries: 3
|
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
rabbitmq:
|
rabbitmq:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
restart: unless-stopped
|
vpn:
|
||||||
|
|
||||||
translation-service:
|
|
||||||
image: git.orfl.xyz/conco/fictionarchive-translation-service:latest
|
|
||||||
environment:
|
|
||||||
ConnectionStrings__DefaultConnection: Host=postgres;Database=FictionArchive_TranslationService;Username=${POSTGRES_USER:-postgres};Password=${POSTGRES_PASSWORD:-postgres}
|
|
||||||
ConnectionStrings__RabbitMQ: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
|
||||||
DeepL__ApiKey: ${DEEPL_API_KEY}
|
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
|
|
||||||
interval: 30s
|
|
||||||
timeout: 10s
|
|
||||||
retries: 3
|
|
||||||
depends_on:
|
|
||||||
postgres:
|
|
||||||
condition: service_healthy
|
|
||||||
rabbitmq:
|
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
network_mode: "service:vpn"
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
scheduler-service:
|
scheduler-service:
|
||||||
image: git.orfl.xyz/conco/fictionarchive-scheduler-service:latest
|
image: git.orfl.xyz/conco/fictionarchive-scheduler-service:latest
|
||||||
|
networks:
|
||||||
|
- fictionarchive
|
||||||
environment:
|
environment:
|
||||||
ConnectionStrings__DefaultConnection: Host=postgres;Database=FictionArchive_SchedulerService;Username=${POSTGRES_USER:-postgres};Password=${POSTGRES_PASSWORD:-postgres}
|
ConnectionStrings__DefaultConnection: Host=postgres;Database=FictionArchive_SchedulerService;Username=${POSTGRES_USER:-postgres};Password=${POSTGRES_PASSWORD:-postgres}
|
||||||
ConnectionStrings__RabbitMQ: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
RabbitMQ__ConnectionString: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
|
|
||||||
interval: 30s
|
|
||||||
timeout: 10s
|
|
||||||
retries: 3
|
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -90,14 +107,14 @@ services:
|
|||||||
|
|
||||||
user-service:
|
user-service:
|
||||||
image: git.orfl.xyz/conco/fictionarchive-user-service:latest
|
image: git.orfl.xyz/conco/fictionarchive-user-service:latest
|
||||||
|
networks:
|
||||||
|
- fictionarchive
|
||||||
environment:
|
environment:
|
||||||
ConnectionStrings__DefaultConnection: Host=postgres;Database=FictionArchive_UserService;Username=${POSTGRES_USER:-postgres};Password=${POSTGRES_PASSWORD:-postgres}
|
ConnectionStrings__DefaultConnection: Host=postgres;Database=FictionArchive_UserService;Username=${POSTGRES_USER:-postgres};Password=${POSTGRES_PASSWORD:-postgres}
|
||||||
ConnectionStrings__RabbitMQ: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
RabbitMQ__ConnectionString: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
||||||
healthcheck:
|
Authentik__BaseUrl: https://auth.orfl.xyz
|
||||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
|
Authentik__ApiToken: ${AUTHENTIK_API_TOKEN}
|
||||||
interval: 30s
|
Authentik__EmailStageId: 10df0c18-8802-4ec7-852e-3cdd355514d3
|
||||||
timeout: 10s
|
|
||||||
retries: 3
|
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -105,42 +122,35 @@ services:
|
|||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
authentication-service:
|
usernoveldata-service:
|
||||||
image: git.orfl.xyz/conco/fictionarchive-authentication-service:latest
|
image: git.orfl.xyz/conco/fictionarchive-usernoveldata-service:latest
|
||||||
|
networks:
|
||||||
|
- fictionarchive
|
||||||
environment:
|
environment:
|
||||||
ConnectionStrings__RabbitMQ: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
ConnectionStrings__DefaultConnection: Host=postgres;Database=FictionArchive_UserNovelDataService;Username=${POSTGRES_USER:-postgres};Password=${POSTGRES_PASSWORD:-postgres}
|
||||||
healthcheck:
|
RabbitMQ__ConnectionString: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
||||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
|
|
||||||
interval: 30s
|
|
||||||
timeout: 10s
|
|
||||||
retries: 3
|
|
||||||
depends_on:
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
rabbitmq:
|
rabbitmq:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
file-service:
|
file-service:
|
||||||
image: git.orfl.xyz/conco/fictionarchive-file-service:latest
|
image: git.orfl.xyz/conco/fictionarchive-file-service:latest
|
||||||
|
networks:
|
||||||
|
- web
|
||||||
|
- fictionarchive
|
||||||
environment:
|
environment:
|
||||||
ConnectionStrings__RabbitMQ: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
RabbitMQ__ConnectionString: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
||||||
S3__Endpoint: ${S3_ENDPOINT:-https://s3.orfl.xyz}
|
|
||||||
S3__Bucket: ${S3_BUCKET:-fictionarchive}
|
|
||||||
S3__AccessKey: ${S3_ACCESS_KEY}
|
S3__AccessKey: ${S3_ACCESS_KEY}
|
||||||
S3__SecretKey: ${S3_SECRET_KEY}
|
S3__SecretKey: ${S3_SECRET_KEY}
|
||||||
Proxy__BaseUrl: https://files.orfl.xyz/api
|
ProxyConfiguration__BaseUrl: https://files.fictionarchive.orfl.xyz/api
|
||||||
OIDC__Authority: https://auth.orfl.xyz/application/o/fictionarchive/
|
|
||||||
OIDC__ClientId: fictionarchive-files
|
|
||||||
OIDC__Audience: fictionarchive-api
|
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
|
|
||||||
interval: 30s
|
|
||||||
timeout: 10s
|
|
||||||
retries: 3
|
|
||||||
labels:
|
labels:
|
||||||
- "traefik.enable=true"
|
- "traefik.enable=true"
|
||||||
- "traefik.http.routers.file-service.rule=Host(`files.orfl.xyz`)"
|
- "traefik.http.routers.file-service.rule=Host(`files.fictionarchive.orfl.xyz`)"
|
||||||
- "traefik.http.routers.file-service.entrypoints=websecure"
|
- "traefik.http.routers.file-service.tls=true"
|
||||||
- "traefik.http.routers.file-service.tls.certresolver=letsencrypt"
|
- "traefik.http.routers.file-service.tls.certresolver=lets-encrypt"
|
||||||
- "traefik.http.services.file-service.loadbalancer.server.port=8080"
|
- "traefik.http.services.file-service.loadbalancer.server.port=8080"
|
||||||
depends_on:
|
depends_on:
|
||||||
rabbitmq:
|
rabbitmq:
|
||||||
@@ -152,30 +162,23 @@ services:
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
api-gateway:
|
api-gateway:
|
||||||
image: git.orfl.xyz/conco/fictionarchive-api:latest
|
image: git.orfl.xyz/conco/fictionarchive-api:latest
|
||||||
|
networks:
|
||||||
|
- web
|
||||||
|
- fictionarchive
|
||||||
environment:
|
environment:
|
||||||
ConnectionStrings__RabbitMQ: amqp://${RABBITMQ_USER:-guest}:${RABBITMQ_PASSWORD:-guest}@rabbitmq
|
|
||||||
OIDC__Authority: https://auth.orfl.xyz/application/o/fictionarchive/
|
|
||||||
OIDC__ClientId: fictionarchive-api
|
|
||||||
OIDC__Audience: fictionarchive-api
|
|
||||||
Cors__AllowedOrigin: https://fictionarchive.orfl.xyz
|
Cors__AllowedOrigin: https://fictionarchive.orfl.xyz
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
|
|
||||||
interval: 30s
|
|
||||||
timeout: 10s
|
|
||||||
retries: 3
|
|
||||||
labels:
|
labels:
|
||||||
- "traefik.enable=true"
|
- "traefik.enable=true"
|
||||||
- "traefik.http.routers.api-gateway.rule=Host(`api.fictionarchive.orfl.xyz`)"
|
- "traefik.http.routers.api-gateway.rule=Host(`api.fictionarchive.orfl.xyz`)"
|
||||||
- "traefik.http.routers.api-gateway.entrypoints=websecure"
|
- "traefik.http.routers.api-gateway.tls=true"
|
||||||
- "traefik.http.routers.api-gateway.tls.certresolver=letsencrypt"
|
- "traefik.http.routers.api-gateway.tls.certresolver=lets-encrypt"
|
||||||
- "traefik.http.services.api-gateway.loadbalancer.server.port=8080"
|
- "traefik.http.services.api-gateway.loadbalancer.server.port=8080"
|
||||||
depends_on:
|
depends_on:
|
||||||
- novel-service
|
- novel-service
|
||||||
- translation-service
|
|
||||||
- scheduler-service
|
- scheduler-service
|
||||||
- user-service
|
|
||||||
- authentication-service
|
|
||||||
- file-service
|
- file-service
|
||||||
|
- user-service
|
||||||
|
- usernoveldata-service
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
# ===========================================
|
# ===========================================
|
||||||
@@ -183,20 +186,21 @@ services:
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
frontend:
|
frontend:
|
||||||
image: git.orfl.xyz/conco/fictionarchive-frontend:latest
|
image: git.orfl.xyz/conco/fictionarchive-frontend:latest
|
||||||
healthcheck:
|
networks:
|
||||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost/"]
|
- web
|
||||||
interval: 30s
|
|
||||||
timeout: 10s
|
|
||||||
retries: 3
|
|
||||||
labels:
|
labels:
|
||||||
- "traefik.enable=true"
|
- traefik.http.routers.fafrontend.rule=Host(`fictionarchive.orfl.xyz`)
|
||||||
- "traefik.http.routers.frontend.rule=Host(`fictionarchive.orfl.xyz`)"
|
- traefik.http.routers.fafrontend.tls=true
|
||||||
- "traefik.http.routers.frontend.entrypoints=websecure"
|
- traefik.http.routers.fafrontend.tls.certresolver=lets-encrypt
|
||||||
- "traefik.http.routers.frontend.tls.certresolver=letsencrypt"
|
- traefik.http.services.fafrontend.loadbalancer.server.port=80
|
||||||
- "traefik.http.services.frontend.loadbalancer.server.port=80"
|
- traefik.enable=true
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
volumes:
|
networks:
|
||||||
postgres_data:
|
web:
|
||||||
rabbitmq_data:
|
external: yes
|
||||||
letsencrypt:
|
fictionarchive:
|
||||||
|
ipam:
|
||||||
|
driver: default
|
||||||
|
config:
|
||||||
|
- subnet: 172.20.0.0/24
|
||||||
|
|||||||
14
fictionarchive-web-astro/package-lock.json
generated
14
fictionarchive-web-astro/package-lock.json
generated
@@ -12,6 +12,7 @@
|
|||||||
"@astrojs/svelte": "^7.2.2",
|
"@astrojs/svelte": "^7.2.2",
|
||||||
"@tailwindcss/vite": "^4.1.17",
|
"@tailwindcss/vite": "^4.1.17",
|
||||||
"@urql/core": "^6.0.1",
|
"@urql/core": "^6.0.1",
|
||||||
|
"@urql/exchange-auth": "^3.0.0",
|
||||||
"@urql/svelte": "^5.0.0",
|
"@urql/svelte": "^5.0.0",
|
||||||
"astro": "^5.16.2",
|
"astro": "^5.16.2",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
@@ -4304,6 +4305,19 @@
|
|||||||
"wonka": "^6.3.2"
|
"wonka": "^6.3.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@urql/exchange-auth": {
|
||||||
|
"version": "3.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@urql/exchange-auth/-/exchange-auth-3.0.0.tgz",
|
||||||
|
"integrity": "sha512-tj09xiOR2f1J2h8TE9uZWjRZipCdmDoTewEytOacDQ+0Teo+yIZxm3ppHxolQtiA51OHrGYiNTkMte8HtfvaBw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@urql/core": "^6.0.0",
|
||||||
|
"wonka": "^6.3.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@urql/core": "^6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@urql/svelte": {
|
"node_modules/@urql/svelte": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/@urql/svelte/-/svelte-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/@urql/svelte/-/svelte-5.0.0.tgz",
|
||||||
|
|||||||
@@ -16,6 +16,7 @@
|
|||||||
"@astrojs/svelte": "^7.2.2",
|
"@astrojs/svelte": "^7.2.2",
|
||||||
"@tailwindcss/vite": "^4.1.17",
|
"@tailwindcss/vite": "^4.1.17",
|
||||||
"@urql/core": "^6.0.1",
|
"@urql/core": "^6.0.1",
|
||||||
|
"@urql/exchange-auth": "^3.0.0",
|
||||||
"@urql/svelte": "^5.0.0",
|
"@urql/svelte": "^5.0.0",
|
||||||
"astro": "^5.16.2",
|
"astro": "^5.16.2",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
|
|||||||
@@ -117,3 +117,14 @@ export async function logout() {
|
|||||||
user.set(null);
|
user.set(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function refreshToken(): Promise<User | null> {
|
||||||
|
if (!userManager) return null;
|
||||||
|
try {
|
||||||
|
const newUser = await userManager.signinSilent();
|
||||||
|
return newUser;
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Token refresh failed:', e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ const authority = import.meta.env.PUBLIC_OIDC_AUTHORITY;
|
|||||||
const clientId = import.meta.env.PUBLIC_OIDC_CLIENT_ID;
|
const clientId = import.meta.env.PUBLIC_OIDC_CLIENT_ID;
|
||||||
const redirectUri = import.meta.env.PUBLIC_OIDC_REDIRECT_URI;
|
const redirectUri = import.meta.env.PUBLIC_OIDC_REDIRECT_URI;
|
||||||
const postLogoutRedirectUri = import.meta.env.PUBLIC_OIDC_POST_LOGOUT_REDIRECT_URI ?? redirectUri;
|
const postLogoutRedirectUri = import.meta.env.PUBLIC_OIDC_POST_LOGOUT_REDIRECT_URI ?? redirectUri;
|
||||||
const scope = import.meta.env.PUBLIC_OIDC_SCOPE ?? 'openid profile email';
|
const scope = import.meta.env.PUBLIC_OIDC_SCOPE ?? 'openid profile email offline_access';
|
||||||
|
|
||||||
export const isOidcConfigured =
|
export const isOidcConfigured =
|
||||||
Boolean(authority) && Boolean(clientId) && Boolean(redirectUri);
|
Boolean(authority) && Boolean(clientId) && Boolean(redirectUri);
|
||||||
@@ -20,7 +20,7 @@ function buildSettings(): UserManagerSettings | null {
|
|||||||
response_type: 'code',
|
response_type: 'code',
|
||||||
scope,
|
scope,
|
||||||
loadUserInfo: true,
|
loadUserInfo: true,
|
||||||
automaticSilentRenew: true,
|
automaticSilentRenew: false, // We handle refresh reactively via authExchange
|
||||||
userStore:
|
userStore:
|
||||||
typeof window !== 'undefined'
|
typeof window !== 'undefined'
|
||||||
? new WebStorageStateStore({ store: window.localStorage })
|
? new WebStorageStateStore({ store: window.localStorage })
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user