Compare commits
13 Commits
feature/FA
...
feature/FA
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fdf2ff7c1b | ||
|
|
e8596b67c4 | ||
|
|
16ed16ff62 | ||
|
|
573a0f6e3f | ||
|
|
1adbb955cf | ||
|
|
71e27b5dbb | ||
| 708f1a5338 | |||
|
|
df7978fb43 | ||
|
|
ceb4271182 | ||
|
|
ffa51cfce4 | ||
| 592fa7fb36 | |||
|
|
6b8cf9961b | ||
| 303a9e6a63 |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -135,3 +135,8 @@ _NCrunch*
|
||||
|
||||
# Local user appsettings
|
||||
appsettings.Local.json
|
||||
|
||||
# Fusion Builds
|
||||
schema.graphql
|
||||
*.fsp
|
||||
gateway.fgp
|
||||
36
AGENTS.md
Normal file
36
AGENTS.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Repository Guidelines
|
||||
|
||||
## Project Structure & Module Organization
|
||||
- `FictionArchive.sln` ties together the gateway and all subgraph services.
|
||||
- `FictionArchive.API`: Fusion gateway host; GraphQL endpoint at `/graphql`, health at `/healthz`, gateway configuration in `gateway.fgp`, and helper script `build_gateway.py`.
|
||||
- `FictionArchive.Service.*`: GraphQL subgraphs (`AuthenticationService`, `FileService`, `NovelService`, `SchedulerService`, `TranslationService`, `UserService`) plus shared helpers in `FictionArchive.Service.Shared`.
|
||||
- `FictionArchive.Common`: shared enums and hosting extensions used across services.
|
||||
- Environment/config files live beside each service (`appsettings*.json`, `Properties/launchSettings.json`); build outputs under `bin/` and `obj/` should stay untracked.
|
||||
|
||||
## Build, Test, and Development Commands
|
||||
- `dotnet restore` then `dotnet build FictionArchive.sln` (Debug by default) to validate all projects compile.
|
||||
- Run the gateway: `dotnet run --project FictionArchive.API` (serves HTTPS; ensure certificates are trusted locally).
|
||||
- Run a subgraph locally: `dotnet run --project FictionArchive.Service.NovelService` (or any other service) to debug a single domain.
|
||||
- Rebuild the Fusion gateway config after subgraph changes: `python FictionArchive.API/build_gateway.py` (requires Python 3 and the `fusion` CLI on PATH; uses `gateway_skip.txt` to omit services).
|
||||
- If tests are added, prefer `dotnet test FictionArchive.sln` to cover the whole solution.
|
||||
|
||||
## Coding Style & Naming Conventions
|
||||
- Target .NET 8/C# 12; use 4-space indentation and file-scoped namespaces where practical.
|
||||
- PascalCase for classes, records, interfaces, and public members; camelCase for locals/parameters; suffix async methods with `Async`.
|
||||
- Favor dependency injection and extension methods for service wiring (see `Program.cs` files and `FictionArchive.Service.Shared/Extensions`).
|
||||
- Keep GraphQL schema files and other generated artifacts out of commits unless intentionally versioned.
|
||||
|
||||
## Testing Guidelines
|
||||
- No dedicated test projects exist yet; when adding tests, create `*.Tests` projects aligned to each service (e.g., `FictionArchive.Service.NovelService.Tests`) and name test files `*Tests.cs`.
|
||||
- Prefer xUnit with fluent assertions; aim for coverage on controllers/resolvers, integration events, and critical extension methods.
|
||||
- Use in-memory fakes or test containers for external dependencies to keep tests deterministic.
|
||||
|
||||
## Commit & Pull Request Guidelines
|
||||
- Follow the observed pattern: `[FA-123] Short, imperative summary` (reference the tracker ID and keep scope focused).
|
||||
- Keep commits small and self-contained; include relevant config/schema updates produced by the gateway build script when behavior changes.
|
||||
- PRs should describe the problem, the solution, and any follow-up work; link to issues, attach GraphQL schema diffs or sample queries when applicable, and note any manual steps (migrations, secrets).
|
||||
|
||||
## Security & Configuration Tips
|
||||
- Do not commit secrets; use user secrets or environment variables for API keys and connection strings referenced in `appsettings*.json`.
|
||||
- Verify HTTPS is enabled locally; adjust `launchSettings.json` only when necessary and document non-default ports.
|
||||
- Regenerate `gateway.fgp` after changing subgraph schemas to avoid stale compositions.
|
||||
@@ -1,75 +0,0 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FictionArchive.API.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class TestController : ControllerBase
|
||||
{
|
||||
/*private readonly FictionArchiveDbContext _dbContext;
|
||||
private readonly ISourceAdapter _novelpiaAdapter;
|
||||
private readonly ITranslationEngineAdapter _translationEngine;
|
||||
|
||||
public TestController(ISourceAdapter novelpiaAdapter, FictionArchiveDbContext dbContext, ITranslationEngineAdapter translationEngine)
|
||||
{
|
||||
_novelpiaAdapter = novelpiaAdapter;
|
||||
_dbContext = dbContext;
|
||||
_translationEngine = translationEngine;
|
||||
}
|
||||
|
||||
[HttpGet("GetNovel")]
|
||||
public async Task<Novel> GetNovel(string novelUrl)
|
||||
{
|
||||
var novel = await _novelpiaAdapter.GetMetadata(novelUrl);
|
||||
novel.Source = new Source()
|
||||
{
|
||||
Name = "Novelpia",
|
||||
Id = 1,
|
||||
Url = "https://novelpia.com"
|
||||
};
|
||||
_dbContext.Novels.Add(novel);
|
||||
await _dbContext.SaveChangesAsync();
|
||||
return novel;
|
||||
}
|
||||
|
||||
[HttpGet("GetChapter")]
|
||||
public async Task<string> GetChapter(uint novelId, uint chapterNumber)
|
||||
{
|
||||
var novel = await _dbContext.Novels.Include(n => n.Chapters).ThenInclude(c => c.Translations).FirstOrDefaultAsync(n => n.Id == novelId);
|
||||
var chapter = novel.Chapters.FirstOrDefault(c => c.Order == chapterNumber);
|
||||
var rawChapter = await _novelpiaAdapter.GetRawChapter(chapter.Url);
|
||||
chapter.Translations.Add(new ChapterTranslation()
|
||||
{
|
||||
Language = novel.RawLanguage,
|
||||
Body = rawChapter
|
||||
});
|
||||
await _dbContext.SaveChangesAsync();
|
||||
return rawChapter;
|
||||
}
|
||||
|
||||
[HttpPost("TranslateChapter")]
|
||||
public async Task<ChapterTranslation> TranslateChapter(uint novelId, uint chapterNumber, Language to)
|
||||
{
|
||||
var novel = await _dbContext.Novels.Include(n => n.Chapters)
|
||||
.ThenInclude(c => c.Translations).FirstOrDefaultAsync(novel => novel.Id == novelId);
|
||||
var chapter = novel.Chapters.FirstOrDefault(c => c.Order == chapterNumber);
|
||||
var chapterRaw = chapter.Translations.FirstOrDefault(ct => ct.Language == novel.RawLanguage);
|
||||
var newTranslation = new ChapterTranslation()
|
||||
{
|
||||
Language = to,
|
||||
TranslationEngine = new TranslationEngine()
|
||||
{
|
||||
Name = "DeepL"
|
||||
}
|
||||
};
|
||||
var translation = await _translationEngine.GetTranslation(chapterRaw.Body, novel.RawLanguage, to);
|
||||
newTranslation.Body = translation;
|
||||
chapter.Translations.Add(newTranslation);
|
||||
await _dbContext.SaveChangesAsync();
|
||||
|
||||
return newTranslation;
|
||||
}*/
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
<PackageReference Include="HotChocolate.AspNetCore" Version="15.1.11" />
|
||||
<PackageReference Include="HotChocolate.Data" Version="15.1.11" />
|
||||
<PackageReference Include="HotChocolate.Data.EntityFramework" Version="15.1.11" />
|
||||
<PackageReference Include="HotChocolate.Fusion" Version="15.1.11" />
|
||||
<PackageReference Include="HotChocolate.Types.Scalars" Version="15.1.11" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
@@ -21,6 +22,11 @@
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2"/>
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Builds the Fusion graph file before building the application itself -->
|
||||
<Target Name="RunFusionBuild" BeforeTargets="BeforeBuild">
|
||||
<Exec Command="python build_gateway.py" WorkingDirectory="$(ProjectDir)" />
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\.dockerignore">
|
||||
<Link>.dockerignore</Link>
|
||||
@@ -28,8 +34,11 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Controllers\" />
|
||||
<Folder Include="GraphQL\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using FictionArchive.Service.Shared.Extensions;
|
||||
|
||||
namespace FictionArchive.API;
|
||||
|
||||
public class Program
|
||||
@@ -6,39 +8,38 @@ public class Program
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
// OpenAPI & REST
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
builder.Services.AddMemoryCache();
|
||||
|
||||
builder.Services.AddHealthChecks();
|
||||
|
||||
#region Fusion Gateway
|
||||
|
||||
builder.Services.AddHttpClient("Fusion");
|
||||
|
||||
builder.Services
|
||||
.AddFusionGatewayServer()
|
||||
.ConfigureFromFile("gateway.fgp")
|
||||
.CoreBuilder.ApplySaneDefaults();
|
||||
|
||||
#endregion
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("AllowAllOrigins",
|
||||
builder =>
|
||||
{
|
||||
builder.AllowAnyOrigin()
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader();
|
||||
});
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthentication();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapGraphQL();
|
||||
app.UseCors("AllowAllOrigins");
|
||||
|
||||
app.MapHealthChecks("/healthz");
|
||||
|
||||
app.MapControllers();
|
||||
app.MapGraphQL();
|
||||
|
||||
app.Run();
|
||||
app.RunWithGraphQLCommands(args);
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"launchUrl": "graphql",
|
||||
"applicationUrl": "https://localhost:7063;http://localhost:5234",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
|
||||
129
FictionArchive.API/build_gateway.py
Normal file
129
FictionArchive.API/build_gateway.py
Normal file
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# ----------------------------------------
|
||||
# Helpers
|
||||
# ----------------------------------------
|
||||
|
||||
def run(cmd, cwd=None):
|
||||
"""Run a command and exit on failure."""
|
||||
print(f"> {' '.join(cmd)}")
|
||||
result = subprocess.run(cmd, cwd=cwd)
|
||||
if result.returncode != 0:
|
||||
print(f"ERROR: command failed in {cwd or os.getcwd()}")
|
||||
sys.exit(result.returncode)
|
||||
|
||||
|
||||
def load_skip_list(skip_file: Path):
|
||||
if not skip_file.exists():
|
||||
print(f"WARNING: skip-projects.txt not found at {skip_file}")
|
||||
return set()
|
||||
|
||||
lines = skip_file.read_text().splitlines()
|
||||
skip = {line.strip() for line in lines
|
||||
if line.strip() and not line.strip().startswith("#")}
|
||||
print("Skip list:", ", ".join(skip) if skip else "(none)")
|
||||
return skip
|
||||
|
||||
|
||||
# ----------------------------------------
|
||||
# Setup paths
|
||||
# ----------------------------------------
|
||||
|
||||
script_dir = Path(__file__).parent.resolve()
|
||||
services_dir = (script_dir / "..").resolve()
|
||||
api_dir = services_dir / "FictionArchive.API"
|
||||
|
||||
print(f"Script dir: {script_dir}")
|
||||
print(f"Services dir: {services_dir}")
|
||||
|
||||
skip_file = script_dir / "gateway_skip.txt"
|
||||
skip_list = load_skip_list(skip_file)
|
||||
|
||||
# ----------------------------------------
|
||||
# Find services
|
||||
# ----------------------------------------
|
||||
|
||||
print("\n----------------------------------------")
|
||||
print(" Finding GraphQL services...")
|
||||
print("----------------------------------------")
|
||||
|
||||
service_dirs = [
|
||||
d for d in services_dir.glob("FictionArchive.Service.*")
|
||||
if d.is_dir()
|
||||
]
|
||||
|
||||
selected_services = []
|
||||
|
||||
for d in service_dirs:
|
||||
name = d.name
|
||||
if name in skip_list:
|
||||
print(f"Skipping: {name}")
|
||||
else:
|
||||
print(f"Found: {name}")
|
||||
selected_services.append(d)
|
||||
|
||||
if not selected_services:
|
||||
print("No services to process. Exiting.")
|
||||
sys.exit(0)
|
||||
|
||||
# ----------------------------------------
|
||||
# Export + pack
|
||||
# ----------------------------------------
|
||||
|
||||
print("\n----------------------------------------")
|
||||
print(" Exporting schemas & packing subgraphs...")
|
||||
print("----------------------------------------")
|
||||
|
||||
for svc in selected_services:
|
||||
name = svc.name
|
||||
print(f"\nProcessing {name}")
|
||||
|
||||
# Build once
|
||||
run(["dotnet", "build", "-c", "Release"], cwd=svc)
|
||||
|
||||
# Export schema
|
||||
run([
|
||||
"dotnet", "run",
|
||||
"--no-build",
|
||||
"--no-launch-profile",
|
||||
"--",
|
||||
"schema", "export",
|
||||
"--output", "schema.graphql"
|
||||
], cwd=svc)
|
||||
|
||||
# Pack subgraph
|
||||
run(["fusion", "subgraph", "pack"], cwd=svc)
|
||||
|
||||
# ----------------------------------------
|
||||
# Compose gateway
|
||||
# ----------------------------------------
|
||||
|
||||
print("\n----------------------------------------")
|
||||
print(" Running fusion compose...")
|
||||
print("----------------------------------------")
|
||||
|
||||
if not api_dir.exists():
|
||||
print(f"ERROR: FictionArchive.API not found at {api_dir}")
|
||||
sys.exit(1)
|
||||
|
||||
gateway_file = api_dir / "gateway.fgp"
|
||||
if gateway_file.exists():
|
||||
gateway_file.unlink()
|
||||
|
||||
for svc in selected_services:
|
||||
name = svc.name
|
||||
print(f"Composing: {name}")
|
||||
|
||||
run([
|
||||
"fusion", "compose",
|
||||
"-p", "gateway.fgp",
|
||||
"-s", f"..{os.sep}{name}"
|
||||
], cwd=api_dir)
|
||||
|
||||
print("\n----------------------------------------")
|
||||
print(" Fusion build complete!")
|
||||
print("----------------------------------------")
|
||||
5
FictionArchive.API/gateway_skip.txt
Normal file
5
FictionArchive.API/gateway_skip.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
# List of service folders to skip
|
||||
FictionArchive.Service.Shared
|
||||
FictionArchive.Service.AuthenticationService
|
||||
FictionArchive.Service.FileService
|
||||
FictionArchive.Service.NovelService.Tests
|
||||
8
FictionArchive.Common/Enums/RequestStatus.cs
Normal file
8
FictionArchive.Common/Enums/RequestStatus.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace FictionArchive.Common.Enums;
|
||||
|
||||
public enum RequestStatus
|
||||
{
|
||||
Failed = -1,
|
||||
Pending = 0,
|
||||
Success = 1
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using FictionArchive.Service.AuthenticationService.Models.Requests;
|
||||
using FictionArchive.Service.AuthenticationService.Models.IntegrationEvents;
|
||||
using FictionArchive.Service.Shared.Services.EventBus;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace FictionArchive.Service.AuthenticationService.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class AuthenticationWebhookController : ControllerBase
|
||||
{
|
||||
private readonly IEventBus _eventBus;
|
||||
|
||||
public AuthenticationWebhookController(IEventBus eventBus)
|
||||
{
|
||||
_eventBus = eventBus;
|
||||
}
|
||||
|
||||
[HttpPost(nameof(UserRegistered))]
|
||||
public async Task<ActionResult> UserRegistered([FromBody] UserRegisteredWebhookPayload payload)
|
||||
{
|
||||
var authUserAddedEvent = new AuthUserAddedEvent
|
||||
{
|
||||
OAuthProviderId = payload.OAuthProviderId,
|
||||
InviterOAuthProviderId = payload.InviterOAuthProviderId,
|
||||
EventUserEmail = payload.EventUserEmail,
|
||||
EventUserUsername = payload.EventUserUsername
|
||||
};
|
||||
|
||||
await _eventBus.Publish(authUserAddedEvent);
|
||||
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
23
FictionArchive.Service.AuthenticationService/Dockerfile
Normal file
23
FictionArchive.Service.AuthenticationService/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.AuthenticationService/FictionArchive.Service.AuthenticationService.csproj", "FictionArchive.Service.AuthenticationService/"]
|
||||
RUN dotnet restore "FictionArchive.Service.AuthenticationService/FictionArchive.Service.AuthenticationService.csproj"
|
||||
COPY . .
|
||||
WORKDIR "/src/FictionArchive.Service.AuthenticationService"
|
||||
RUN dotnet build "./FictionArchive.Service.AuthenticationService.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "./FictionArchive.Service.AuthenticationService.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.AuthenticationService.dll"]
|
||||
@@ -0,0 +1,29 @@
|
||||
<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.VisualStudio.Web.CodeGeneration.Design" Version="8.0.7" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\.dockerignore">
|
||||
<Link>.dockerignore</Link>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Controllers\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
@FictionArchive.Service.AuthenticationService_HostAddress = http://localhost:5091
|
||||
|
||||
GET {{FictionArchive.Service.AuthenticationService_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
@@ -0,0 +1,16 @@
|
||||
using FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
namespace FictionArchive.Service.AuthenticationService.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 @@
|
||||
namespace FictionArchive.Service.AuthenticationService.Models.Requests;
|
||||
|
||||
public class UserRegisteredWebhookPayload
|
||||
{
|
||||
// The body of the notification message
|
||||
public string Body { get; set; }
|
||||
|
||||
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; }
|
||||
}
|
||||
49
FictionArchive.Service.AuthenticationService/Program.cs
Normal file
49
FictionArchive.Service.AuthenticationService/Program.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using FictionArchive.Service.Shared;
|
||||
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
||||
|
||||
namespace FictionArchive.Service.AuthenticationService;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
#region Event Bus
|
||||
|
||||
builder.Services.AddRabbitMQ(opt =>
|
||||
{
|
||||
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
|
||||
});
|
||||
|
||||
#endregion
|
||||
|
||||
builder.Services.AddHealthChecks();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.MapHealthChecks("/healthz");
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:23522",
|
||||
"sslPort": 44397
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "http://localhost:5091",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7223;http://localhost:5091",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"RabbitMQ": {
|
||||
"ConnectionString": "amqp://localhost",
|
||||
"ClientIdentifier": "AuthenticationService"
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System.Web;
|
||||
using Amazon.S3;
|
||||
using Amazon.S3.Model;
|
||||
using FictionArchive.Service.FileService.Models;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace FictionArchive.Service.FileService.Controllers
|
||||
{
|
||||
[Route("api/{*path}")]
|
||||
[ApiController]
|
||||
public class S3ProxyController : ControllerBase
|
||||
{
|
||||
private readonly AmazonS3Client _amazonS3Client;
|
||||
private readonly S3Configuration _s3Configuration;
|
||||
|
||||
public S3ProxyController(AmazonS3Client amazonS3Client, IOptions<S3Configuration> s3Configuration)
|
||||
{
|
||||
_amazonS3Client = amazonS3Client;
|
||||
_s3Configuration = s3Configuration.Value;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Get(string path)
|
||||
{
|
||||
var decodedPath = HttpUtility.UrlDecode(path);
|
||||
|
||||
try
|
||||
{
|
||||
var s3Response = await _amazonS3Client.GetObjectAsync(new GetObjectRequest()
|
||||
{
|
||||
BucketName = _s3Configuration.Bucket,
|
||||
Key = decodedPath
|
||||
});
|
||||
|
||||
return new FileStreamResult(s3Response.ResponseStream, s3Response.Headers.ContentType);
|
||||
}
|
||||
catch (AmazonS3Exception e)
|
||||
{
|
||||
if (e.Message == "Key not found")
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
23
FictionArchive.Service.FileService/Dockerfile
Normal file
23
FictionArchive.Service.FileService/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.ImageService/FictionArchive.Service.ImageService.csproj", "FictionArchive.Service.ImageService/"]
|
||||
RUN dotnet restore "FictionArchive.Service.ImageService/FictionArchive.Service.ImageService.csproj"
|
||||
COPY . .
|
||||
WORKDIR "/src/FictionArchive.Service.ImageService"
|
||||
RUN dotnet build "./FictionArchive.Service.ImageService.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "./FictionArchive.Service.ImageService.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.ImageService.dll"]
|
||||
@@ -0,0 +1,30 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\.dockerignore">
|
||||
<Link>.dockerignore</Link>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AWSSDK.S3" Version="4.0.13.1" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="9.0.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Controllers\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,10 @@
|
||||
using FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
namespace FictionArchive.Service.FileService.Models.IntegrationEvents;
|
||||
|
||||
public class FileUploadRequestCreatedEvent : IIntegrationEvent
|
||||
{
|
||||
public Guid RequestId { get; set; }
|
||||
public string FilePath { get; set; }
|
||||
public byte[] FileData { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using FictionArchive.Common.Enums;
|
||||
using FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
namespace FictionArchive.Service.FileService.Models.IntegrationEvents;
|
||||
|
||||
public class FileUploadRequestStatusUpdateEvent : IIntegrationEvent
|
||||
{
|
||||
public Guid RequestId { get; set; }
|
||||
public RequestStatus Status { get; set; }
|
||||
|
||||
#region Success
|
||||
|
||||
public string? FileAccessUrl { get; set; }
|
||||
|
||||
#endregion
|
||||
|
||||
#region Failure
|
||||
|
||||
public string? ErrorMessage { get; set; }
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace FictionArchive.Service.FileService.Models;
|
||||
|
||||
public class ProxyConfiguration
|
||||
{
|
||||
public string BaseUrl { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace FictionArchive.Service.FileService.Models;
|
||||
|
||||
public class S3Configuration
|
||||
{
|
||||
public string Url { get; set; }
|
||||
public string Bucket { get; set; }
|
||||
public string AccessKey { get; set; }
|
||||
public string SecretKey { get; set; }
|
||||
}
|
||||
69
FictionArchive.Service.FileService/Program.cs
Normal file
69
FictionArchive.Service.FileService/Program.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using Amazon.Runtime;
|
||||
using Amazon.S3;
|
||||
using FictionArchive.Common.Extensions;
|
||||
using FictionArchive.Service.FileService.Models;
|
||||
using FictionArchive.Service.FileService.Models.IntegrationEvents;
|
||||
using FictionArchive.Service.FileService.Services.EventHandlers;
|
||||
using FictionArchive.Service.Shared.Extensions;
|
||||
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace FictionArchive.Service.FileService;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.AddLocalAppsettings();
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
builder.Services.AddHealthChecks();
|
||||
|
||||
#region Event Bus
|
||||
|
||||
builder.Services.AddRabbitMQ(opt =>
|
||||
{
|
||||
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
|
||||
})
|
||||
.Subscribe<FileUploadRequestCreatedEvent, FileUploadRequestCreatedEventHandler>();
|
||||
|
||||
#endregion
|
||||
|
||||
builder.Services.Configure<ProxyConfiguration>(builder.Configuration.GetSection("ProxyConfiguration"));
|
||||
|
||||
// Add S3 Client
|
||||
builder.Services.Configure<S3Configuration>(builder.Configuration.GetSection("S3"));
|
||||
builder.Services.AddSingleton<AmazonS3Client>(provider =>
|
||||
{
|
||||
var config = provider.GetRequiredService<IOptions<S3Configuration>>().Value;
|
||||
var s3Config = new AmazonS3Config
|
||||
{
|
||||
ServiceURL = config.Url, // Garage endpoint
|
||||
ForcePathStyle = true, // REQUIRED for Garage
|
||||
AuthenticationRegion = "garage"
|
||||
};
|
||||
return new AmazonS3Client(
|
||||
new BasicAWSCredentials(config.AccessKey, config.SecretKey),
|
||||
s3Config);
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.MapHealthChecks("/healthz");
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:5546",
|
||||
"sslPort": 44373
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "http://localhost:5057",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7247;http://localhost:5057",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using Amazon.S3;
|
||||
using Amazon.S3.Model;
|
||||
using FictionArchive.Common.Enums;
|
||||
using FictionArchive.Service.FileService.Models;
|
||||
using FictionArchive.Service.FileService.Models.IntegrationEvents;
|
||||
using FictionArchive.Service.Shared.Services.EventBus;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace FictionArchive.Service.FileService.Services.EventHandlers;
|
||||
|
||||
public class FileUploadRequestCreatedEventHandler : IIntegrationEventHandler<FileUploadRequestCreatedEvent>
|
||||
{
|
||||
private readonly ILogger<FileUploadRequestCreatedEventHandler> _logger;
|
||||
private readonly AmazonS3Client _amazonS3Client;
|
||||
private readonly IEventBus _eventBus;
|
||||
private readonly S3Configuration _s3Configuration;
|
||||
private readonly ProxyConfiguration _proxyConfiguration;
|
||||
|
||||
public FileUploadRequestCreatedEventHandler(ILogger<FileUploadRequestCreatedEventHandler> logger, AmazonS3Client amazonS3Client, IEventBus eventBus, IOptions<S3Configuration> s3Configuration, IOptions<ProxyConfiguration> proxyConfiguration)
|
||||
{
|
||||
_logger = logger;
|
||||
_amazonS3Client = amazonS3Client;
|
||||
_eventBus = eventBus;
|
||||
_proxyConfiguration = proxyConfiguration.Value;
|
||||
_s3Configuration = s3Configuration.Value;
|
||||
}
|
||||
|
||||
public async Task Handle(FileUploadRequestCreatedEvent @event)
|
||||
{
|
||||
var putObjectRequest = new PutObjectRequest();
|
||||
putObjectRequest.BucketName = _s3Configuration.Bucket;
|
||||
putObjectRequest.Key = @event.FilePath;
|
||||
putObjectRequest.UseChunkEncoding = false; // Needed to avoid an error with Garage
|
||||
|
||||
using MemoryStream memoryStream = new MemoryStream(@event.FileData);
|
||||
putObjectRequest.InputStream = memoryStream;
|
||||
|
||||
var s3Response = await _amazonS3Client.PutObjectAsync(putObjectRequest);
|
||||
if (s3Response.HttpStatusCode != System.Net.HttpStatusCode.OK)
|
||||
{
|
||||
_logger.LogError("An error occurred while uploading file to S3. Response code: {responsecode}", s3Response.HttpStatusCode);
|
||||
await _eventBus.Publish(new FileUploadRequestStatusUpdateEvent()
|
||||
{
|
||||
RequestId = @event.RequestId,
|
||||
Status = RequestStatus.Failed,
|
||||
ErrorMessage = "An error occurred while uploading file to S3."
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await _eventBus.Publish(new FileUploadRequestStatusUpdateEvent()
|
||||
{
|
||||
Status = RequestStatus.Success,
|
||||
RequestId = @event.RequestId,
|
||||
FileAccessUrl = _proxyConfiguration.BaseUrl + "/" + @event.FilePath
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
22
FictionArchive.Service.FileService/appsettings.json
Normal file
22
FictionArchive.Service.FileService/appsettings.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"ProxyConfiguration": {
|
||||
"BaseUrl": "https://localhost:7247/api"
|
||||
},
|
||||
"RabbitMQ": {
|
||||
"ConnectionString": "amqp://localhost",
|
||||
"ClientIdentifier": "FileService"
|
||||
},
|
||||
"S3": {
|
||||
"Url": "https://s3.orfl.xyz",
|
||||
"Bucket": "fictionarchive",
|
||||
"AccessKey": "REPLACE_ME",
|
||||
"SecretKey": "REPLACE_ME"
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
@@ -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.NovelService\\FictionArchive.Service.NovelService.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,165 @@
|
||||
using FictionArchive.Common.Enums;
|
||||
using FictionArchive.Service.FileService.IntegrationEvents;
|
||||
using FictionArchive.Service.NovelService.Models.Configuration;
|
||||
using FictionArchive.Service.NovelService.Models.Enums;
|
||||
using FictionArchive.Service.NovelService.Models.Images;
|
||||
using FictionArchive.Service.NovelService.Models.Localization;
|
||||
using FictionArchive.Service.NovelService.Models.Novels;
|
||||
using FictionArchive.Service.NovelService.Models.SourceAdapters;
|
||||
using FictionArchive.Service.NovelService.Services;
|
||||
using FictionArchive.Service.NovelService.Services.SourceAdapters;
|
||||
using FictionArchive.Service.Shared.Services.EventBus;
|
||||
using FluentAssertions;
|
||||
using HtmlAgilityPack;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using Xunit;
|
||||
|
||||
namespace FictionArchive.Service.NovelService.Tests;
|
||||
|
||||
public class NovelUpdateServiceTests
|
||||
{
|
||||
private static NovelServiceDbContext CreateDbContext()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<NovelServiceDbContext>()
|
||||
.UseInMemoryDatabase($"NovelUpdateServiceTests-{Guid.NewGuid()}")
|
||||
.Options;
|
||||
|
||||
return new NovelServiceDbContext(options, NullLogger<NovelServiceDbContext>.Instance);
|
||||
}
|
||||
|
||||
private static NovelCreateResult CreateNovelWithSingleChapter(NovelServiceDbContext dbContext, Source source)
|
||||
{
|
||||
var chapter = new Chapter
|
||||
{
|
||||
Order = 1,
|
||||
Revision = 1,
|
||||
Url = "http://demo/chapter-1",
|
||||
Name = LocalizationKey.CreateFromText("Chapter 1", Language.En),
|
||||
Body = new LocalizationKey { Texts = new List<LocalizationText>() },
|
||||
Images = new List<Image>()
|
||||
};
|
||||
|
||||
var novel = new Novel
|
||||
{
|
||||
Url = "http://demo/novel",
|
||||
ExternalId = "demo-1",
|
||||
Author = new Person { Name = LocalizationKey.CreateFromText("Author", Language.En) },
|
||||
RawLanguage = Language.En,
|
||||
RawStatus = NovelStatus.InProgress,
|
||||
Source = source,
|
||||
Name = LocalizationKey.CreateFromText("Demo Novel", Language.En),
|
||||
Description = LocalizationKey.CreateFromText("Description", Language.En),
|
||||
Chapters = new List<Chapter> { chapter },
|
||||
Tags = new List<NovelTag>()
|
||||
};
|
||||
|
||||
dbContext.Novels.Add(novel);
|
||||
dbContext.SaveChanges();
|
||||
|
||||
return new NovelCreateResult(novel, chapter);
|
||||
}
|
||||
|
||||
private static NovelUpdateService CreateService(
|
||||
NovelServiceDbContext dbContext,
|
||||
ISourceAdapter adapter,
|
||||
IEventBus eventBus,
|
||||
string pendingImageUrl = "https://pending/placeholder.jpg")
|
||||
{
|
||||
var options = Options.Create(new NovelUpdateServiceConfiguration
|
||||
{
|
||||
PendingImageUrl = pendingImageUrl
|
||||
});
|
||||
|
||||
return new NovelUpdateService(dbContext, NullLogger<NovelUpdateService>.Instance, new[] { adapter }, eventBus, options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PullChapterContents_rewrites_images_and_publishes_requests()
|
||||
{
|
||||
using var dbContext = CreateDbContext();
|
||||
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
|
||||
var (novel, 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 image1 = new ImageData { Url = "http://img/x1.jpg", Data = new byte[] { 1, 2, 3 } };
|
||||
var image2 = new ImageData { Url = "http://img/x2.jpg", Data = new byte[] { 4, 5, 6 } };
|
||||
|
||||
var adapter = Substitute.For<ISourceAdapter>();
|
||||
adapter.SourceDescriptor.Returns(new SourceDescriptor { Key = "demo", Name = "Demo", Url = "http://demo" });
|
||||
adapter.GetRawChapter(chapter.Url).Returns(Task.FromResult(new ChapterFetchResult
|
||||
{
|
||||
Text = rawHtml,
|
||||
ImageData = new List<ImageData> { image1, image2 }
|
||||
}));
|
||||
|
||||
var publishedEvents = new List<FileUploadRequestCreatedEvent>();
|
||||
var eventBus = Substitute.For<IEventBus>();
|
||||
eventBus.Publish(Arg.Do<FileUploadRequestCreatedEvent>(publishedEvents.Add)).Returns(Task.CompletedTask);
|
||||
eventBus.Publish(Arg.Any<object>(), Arg.Any<string>()).Returns(Task.CompletedTask);
|
||||
|
||||
var pendingImageUrl = "https://pending/placeholder.jpg";
|
||||
var service = CreateService(dbContext, adapter, eventBus, pendingImageUrl);
|
||||
|
||||
var updatedChapter = await service.PullChapterContents(novel.Id, chapter.Order);
|
||||
|
||||
updatedChapter.Images.Should().HaveCount(2);
|
||||
updatedChapter.Images.Select(i => i.OriginalPath).Should().BeEquivalentTo(new[] { image1.Url, image2.Url });
|
||||
updatedChapter.Images.All(i => i.Id != Guid.Empty).Should().BeTrue();
|
||||
|
||||
var storedHtml = updatedChapter.Body.Texts.Single().Text;
|
||||
var doc = new HtmlDocument();
|
||||
doc.LoadHtml(storedHtml);
|
||||
var imgNodes = doc.DocumentNode.SelectNodes("//img");
|
||||
imgNodes.Should().NotBeNull();
|
||||
imgNodes!.Count.Should().Be(2);
|
||||
imgNodes.Should().OnlyContain(node => node.GetAttributeValue("src", string.Empty) == pendingImageUrl);
|
||||
imgNodes.Select(node => node.GetAttributeValue("alt", string.Empty))
|
||||
.Should()
|
||||
.BeEquivalentTo(updatedChapter.Images.Select(img => img.Id.ToString()));
|
||||
|
||||
publishedEvents.Should().HaveCount(2);
|
||||
publishedEvents.Select(e => e.RequestId).Should().BeEquivalentTo(updatedChapter.Images.Select(i => i.Id));
|
||||
publishedEvents.Select(e => e.FileData).Should().BeEquivalentTo(new[] { image1.Data, image2.Data });
|
||||
publishedEvents.Should().OnlyContain(e => e.FilePath.StartsWith($"{novel.Id}/Images/Chapter-{updatedChapter.Id}/"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PullChapterContents_adds_alt_when_missing()
|
||||
{
|
||||
using var dbContext = CreateDbContext();
|
||||
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
|
||||
var (novel, chapter) = CreateNovelWithSingleChapter(dbContext, source);
|
||||
|
||||
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 adapter = Substitute.For<ISourceAdapter>();
|
||||
adapter.SourceDescriptor.Returns(new SourceDescriptor { Key = "demo", Name = "Demo", Url = "http://demo" });
|
||||
adapter.GetRawChapter(chapter.Url).Returns(Task.FromResult(new ChapterFetchResult
|
||||
{
|
||||
Text = rawHtml,
|
||||
ImageData = new List<ImageData> { image }
|
||||
}));
|
||||
|
||||
var eventBus = Substitute.For<IEventBus>();
|
||||
eventBus.Publish(Arg.Any<FileUploadRequestCreatedEvent>()).Returns(Task.CompletedTask);
|
||||
eventBus.Publish(Arg.Any<object>(), Arg.Any<string>()).Returns(Task.CompletedTask);
|
||||
|
||||
var service = CreateService(dbContext, adapter, eventBus);
|
||||
|
||||
var updatedChapter = await service.PullChapterContents(novel.Id, chapter.Order);
|
||||
|
||||
var storedHtml = updatedChapter.Body.Texts.Single().Text;
|
||||
var doc = new HtmlDocument();
|
||||
doc.LoadHtml(storedHtml);
|
||||
var imgNode = doc.DocumentNode.SelectSingleNode("//img");
|
||||
imgNode.Should().NotBeNull();
|
||||
imgNode!.GetAttributeValue("alt", string.Empty).Should().Be(updatedChapter.Images.Single().Id.ToString());
|
||||
imgNode.GetAttributeValue("src", string.Empty).Should().Be("https://pending/placeholder.jpg");
|
||||
}
|
||||
|
||||
private record NovelCreateResult(Novel Novel, Chapter Chapter);
|
||||
}
|
||||
@@ -8,6 +8,8 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="HotChocolate.AspNetCore.CommandLine" Version="15.1.11" />
|
||||
<PackageReference Include="HtmlAgilityPack" Version="1.12.4" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
|
||||
540
FictionArchive.Service.NovelService/Migrations/20251123203953_AddImages.Designer.cs
generated
Normal file
540
FictionArchive.Service.NovelService/Migrations/20251123203953_AddImages.Designer.cs
generated
Normal file
@@ -0,0 +1,540 @@
|
||||
// <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("20251123203953_AddImages")]
|
||||
partial class AddImages
|
||||
{
|
||||
/// <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?>("NovelId")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<long>("Order")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<long>("Revision")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("Url")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("BodyId");
|
||||
|
||||
b.HasIndex("NameId");
|
||||
|
||||
b.HasIndex("NovelId");
|
||||
|
||||
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.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("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.Novel", null)
|
||||
.WithMany("Chapters")
|
||||
.HasForeignKey("NovelId");
|
||||
|
||||
b.Navigation("Body");
|
||||
|
||||
b.Navigation("Name");
|
||||
});
|
||||
|
||||
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("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("Chapters");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using NodaTime;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace FictionArchive.Service.NovelService.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddImages : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "CoverImageId",
|
||||
table: "Novels",
|
||||
type: "uuid",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Images",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
OriginalPath = table.Column<string>(type: "text", nullable: false),
|
||||
NewPath = table.Column<string>(type: "text", nullable: true),
|
||||
ChapterId = table.Column<long>(type: "bigint", 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_Images", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_Images_Chapter_ChapterId",
|
||||
column: x => x.ChapterId,
|
||||
principalTable: "Chapter",
|
||||
principalColumn: "Id");
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Novels_CoverImageId",
|
||||
table: "Novels",
|
||||
column: "CoverImageId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Images_ChapterId",
|
||||
table: "Images",
|
||||
column: "ChapterId");
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_Novels_Images_CoverImageId",
|
||||
table: "Novels",
|
||||
column: "CoverImageId",
|
||||
principalTable: "Images",
|
||||
principalColumn: "Id");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_Novels_Images_CoverImageId",
|
||||
table: "Novels");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Images");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_Novels_CoverImageId",
|
||||
table: "Novels");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CoverImageId",
|
||||
table: "Novels");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,35 @@ namespace FictionArchive.Service.NovelService.Migrations
|
||||
|
||||
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")
|
||||
@@ -158,6 +187,9 @@ namespace FictionArchive.Service.NovelService.Migrations
|
||||
b.Property<long>("AuthorId")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<Guid?>("CoverImageId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Instant>("CreatedTime")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
@@ -194,6 +226,8 @@ namespace FictionArchive.Service.NovelService.Migrations
|
||||
|
||||
b.HasIndex("AuthorId");
|
||||
|
||||
b.HasIndex("CoverImageId");
|
||||
|
||||
b.HasIndex("DescriptionId");
|
||||
|
||||
b.HasIndex("NameId");
|
||||
@@ -335,6 +369,15 @@ namespace FictionArchive.Service.NovelService.Migrations
|
||||
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")
|
||||
@@ -398,6 +441,10 @@ namespace FictionArchive.Service.NovelService.Migrations
|
||||
.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")
|
||||
@@ -418,6 +465,8 @@ namespace FictionArchive.Service.NovelService.Migrations
|
||||
|
||||
b.Navigation("Author");
|
||||
|
||||
b.Navigation("CoverImage");
|
||||
|
||||
b.Navigation("Description");
|
||||
|
||||
b.Navigation("Name");
|
||||
@@ -473,6 +522,11 @@ namespace FictionArchive.Service.NovelService.Migrations
|
||||
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("Chapters");
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace FictionArchive.Service.NovelService.Models.Configuration;
|
||||
|
||||
public class NovelUpdateServiceConfiguration
|
||||
{
|
||||
public string PendingImageUrl { get; set; }
|
||||
}
|
||||
13
FictionArchive.Service.NovelService/Models/Images/Image.cs
Normal file
13
FictionArchive.Service.NovelService/Models/Images/Image.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using FictionArchive.Service.NovelService.Models.Novels;
|
||||
using FictionArchive.Service.Shared.Models;
|
||||
|
||||
namespace FictionArchive.Service.NovelService.Models.Images;
|
||||
|
||||
public class Image : BaseEntity<Guid>
|
||||
{
|
||||
public string OriginalPath { get; set; }
|
||||
public string? NewPath { get; set; }
|
||||
|
||||
// Chapter link. Even if an image appears in another chapter, we should rehost it separately.
|
||||
public Chapter? Chapter { get; set; }
|
||||
}
|
||||
@@ -2,7 +2,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
||||
|
||||
public class ChapterPullRequestedEvent : IntegrationEvent
|
||||
public class ChapterPullRequestedEvent : IIntegrationEvent
|
||||
{
|
||||
public uint NovelId { get; set; }
|
||||
public uint ChapterNumber { get; set; }
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
using FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
namespace FictionArchive.Service.FileService.IntegrationEvents;
|
||||
|
||||
public class FileUploadRequestCreatedEvent : IIntegrationEvent
|
||||
{
|
||||
public Guid RequestId { get; set; }
|
||||
public string FilePath { get; set; }
|
||||
public byte[] FileData { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using FictionArchive.Common.Enums;
|
||||
using FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
||||
|
||||
public class FileUploadRequestStatusUpdateEvent : IIntegrationEvent
|
||||
{
|
||||
public Guid RequestId { get; set; }
|
||||
public RequestStatus Status { get; set; }
|
||||
|
||||
#region Success
|
||||
|
||||
public string? FileAccessUrl { get; set; }
|
||||
|
||||
#endregion
|
||||
|
||||
#region Failure
|
||||
|
||||
public string? ErrorMessage { get; set; }
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -2,7 +2,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
||||
|
||||
public class NovelUpdateRequestedEvent : IntegrationEvent
|
||||
public class NovelUpdateRequestedEvent : IIntegrationEvent
|
||||
{
|
||||
public string NovelUrl { get; set; }
|
||||
}
|
||||
@@ -3,7 +3,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
||||
|
||||
public class TranslationRequestCompletedEvent : IntegrationEvent
|
||||
public class TranslationRequestCompletedEvent : IIntegrationEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// Maps this event back to a triggering request.
|
||||
|
||||
@@ -3,7 +3,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
||||
|
||||
public class TranslationRequestCreatedEvent : IntegrationEvent
|
||||
public class TranslationRequestCreatedEvent : IIntegrationEvent
|
||||
{
|
||||
public Guid TranslationRequestId { get; set; }
|
||||
public Language From { get; set; }
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using FictionArchive.Service.NovelService.Models.Images;
|
||||
using FictionArchive.Service.NovelService.Models.Localization;
|
||||
using FictionArchive.Service.Shared.Models;
|
||||
|
||||
@@ -11,4 +12,7 @@ public class Chapter : BaseEntity<uint>
|
||||
|
||||
public LocalizationKey Name { get; set; }
|
||||
public LocalizationKey Body { get; set; }
|
||||
|
||||
// Images appearing in this chapter.
|
||||
public List<Image> Images { get; set; }
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using FictionArchive.Common.Enums;
|
||||
using FictionArchive.Service.NovelService.Models.Images;
|
||||
using FictionArchive.Service.NovelService.Models.Localization;
|
||||
using FictionArchive.Service.Shared.Models;
|
||||
using NovelStatus = FictionArchive.Service.NovelService.Models.Enums.NovelStatus;
|
||||
@@ -22,4 +23,5 @@ public class Novel : BaseEntity<uint>
|
||||
|
||||
public List<Chapter> Chapters { get; set; }
|
||||
public List<NovelTag> Tags { get; set; }
|
||||
public Image? CoverImage { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace FictionArchive.Service.NovelService.Models.SourceAdapters;
|
||||
|
||||
public class ChapterFetchResult
|
||||
{
|
||||
public string Text { get; set; }
|
||||
public List<ImageData> ImageData { get; set; }
|
||||
}
|
||||
@@ -6,5 +6,5 @@ public class ChapterMetadata
|
||||
public uint Order { get; set; }
|
||||
public string? Url { get; set; }
|
||||
public string Name { get; set; }
|
||||
|
||||
public List<string> ImageUrls { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace FictionArchive.Service.NovelService.Models.SourceAdapters;
|
||||
|
||||
public class ImageData
|
||||
{
|
||||
public string Url { get; set; }
|
||||
public byte[] Data { get; set; }
|
||||
}
|
||||
@@ -11,6 +11,7 @@ public class NovelMetadata
|
||||
public string AuthorUrl { get; set; }
|
||||
public string Url { get; set; }
|
||||
public string ExternalId { get; set; }
|
||||
public ImageData? CoverImage { get; set; }
|
||||
|
||||
public Language RawLanguage { get; set; }
|
||||
public NovelStatus RawStatus { get; set; }
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using FictionArchive.Common.Extensions;
|
||||
using FictionArchive.Service.NovelService.GraphQL;
|
||||
using FictionArchive.Service.NovelService.Models.Configuration;
|
||||
using FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
||||
using FictionArchive.Service.NovelService.Services;
|
||||
using FictionArchive.Service.NovelService.Services.EventHandlers;
|
||||
@@ -16,6 +18,7 @@ public class Program
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.AddLocalAppsettings();
|
||||
|
||||
builder.Services.AddMemoryCache();
|
||||
|
||||
@@ -27,7 +30,8 @@ public class Program
|
||||
})
|
||||
.Subscribe<TranslationRequestCompletedEvent, TranslationRequestCompletedEventHandler>()
|
||||
.Subscribe<NovelUpdateRequestedEvent, NovelUpdateRequestedEventHandler>()
|
||||
.Subscribe<ChapterPullRequestedEvent, ChapterPullRequestedEventHandler>();
|
||||
.Subscribe<ChapterPullRequestedEvent, ChapterPullRequestedEventHandler>()
|
||||
.Subscribe<FileUploadRequestStatusUpdateEvent, FileUploadRequestStatusUpdateEventHandler>();
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -56,6 +60,7 @@ public class Program
|
||||
})
|
||||
.AddHttpMessageHandler<NovelpiaAuthMessageHandler>();
|
||||
|
||||
builder.Services.Configure<NovelUpdateServiceConfiguration>(builder.Configuration.GetSection("UpdateService"));
|
||||
builder.Services.AddTransient<NovelUpdateService>();
|
||||
|
||||
#endregion
|
||||
@@ -77,6 +82,6 @@ public class Program
|
||||
|
||||
app.MapGraphQL();
|
||||
|
||||
app.Run();
|
||||
app.RunWithGraphQLCommands(args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using FictionArchive.Common.Enums;
|
||||
using FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
||||
using FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
namespace FictionArchive.Service.NovelService.Services.EventHandlers;
|
||||
|
||||
public class FileUploadRequestStatusUpdateEventHandler : IIntegrationEventHandler<FileUploadRequestStatusUpdateEvent>
|
||||
{
|
||||
private readonly ILogger<FileUploadRequestStatusUpdateEventHandler> _logger;
|
||||
private readonly NovelServiceDbContext _context;
|
||||
private readonly NovelUpdateService _novelUpdateService;
|
||||
|
||||
public FileUploadRequestStatusUpdateEventHandler(ILogger<FileUploadRequestStatusUpdateEventHandler> logger, NovelServiceDbContext context, NovelUpdateService novelUpdateService)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_novelUpdateService = novelUpdateService;
|
||||
}
|
||||
|
||||
public async Task Handle(FileUploadRequestStatusUpdateEvent @event)
|
||||
{
|
||||
var image = await _context.Images.FindAsync(@event.RequestId);
|
||||
if (image == null)
|
||||
{
|
||||
// Not a request we care about.
|
||||
return;
|
||||
}
|
||||
if (@event.Status == RequestStatus.Failed)
|
||||
{
|
||||
_logger.LogError("Image upload failed for image with id {imageId}", image.Id);
|
||||
return;
|
||||
}
|
||||
else if (@event.Status == RequestStatus.Success)
|
||||
{
|
||||
_logger.LogInformation("Image upload succeeded for image with id {imageId}", image.Id);
|
||||
await _novelUpdateService.UpdateImage(image.Id, @event.FileAccessUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using FictionArchive.Service.NovelService.Models.Images;
|
||||
using FictionArchive.Service.NovelService.Models.Localization;
|
||||
using FictionArchive.Service.NovelService.Models.Novels;
|
||||
using FictionArchive.Service.Shared.Services.Database;
|
||||
@@ -14,4 +15,5 @@ public class NovelServiceDbContext(DbContextOptions options, ILogger<NovelServic
|
||||
public DbSet<NovelTag> Tags { get; set; }
|
||||
public DbSet<LocalizationKey> LocalizationKeys { get; set; }
|
||||
public DbSet<LocalizationRequest> LocalizationRequests { get; set; }
|
||||
public DbSet<Image> Images { get; set; }
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
using FictionArchive.Service.FileService.IntegrationEvents;
|
||||
using FictionArchive.Service.NovelService.Models.Configuration;
|
||||
using FictionArchive.Service.NovelService.Models.Enums;
|
||||
using FictionArchive.Service.NovelService.Models.Images;
|
||||
using FictionArchive.Service.NovelService.Models.Localization;
|
||||
using FictionArchive.Service.NovelService.Models.Novels;
|
||||
using FictionArchive.Service.NovelService.Models.SourceAdapters;
|
||||
using FictionArchive.Service.NovelService.Services.SourceAdapters;
|
||||
using FictionArchive.Service.Shared.Services.EventBus;
|
||||
using HtmlAgilityPack;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace FictionArchive.Service.NovelService.Services;
|
||||
|
||||
@@ -12,12 +18,16 @@ public class NovelUpdateService
|
||||
private readonly NovelServiceDbContext _dbContext;
|
||||
private readonly ILogger<NovelUpdateService> _logger;
|
||||
private readonly IEnumerable<ISourceAdapter> _sourceAdapters;
|
||||
private readonly IEventBus _eventBus;
|
||||
private readonly NovelUpdateServiceConfiguration _novelUpdateServiceConfiguration;
|
||||
|
||||
public NovelUpdateService(NovelServiceDbContext dbContext, ILogger<NovelUpdateService> logger, IEnumerable<ISourceAdapter> sourceAdapters)
|
||||
public NovelUpdateService(NovelServiceDbContext dbContext, ILogger<NovelUpdateService> logger, IEnumerable<ISourceAdapter> sourceAdapters, IEventBus eventBus, IOptions<NovelUpdateServiceConfiguration> novelUpdateServiceConfiguration)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_logger = logger;
|
||||
_sourceAdapters = sourceAdapters;
|
||||
_eventBus = eventBus;
|
||||
_novelUpdateServiceConfiguration = novelUpdateServiceConfiguration.Value;
|
||||
}
|
||||
|
||||
public async Task<Novel> ImportNovel(string novelUrl)
|
||||
@@ -59,6 +69,10 @@ public class NovelUpdateService
|
||||
RawLanguage = metadata.RawLanguage,
|
||||
Url = metadata.Url,
|
||||
ExternalId = metadata.ExternalId,
|
||||
CoverImage = metadata.CoverImage != null ? new Image()
|
||||
{
|
||||
OriginalPath = metadata.CoverImage.Url,
|
||||
} : null,
|
||||
Chapters = metadata.Chapters.Select(chapter =>
|
||||
{
|
||||
return new Chapter()
|
||||
@@ -86,6 +100,17 @@ public class NovelUpdateService
|
||||
});
|
||||
await _dbContext.SaveChangesAsync();
|
||||
|
||||
// Signal request for cover image if present
|
||||
if (addedNovel.Entity.CoverImage != null)
|
||||
{
|
||||
await _eventBus.Publish(new FileUploadRequestCreatedEvent()
|
||||
{
|
||||
RequestId = addedNovel.Entity.CoverImage.Id,
|
||||
FileData = metadata.CoverImage.Data,
|
||||
FilePath = $"Novels/{addedNovel.Entity.Id}/Images/cover.jpg"
|
||||
});
|
||||
}
|
||||
|
||||
return addedNovel.Entity;
|
||||
}
|
||||
|
||||
@@ -95,17 +120,85 @@ public class NovelUpdateService
|
||||
.Include(novel => novel.Chapters)
|
||||
.ThenInclude(chapter => chapter.Body)
|
||||
.ThenInclude(body => body.Texts)
|
||||
.Include(novel => novel.Source)
|
||||
.Include(novel => novel.Source).Include(novel => novel.Chapters).ThenInclude(chapter => chapter.Images)
|
||||
.FirstOrDefaultAsync();
|
||||
var chapter = novel.Chapters.Where(chapter => chapter.Order == chapterNumber).FirstOrDefault();
|
||||
var adapter = _sourceAdapters.FirstOrDefault(adapter => adapter.SourceDescriptor.Key == novel.Source.Key);
|
||||
var rawChapter = await adapter.GetRawChapter(chapter.Url);
|
||||
chapter.Body.Texts.Add(new LocalizationText()
|
||||
var localizationText = new LocalizationText()
|
||||
{
|
||||
Text = rawChapter,
|
||||
Text = rawChapter.Text,
|
||||
Language = novel.RawLanguage
|
||||
});
|
||||
};
|
||||
chapter.Body.Texts.Add(localizationText);
|
||||
chapter.Images = rawChapter.ImageData.Select(img => new Image()
|
||||
{
|
||||
OriginalPath = img.Url
|
||||
}).ToList();
|
||||
await _dbContext.SaveChangesAsync();
|
||||
|
||||
// Images are saved and have ids, update the chapter body to replace image tags
|
||||
var chapterDoc = new HtmlDocument();
|
||||
chapterDoc.LoadHtml(rawChapter.Text);
|
||||
foreach (var image in chapter.Images)
|
||||
{
|
||||
var match = chapterDoc.DocumentNode.SelectSingleNode(@$"//img[@src='{image.OriginalPath}']");
|
||||
if (match != null)
|
||||
{
|
||||
match.Attributes["src"].Value = _novelUpdateServiceConfiguration.PendingImageUrl;
|
||||
if (match.Attributes.Contains("alt"))
|
||||
{
|
||||
match.Attributes["alt"].Value = image.Id.ToString();
|
||||
}
|
||||
else
|
||||
{
|
||||
match.Attributes.Add("alt", image.Id.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
localizationText.Text = chapterDoc.DocumentNode.OuterHtml;
|
||||
await _dbContext.SaveChangesAsync();
|
||||
|
||||
// Body was updated, raise image request
|
||||
int imgCount = 0;
|
||||
foreach (var image in chapter.Images)
|
||||
{
|
||||
var data = rawChapter.ImageData.FirstOrDefault(img => img.Url == image.OriginalPath);
|
||||
await _eventBus.Publish(new FileUploadRequestCreatedEvent()
|
||||
{
|
||||
FileData = data.Data,
|
||||
FilePath = $"{novel.Id}/Images/Chapter-{chapter.Id}/{imgCount++}.jpg",
|
||||
RequestId = image.Id
|
||||
});
|
||||
}
|
||||
|
||||
return chapter;
|
||||
}
|
||||
|
||||
public async Task UpdateImage(Guid imageId, string newUrl)
|
||||
{
|
||||
var image = await _dbContext.Images
|
||||
.Include(img => img.Chapter)
|
||||
.ThenInclude(chapter => chapter.Body)
|
||||
.ThenInclude(body => body.Texts)
|
||||
.FirstOrDefaultAsync(image => image.Id == imageId);
|
||||
image.NewPath = newUrl;
|
||||
|
||||
// If this is an image from a chapter, let's update the chapter body(s)
|
||||
if (image.Chapter != null)
|
||||
{
|
||||
foreach (var bodyText in image.Chapter.Body.Texts)
|
||||
{
|
||||
var chapterDoc = new HtmlDocument();
|
||||
chapterDoc.LoadHtml(bodyText.Text);
|
||||
var match = chapterDoc.DocumentNode.SelectSingleNode(@$"//img[@alt='{image.Id}']");
|
||||
if (match != null)
|
||||
{
|
||||
match.Attributes["src"].Value = newUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await _dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
@@ -8,5 +8,5 @@ public interface ISourceAdapter
|
||||
public SourceDescriptor SourceDescriptor { get; }
|
||||
public Task<bool> CanProcessNovel(string url);
|
||||
public Task<NovelMetadata> GetMetadata(string novelUrl);
|
||||
public Task<string> GetRawChapter(string chapterUrl);
|
||||
public Task<ChapterFetchResult> GetRawChapter(string chapterUrl);
|
||||
}
|
||||
@@ -81,6 +81,21 @@ public class NovelpiaAdapter : ISourceAdapter
|
||||
novel.AuthorName = authorMatch.Groups[2].Value;
|
||||
novel.AuthorUrl = authorMatch.Groups[2].Value;
|
||||
|
||||
// Cover image URL
|
||||
var coverMatch = Regex.Match(novelData, @"href=""(//images\.novelpia\.com/imagebox/cover/.+?\.file)""");
|
||||
string coverImageUrl = coverMatch.Groups[1].Value;
|
||||
if (string.IsNullOrEmpty(coverImageUrl))
|
||||
{
|
||||
coverMatch = Regex.Match(novelData, @"src=""(//images\.novelpia\.com/imagebox/cover/.+?\.file)""");
|
||||
coverImageUrl = coverMatch.Groups[1].Value;
|
||||
}
|
||||
|
||||
novel.CoverImage = new ImageData()
|
||||
{
|
||||
Url = coverImageUrl,
|
||||
Data = await GetImageData(coverImageUrl),
|
||||
};
|
||||
|
||||
// Some badge info
|
||||
var badgeSet = Regex.Match(novelData, @"(?s)<p\s+class=""in-badge"">(.*?)<\/p>");
|
||||
var badgeMatches = Regex.Matches(badgeSet.Groups[1].Value, @"<span[^>]*>(.*?)<\/span>");
|
||||
@@ -160,7 +175,7 @@ public class NovelpiaAdapter : ISourceAdapter
|
||||
return novel;
|
||||
}
|
||||
|
||||
public async Task<string> GetRawChapter(string chapterUrl)
|
||||
public async Task<ChapterFetchResult> GetRawChapter(string chapterUrl)
|
||||
{
|
||||
var chapterId = uint.Parse(Regex.Match(chapterUrl, ChapterIdRegex).Groups[1].Value);
|
||||
var endpoint = ChapterDownloadEndpoint + chapterId;
|
||||
@@ -172,6 +187,11 @@ public class NovelpiaAdapter : ISourceAdapter
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
var fetchResult = new ChapterFetchResult()
|
||||
{
|
||||
ImageData = new List<ImageData>()
|
||||
};
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
using var doc = JsonDocument.Parse(responseContent);
|
||||
JsonElement root = doc.RootElement;
|
||||
@@ -182,10 +202,20 @@ public class NovelpiaAdapter : ISourceAdapter
|
||||
foreach (JsonElement item in sArray.EnumerateArray())
|
||||
{
|
||||
string text = item.GetProperty("text").GetString();
|
||||
var imageMatch = Regex.Match(text, @"<img.+?src=\""(.+?)\"".+?>");
|
||||
if (text.Contains("cover-wrapper"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (imageMatch.Success)
|
||||
{
|
||||
var url = imageMatch.Groups[1].Value;
|
||||
fetchResult.ImageData.Add(new ImageData()
|
||||
{
|
||||
Url = url,
|
||||
Data = await GetImageData(url)
|
||||
});
|
||||
}
|
||||
if (text.Contains("opacity: 0"))
|
||||
{
|
||||
continue;
|
||||
@@ -193,8 +223,24 @@ public class NovelpiaAdapter : ISourceAdapter
|
||||
|
||||
builder.Append(WebUtility.HtmlDecode(text));
|
||||
}
|
||||
fetchResult.Text = builder.ToString();
|
||||
|
||||
return builder.ToString();
|
||||
return fetchResult;
|
||||
}
|
||||
|
||||
private async Task<byte[]> GetImageData(string url)
|
||||
{
|
||||
if (!url.StartsWith("http"))
|
||||
{
|
||||
url = "https:" + url;
|
||||
}
|
||||
|
||||
var image = await _httpClient.GetAsync(url);
|
||||
if (!image.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogError("Attempting to fetch image with url {imgUrl} returned status code {code}.", url, image.StatusCode);
|
||||
throw new Exception();
|
||||
}
|
||||
return await image.Content.ReadAsByteArrayAsync();
|
||||
}
|
||||
}
|
||||
@@ -52,10 +52,15 @@ public class NovelpiaAuthMessageHandler : DelegatingHandler
|
||||
var response = await _httpClient.SendAsync(loginMessage);
|
||||
using (var streamReader = new StreamReader(response.Content.ReadAsStream()))
|
||||
{
|
||||
if (streamReader.ReadToEnd().Contains(LoginSuccessMessage))
|
||||
var message = await streamReader.ReadToEndAsync();
|
||||
if (message.Contains(LoginSuccessMessage))
|
||||
{
|
||||
_cache.Set(CacheKey, loginKey);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("An error occured while retrieving the login key. Message: " + message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
"Username": "REPLACE_ME",
|
||||
"Password": "REPLACE_ME"
|
||||
},
|
||||
"UpdateService": {
|
||||
"PendingImageUrl": "https://localhost:7247/api/pendingupload.png"
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Host=localhost;Database=FictionArchive_NovelService;Username=postgres;password=postgres"
|
||||
},
|
||||
|
||||
6
FictionArchive.Service.NovelService/subgraph-config.json
Normal file
6
FictionArchive.Service.NovelService/subgraph-config.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"subgraph": "Novels",
|
||||
"http": {
|
||||
"baseAddress": "http://localhost:5101/graphql"
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,6 @@ public class Program
|
||||
|
||||
app.MapGraphQL();
|
||||
|
||||
app.Run();
|
||||
app.RunWithGraphQLCommands(args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"subgraph": "Scheduler",
|
||||
"http": {
|
||||
"baseAddress": "http://localhost:5213/graphql"
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,13 @@ public static class GraphQLExtensions
|
||||
return services.AddGraphQLServer()
|
||||
.AddQueryType<TQuery>()
|
||||
.AddMutationType<TMutation>()
|
||||
.AddDiagnosticEventListener<ErrorEventListener>()
|
||||
.ApplySaneDefaults();
|
||||
|
||||
}
|
||||
|
||||
public static IRequestExecutorBuilder ApplySaneDefaults(this IRequestExecutorBuilder builder)
|
||||
{
|
||||
return builder.AddDiagnosticEventListener<ErrorEventListener>()
|
||||
.AddErrorFilter<LoggingErrorFilter>()
|
||||
.AddType<UnsignedIntType>()
|
||||
.AddType<InstantType>()
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="GraphQL.Server.Ui.GraphiQL" Version="8.3.3" />
|
||||
<PackageReference Include="HotChocolate.AspNetCore" Version="15.1.11" />
|
||||
<PackageReference Include="HotChocolate.AspNetCore.CommandLine" Version="15.1.11" />
|
||||
<PackageReference Include="HotChocolate.Data.EntityFramework" Version="15.1.11" />
|
||||
<PackageReference Include="HotChocolate.Types.Scalars" Version="15.1.11" />
|
||||
<PackageReference Include="HotChocolate.Types.NodaTime" Version="15.1.11" />
|
||||
|
||||
@@ -16,7 +16,7 @@ public class EventBusBuilder<TEventBus> where TEventBus : class, IEventBus
|
||||
_services.AddSingleton<SubscriptionManager>(_subscriptionManager);
|
||||
}
|
||||
|
||||
public EventBusBuilder<TEventBus> Subscribe<TEvent, TEventHandler>() where TEvent : IntegrationEvent where TEventHandler : class, IIntegrationEventHandler<TEvent>
|
||||
public EventBusBuilder<TEventBus> Subscribe<TEvent, TEventHandler>() where TEvent : IIntegrationEvent where TEventHandler : class, IIntegrationEventHandler<TEvent>
|
||||
{
|
||||
_services.AddKeyedTransient<IIntegrationEventHandler, TEventHandler>(typeof(TEvent).Name);
|
||||
_subscriptionManager.RegisterSubscription<TEvent>();
|
||||
|
||||
@@ -2,6 +2,6 @@ namespace FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
public interface IEventBus
|
||||
{
|
||||
Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IntegrationEvent;
|
||||
Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IIntegrationEvent;
|
||||
Task Publish(object integrationEvent, string eventType);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using NodaTime;
|
||||
|
||||
namespace FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
public interface IIntegrationEvent
|
||||
{
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
namespace FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
public interface IIntegrationEventHandler<in TEvent> : IIntegrationEventHandler where TEvent : IntegrationEvent
|
||||
public interface IIntegrationEventHandler<in TEvent> : IIntegrationEventHandler where TEvent : IIntegrationEvent
|
||||
{
|
||||
Task Handle(TEvent @event);
|
||||
Task IIntegrationEventHandler.Handle(IntegrationEvent @event) => Handle((TEvent)@event);
|
||||
Task IIntegrationEventHandler.Handle(IIntegrationEvent @event) => Handle((TEvent)@event);
|
||||
}
|
||||
|
||||
public interface IIntegrationEventHandler
|
||||
{
|
||||
Task Handle(IntegrationEvent @event);
|
||||
Task Handle(IIntegrationEvent @event);
|
||||
}
|
||||
@@ -22,6 +22,8 @@ public class RabbitMQEventBus : IEventBus, IHostedService
|
||||
private readonly JsonSerializerSettings _jsonSerializerSettings;
|
||||
|
||||
private const string ExchangeName = "fiction-archive-event-bus";
|
||||
private const string CreatedAtHeader = "X-Created-At";
|
||||
private const string EventIdHeader = "X-Event-Id";
|
||||
|
||||
public RabbitMQEventBus(IServiceScopeFactory serviceScopeFactory, RabbitMQConnectionProvider connectionProvider, IOptions<RabbitMQOptions> options, SubscriptionManager subscriptionManager, ILogger<RabbitMQEventBus> logger)
|
||||
{
|
||||
@@ -33,14 +35,10 @@ public class RabbitMQEventBus : IEventBus, IHostedService
|
||||
_jsonSerializerSettings = new JsonSerializerSettings().ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
|
||||
}
|
||||
|
||||
public async Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IntegrationEvent
|
||||
public async Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IIntegrationEvent
|
||||
{
|
||||
var routingKey = typeof(TEvent).Name;
|
||||
|
||||
// Set integration event values
|
||||
integrationEvent.CreatedAt = Instant.FromDateTimeUtc(DateTime.UtcNow);
|
||||
integrationEvent.EventId = Guid.NewGuid();
|
||||
|
||||
await Publish(integrationEvent, routingKey);
|
||||
}
|
||||
|
||||
@@ -48,7 +46,16 @@ public class RabbitMQEventBus : IEventBus, IHostedService
|
||||
{
|
||||
var channel = await _connectionProvider.GetDefaultChannelAsync();
|
||||
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(integrationEvent));
|
||||
await channel.BasicPublishAsync(ExchangeName, eventType, true, body);
|
||||
|
||||
// headers
|
||||
var props = new BasicProperties();
|
||||
props.Headers = new Dictionary<string, object?>()
|
||||
{
|
||||
{ CreatedAtHeader, Instant.FromDateTimeUtc(DateTime.UtcNow).ToString() },
|
||||
{ EventIdHeader, Guid.NewGuid().ToString() }
|
||||
};
|
||||
|
||||
await channel.BasicPublishAsync(ExchangeName, eventType, true, props, body);
|
||||
_logger.LogInformation("Published event {EventName}", eventType);
|
||||
}
|
||||
|
||||
@@ -70,6 +77,8 @@ public class RabbitMQEventBus : IEventBus, IHostedService
|
||||
return OnReceivedEvent(sender, @event, channel);
|
||||
};
|
||||
|
||||
await channel.BasicConsumeAsync(_options.ClientIdentifier, false, consumer, cancellationToken: cancellationToken);
|
||||
|
||||
foreach (var subscription in _subscriptionManager.Subscriptions)
|
||||
{
|
||||
await channel.QueueBindAsync(_options.ClientIdentifier, ExchangeName, subscription.Key,
|
||||
@@ -77,8 +86,6 @@ public class RabbitMQEventBus : IEventBus, IHostedService
|
||||
_logger.LogInformation("Subscribed to {SubscriptionKey}", subscription.Key);
|
||||
}
|
||||
|
||||
await channel.BasicConsumeAsync(_options.ClientIdentifier, false, consumer, cancellationToken: cancellationToken);
|
||||
|
||||
_logger.LogInformation("RabbitMQ EventBus started.");
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -106,7 +113,7 @@ public class RabbitMQEventBus : IEventBus, IHostedService
|
||||
}
|
||||
|
||||
var eventBody = Encoding.UTF8.GetString(@event.Body.Span);
|
||||
var eventObject = JsonConvert.DeserializeObject(eventBody, _subscriptionManager.Subscriptions[eventName], _jsonSerializerSettings) as IntegrationEvent;
|
||||
var eventObject = JsonConvert.DeserializeObject(eventBody, _subscriptionManager.Subscriptions[eventName], _jsonSerializerSettings) as IIntegrationEvent;
|
||||
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
using NodaTime;
|
||||
|
||||
namespace FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
public abstract class IntegrationEvent
|
||||
{
|
||||
public Guid EventId { get; set; }
|
||||
public Instant CreatedAt { get; set; }
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using FictionArchive.Service.TranslationService.Services.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
@@ -12,7 +13,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
namespace FictionArchive.Service.TranslationService.Migrations
|
||||
{
|
||||
[DbContext(typeof(TranslationServiceDbContext))]
|
||||
[Migration("20251118052322_Initial")]
|
||||
[Migration("20251122225458_Initial")]
|
||||
partial class Initial
|
||||
{
|
||||
/// <inheritdoc />
|
||||
@@ -27,11 +28,9 @@ namespace FictionArchive.Service.TranslationService.Migrations
|
||||
|
||||
modelBuilder.Entity("FictionArchive.Service.TranslationService.Models.Database.TranslationRequest", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<long>("BilledCharacterCount")
|
||||
.HasColumnType("bigint");
|
||||
@@ -1,6 +1,6 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using NodaTime;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
@@ -16,8 +16,7 @@ namespace FictionArchive.Service.TranslationService.Migrations
|
||||
name: "TranslationRequests",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false)
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
OriginalText = table.Column<string>(type: "text", nullable: false),
|
||||
TranslatedText = table.Column<string>(type: "text", nullable: true),
|
||||
From = table.Column<int>(type: "integer", nullable: false),
|
||||
@@ -1,4 +1,5 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using FictionArchive.Service.TranslationService.Services.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
@@ -24,11 +25,9 @@ namespace FictionArchive.Service.TranslationService.Migrations
|
||||
|
||||
modelBuilder.Entity("FictionArchive.Service.TranslationService.Models.Database.TranslationRequest", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<long>("BilledCharacterCount")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
@@ -4,7 +4,7 @@ using FictionArchive.Service.TranslationService.Models.Enums;
|
||||
|
||||
namespace FictionArchive.Service.TranslationService.Models.IntegrationEvents;
|
||||
|
||||
public class TranslationRequestCompletedEvent : IntegrationEvent
|
||||
public class TranslationRequestCompletedEvent : IIntegrationEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// Maps this event back to a triggering request.
|
||||
|
||||
@@ -3,7 +3,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
|
||||
|
||||
namespace FictionArchive.Service.TranslationService.Models.IntegrationEvents;
|
||||
|
||||
public class TranslationRequestCreatedEvent : IntegrationEvent
|
||||
public class TranslationRequestCreatedEvent : IIntegrationEvent
|
||||
{
|
||||
public Guid TranslationRequestId { get; set; }
|
||||
public Language From { get; set; }
|
||||
|
||||
@@ -73,6 +73,6 @@ public class Program
|
||||
|
||||
app.MapGraphQL();
|
||||
|
||||
app.Run();
|
||||
app.RunWithGraphQLCommands(args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"subgraph": "Translation",
|
||||
"http": {
|
||||
"baseAddress": "http://localhost:5234/graphql"
|
||||
}
|
||||
}
|
||||
23
FictionArchive.Service.UserService/Dockerfile
Normal file
23
FictionArchive.Service.UserService/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.UserService/FictionArchive.Service.UserService.csproj", "FictionArchive.Service.UserService/"]
|
||||
RUN dotnet restore "FictionArchive.Service.UserService/FictionArchive.Service.UserService.csproj"
|
||||
COPY . .
|
||||
WORKDIR "/src/FictionArchive.Service.UserService"
|
||||
RUN dotnet build "./FictionArchive.Service.UserService.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "./FictionArchive.Service.UserService.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.UserService.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>
|
||||
<Content Include="..\.dockerignore">
|
||||
<Link>.dockerignore</Link>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
13
FictionArchive.Service.UserService/GraphQL/Mutation.cs
Normal file
13
FictionArchive.Service.UserService/GraphQL/Mutation.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using FictionArchive.Service.UserService.Models.Database;
|
||||
using FictionArchive.Service.UserService.Services;
|
||||
|
||||
namespace FictionArchive.Service.UserService.GraphQL;
|
||||
|
||||
public class Mutation
|
||||
{
|
||||
public async Task<User> RegisterUser(string username, string email, string oAuthProviderId,
|
||||
string? inviterOAuthProviderId, UserManagementService userManagementService)
|
||||
{
|
||||
return await userManagementService.RegisterUser(username, email, oAuthProviderId, inviterOAuthProviderId);
|
||||
}
|
||||
}
|
||||
12
FictionArchive.Service.UserService/GraphQL/Query.cs
Normal file
12
FictionArchive.Service.UserService/GraphQL/Query.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using FictionArchive.Service.UserService.Models.Database;
|
||||
using FictionArchive.Service.UserService.Services;
|
||||
|
||||
namespace FictionArchive.Service.UserService.GraphQL;
|
||||
|
||||
public class Query
|
||||
{
|
||||
public async Task<IQueryable<User>> GetUsers(UserManagementService userManagementService)
|
||||
{
|
||||
return userManagementService.GetUsers();
|
||||
}
|
||||
}
|
||||
77
FictionArchive.Service.UserService/Migrations/20251122034145_Initial.Designer.cs
generated
Normal file
77
FictionArchive.Service.UserService/Migrations/20251122034145_Initial.Designer.cs
generated
Normal file
@@ -0,0 +1,77 @@
|
||||
// <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("20251122034145_Initial")]
|
||||
partial class Initial
|
||||
{
|
||||
/// <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<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.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,51 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using NodaTime;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace FictionArchive.Service.UserService.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class Initial : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Users",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
Username = table.Column<string>(type: "text", nullable: false),
|
||||
Email = table.Column<string>(type: "text", nullable: false),
|
||||
OAuthProviderId = table.Column<string>(type: "text", nullable: false),
|
||||
Disabled = table.Column<bool>(type: "boolean", nullable: false),
|
||||
InviterId = table.Column<Guid>(type: "uuid", 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_Users", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_Users_Users_InviterId",
|
||||
column: x => x.InviterId,
|
||||
principalTable: "Users",
|
||||
principalColumn: "Id");
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Users_InviterId",
|
||||
table: "Users",
|
||||
column: "InviterId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Users");
|
||||
}
|
||||
}
|
||||
}
|
||||
80
FictionArchive.Service.UserService/Migrations/20251122040724_UniqueOAuthProviderId.Designer.cs
generated
Normal file
80
FictionArchive.Service.UserService/Migrations/20251122040724_UniqueOAuthProviderId.Designer.cs
generated
Normal file
@@ -0,0 +1,80 @@
|
||||
// <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("20251122040724_UniqueOAuthProviderId")]
|
||||
partial class UniqueOAuthProviderId
|
||||
{
|
||||
/// <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<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,28 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace FictionArchive.Service.UserService.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class UniqueOAuthProviderId : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Users_OAuthProviderId",
|
||||
table: "Users",
|
||||
column: "OAuthProviderId",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_Users_OAuthProviderId",
|
||||
table: "Users");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using FictionArchive.Service.UserService.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.UserService.Migrations
|
||||
{
|
||||
[DbContext(typeof(UserServiceDbContext))]
|
||||
partial class UserServiceDbContextModelSnapshot : 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.UserService.Models.Database.User", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
20
FictionArchive.Service.UserService/Models/Database/User.cs
Normal file
20
FictionArchive.Service.UserService/Models/Database/User.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using FictionArchive.Service.Shared.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FictionArchive.Service.UserService.Models.Database;
|
||||
|
||||
[Index(nameof(OAuthProviderId), IsUnique = true)]
|
||||
public class User : BaseEntity<Guid>
|
||||
{
|
||||
public string Username { get; set; }
|
||||
public string Email { get; set; }
|
||||
public string OAuthProviderId { get; set; }
|
||||
|
||||
|
||||
public bool Disabled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The user that generated an invite used by this user.
|
||||
/// </summary>
|
||||
public User? Inviter { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
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; }
|
||||
}
|
||||
52
FictionArchive.Service.UserService/Program.cs
Normal file
52
FictionArchive.Service.UserService/Program.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
using FictionArchive.Service.Shared.Extensions;
|
||||
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
||||
using FictionArchive.Service.UserService.GraphQL;
|
||||
using FictionArchive.Service.UserService.Models.IntegrationEvents;
|
||||
using FictionArchive.Service.UserService.Services;
|
||||
using FictionArchive.Service.UserService.Services.EventHandlers;
|
||||
|
||||
namespace FictionArchive.Service.UserService;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
#region Event Bus
|
||||
|
||||
builder.Services.AddRabbitMQ(opt =>
|
||||
{
|
||||
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
|
||||
})
|
||||
.Subscribe<AuthUserAddedEvent, AuthUserAddedEventHandler>();
|
||||
|
||||
#endregion
|
||||
|
||||
#region GraphQL
|
||||
|
||||
builder.Services.AddDefaultGraphQl<Query, Mutation>();
|
||||
|
||||
#endregion
|
||||
|
||||
builder.Services.RegisterDbContext<UserServiceDbContext>(builder.Configuration.GetConnectionString("DefaultConnection"));
|
||||
builder.Services.AddTransient<UserManagementService>();
|
||||
|
||||
builder.Services.AddHealthChecks();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Update database
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var dbContext = scope.ServiceProvider.GetRequiredService<UserServiceDbContext>();
|
||||
dbContext.UpdateDatabase();
|
||||
}
|
||||
|
||||
app.MapGraphQL();
|
||||
|
||||
app.MapHealthChecks("/healthz");
|
||||
|
||||
app.RunWithGraphQLCommands(args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:20480",
|
||||
"sslPort": 44309
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "http://localhost:5145",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "graphql",
|
||||
"applicationUrl": "https://localhost:7157;http://localhost:5145",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using FictionArchive.Service.UserService.Models.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FictionArchive.Service.UserService.Services;
|
||||
|
||||
public class UserManagementService
|
||||
{
|
||||
private readonly ILogger<UserManagementService> _logger;
|
||||
private readonly UserServiceDbContext _dbContext;
|
||||
|
||||
public UserManagementService(UserServiceDbContext dbContext, ILogger<UserManagementService> logger)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<User> RegisterUser(string username, string email, string oAuthProviderId,
|
||||
string? inviterOAuthProviderId)
|
||||
{
|
||||
var newUser = new User();
|
||||
User? inviter =
|
||||
await _dbContext.Users.FirstOrDefaultAsync(user => user.OAuthProviderId == inviterOAuthProviderId);
|
||||
if (inviter == null && inviterOAuthProviderId != null)
|
||||
{
|
||||
_logger.LogCritical(
|
||||
"A user with OAuthProviderId {OAuthProviderId} was marked as having inviter with OAuthProviderId {inviterOAuthProviderId}, but no user was found with that value.",
|
||||
inviterOAuthProviderId, inviterOAuthProviderId);
|
||||
newUser.Disabled = true;
|
||||
}
|
||||
|
||||
newUser.Username = username;
|
||||
newUser.Email = email;
|
||||
newUser.OAuthProviderId = oAuthProviderId;
|
||||
|
||||
_dbContext.Users.Add(newUser); // Add the new user to the DbContext
|
||||
await _dbContext.SaveChangesAsync(); // Save changes to the database
|
||||
|
||||
return newUser;
|
||||
}
|
||||
|
||||
public IQueryable<User> GetUsers()
|
||||
{
|
||||
return _dbContext.Users.AsQueryable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using FictionArchive.Service.Shared.Services.Database;
|
||||
using FictionArchive.Service.UserService.Models.Database;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FictionArchive.Service.UserService.Services;
|
||||
|
||||
public class UserServiceDbContext : FictionArchiveDbContext
|
||||
{
|
||||
public DbSet<User> Users { get; set; }
|
||||
|
||||
public UserServiceDbContext(DbContextOptions options, ILogger<UserServiceDbContext> logger) : base(options, logger)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
16
FictionArchive.Service.UserService/appsettings.json
Normal file
16
FictionArchive.Service.UserService/appsettings.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Host=localhost;Database=FictionArchive_UserService;Username=postgres;password=postgres"
|
||||
},
|
||||
"RabbitMQ": {
|
||||
"ConnectionString": "amqp://localhost",
|
||||
"ClientIdentifier": "UserService"
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
6
FictionArchive.Service.UserService/subgraph-config.json
Normal file
6
FictionArchive.Service.UserService/subgraph-config.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"subgraph": "User",
|
||||
"http": {
|
||||
"baseAddress": "http://localhost:5145/graphql"
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.Shar
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.SchedulerService", "FictionArchive.Service.SchedulerService\FictionArchive.Service.SchedulerService.csproj", "{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.UserService", "FictionArchive.Service.UserService\FictionArchive.Service.UserService.csproj", "{EE4D4795-2F79-4614-886D-AF8DA77120AC}"
|
||||
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}"
|
||||
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}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -42,5 +50,21 @@ Global
|
||||
{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Debug|Any CPU.ActiveCfg = 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.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.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.Build.0 = Release|Any CPU
|
||||
{166E645E-9DFB-44E8-8CC8-FA249A11679F}.Debug|Any CPU.ActiveCfg = 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.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
1
fictionarchive-web/.env
Normal file
1
fictionarchive-web/.env
Normal file
@@ -0,0 +1 @@
|
||||
VITE_GRAPHQL_URI=http://localhost:5234/graphql/
|
||||
27
fictionarchive-web/.gitignore
vendored
Normal file
27
fictionarchive-web/.gitignore
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Generated GraphQL artifacts
|
||||
src/__generated__/
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
42
fictionarchive-web/README.md
Normal file
42
fictionarchive-web/README.md
Normal file
@@ -0,0 +1,42 @@
|
||||
# FictionArchive React Starter
|
||||
|
||||
A minimal React + Vite + Apollo Client scaffold ready to connect to the FictionArchive Fusion gateway. Point it at your own endpoint by changing `VITE_GRAPHQL_URI`.
|
||||
|
||||
## Getting started
|
||||
|
||||
```bash
|
||||
cd fictionarchive-web
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Then open the printed local URL. Update `.env` (create it if missing) with your endpoint:
|
||||
|
||||
```
|
||||
VITE_GRAPHQL_URI=https://localhost:5001/graphql
|
||||
VITE_OIDC_AUTHORITY=https://your-idp
|
||||
VITE_OIDC_CLIENT_ID=fictionarchive-web
|
||||
VITE_OIDC_REDIRECT_URI=http://localhost:5173
|
||||
VITE_OIDC_POST_LOGOUT_REDIRECT_URI=http://localhost:5173
|
||||
# Optional: token used only by codegen if your gateway requires auth
|
||||
VITE_CODEGEN_TOKEN=your_api_token
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
- `npm run dev`: start Vite dev server.
|
||||
- `npm run build`: type-check + build (runs codegen first via `prebuild`).
|
||||
- `npm run codegen`: generate typed hooks from `src/**/*.graphql` into `src/__generated__/graphql.ts`.
|
||||
|
||||
## Project notes
|
||||
|
||||
- `src/apolloClient.ts` configures the Apollo client with `InMemoryCache`, reads `VITE_GRAPHQL_URI`, and attaches an `Authorization: Bearer` header when an OIDC user is present.
|
||||
- GraphQL code generation is configured via `codegen.ts` (loads `.env`/`.env.local` automatically); run `npm run codegen` to emit typed hooks to `src/__generated__/graphql.ts` (ignored by git) or rely on the `prebuild` hook.
|
||||
- Routing is handled in `src/App.tsx` with `react-router-dom`; `/` renders the novels listing and `/novels/:id` is stubbed for future detail pages.
|
||||
- Styles live primarily in `src/index.css` alongside the shared UI components.
|
||||
|
||||
## Codegen tips
|
||||
|
||||
- Default schema URL: `CODEGEN_SCHEMA_URL` (falls back to `VITE_GRAPHQL_URI`, then `https://localhost:5001/graphql`).
|
||||
- Add `VITE_CODEGEN_TOKEN` (or `CODEGEN_TOKEN`) if your gateway requires a bearer token during introspection.
|
||||
- Generated outputs land in `src/__generated__/graphql.ts` (git-ignored). Run `npm run codegen` after schema/operation changes or rely on `npm run build` (runs `prebuild`).
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user