Compare commits
3 Commits
98ae4ea4f2
...
feature/FA
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f88f340d0a | ||
| 055ef33666 | |||
|
|
48ee43c4f6 |
@@ -1,7 +1,6 @@
|
|||||||
using FictionArchive.Service.AuthenticationService.Models.Requests;
|
using FictionArchive.Service.AuthenticationService.Models.Requests;
|
||||||
using FictionArchive.Service.AuthenticationService.Models.IntegrationEvents;
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
using MassTransit;
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
namespace FictionArchive.Service.AuthenticationService.Controllers
|
namespace FictionArchive.Service.AuthenticationService.Controllers
|
||||||
@@ -10,11 +9,11 @@ namespace FictionArchive.Service.AuthenticationService.Controllers
|
|||||||
[ApiController]
|
[ApiController]
|
||||||
public class AuthenticationWebhookController : ControllerBase
|
public class AuthenticationWebhookController : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly IEventBus _eventBus;
|
private readonly IPublishEndpoint _publishEndpoint;
|
||||||
|
|
||||||
public AuthenticationWebhookController(IEventBus eventBus)
|
public AuthenticationWebhookController(IPublishEndpoint publishEndpoint)
|
||||||
{
|
{
|
||||||
_eventBus = eventBus;
|
_publishEndpoint = publishEndpoint;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost(nameof(UserRegistered))]
|
[HttpPost(nameof(UserRegistered))]
|
||||||
@@ -28,7 +27,7 @@ namespace FictionArchive.Service.AuthenticationService.Controllers
|
|||||||
EventUserUsername = payload.EventUserUsername
|
EventUserUsername = payload.EventUserUsername
|
||||||
};
|
};
|
||||||
|
|
||||||
await _eventBus.Publish(authUserAddedEvent);
|
await _publishEndpoint.Publish(authUserAddedEvent);
|
||||||
|
|
||||||
return Ok();
|
return Ok();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
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; }
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
using FictionArchive.Service.Shared;
|
using FictionArchive.Service.Shared.MassTransit;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.AuthenticationService;
|
namespace FictionArchive.Service.AuthenticationService;
|
||||||
|
|
||||||
@@ -16,13 +15,10 @@ public class Program
|
|||||||
builder.Services.AddEndpointsApiExplorer();
|
builder.Services.AddEndpointsApiExplorer();
|
||||||
builder.Services.AddSwaggerGen();
|
builder.Services.AddSwaggerGen();
|
||||||
|
|
||||||
#region Event Bus
|
#region MassTransit
|
||||||
|
|
||||||
|
builder.Services.AddFictionArchiveMassTransit(builder.Configuration);
|
||||||
|
|
||||||
builder.Services.AddRabbitMQ(opt =>
|
|
||||||
{
|
|
||||||
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
|
|
||||||
});
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
builder.Services.AddHealthChecks();
|
builder.Services.AddHealthChecks();
|
||||||
|
|||||||
@@ -6,8 +6,10 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"RabbitMQ": {
|
"RabbitMQ": {
|
||||||
"ConnectionString": "amqp://localhost",
|
"Host": "localhost",
|
||||||
"ClientIdentifier": "AuthenticationService"
|
"VirtualHost": "/",
|
||||||
|
"Username": "guest",
|
||||||
|
"Password": "guest"
|
||||||
},
|
},
|
||||||
"AllowedHosts": "*"
|
"AllowedHosts": "*"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
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; }
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@@ -2,10 +2,9 @@ using Amazon.Runtime;
|
|||||||
using Amazon.S3;
|
using Amazon.S3;
|
||||||
using FictionArchive.Common.Extensions;
|
using FictionArchive.Common.Extensions;
|
||||||
using FictionArchive.Service.FileService.Models;
|
using FictionArchive.Service.FileService.Models;
|
||||||
using FictionArchive.Service.FileService.Models.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.FileService.Services.EventHandlers;
|
using FictionArchive.Service.FileService.Services.EventHandlers;
|
||||||
using FictionArchive.Service.Shared.Extensions;
|
using FictionArchive.Service.Shared.Extensions;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
using FictionArchive.Service.Shared.MassTransit;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
namespace FictionArchive.Service.FileService;
|
namespace FictionArchive.Service.FileService;
|
||||||
@@ -24,14 +23,15 @@ public class Program
|
|||||||
|
|
||||||
builder.Services.AddHealthChecks();
|
builder.Services.AddHealthChecks();
|
||||||
|
|
||||||
#region Event Bus
|
#region MassTransit
|
||||||
|
|
||||||
|
builder.Services.AddFictionArchiveMassTransit(
|
||||||
|
builder.Configuration,
|
||||||
|
x =>
|
||||||
|
{
|
||||||
|
x.AddConsumer<UploadFileCommandConsumer>();
|
||||||
|
});
|
||||||
|
|
||||||
builder.Services.AddRabbitMQ(opt =>
|
|
||||||
{
|
|
||||||
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
|
|
||||||
})
|
|
||||||
.Subscribe<FileUploadRequestCreatedEvent, FileUploadRequestCreatedEventHandler>();
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
// Add authentication with cookie support
|
// Add authentication with cookie support
|
||||||
|
|||||||
@@ -2,57 +2,62 @@ using Amazon.S3;
|
|||||||
using Amazon.S3.Model;
|
using Amazon.S3.Model;
|
||||||
using FictionArchive.Common.Enums;
|
using FictionArchive.Common.Enums;
|
||||||
using FictionArchive.Service.FileService.Models;
|
using FictionArchive.Service.FileService.Models;
|
||||||
using FictionArchive.Service.FileService.Models.IntegrationEvents;
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
|
using MassTransit;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
namespace FictionArchive.Service.FileService.Services.EventHandlers;
|
namespace FictionArchive.Service.FileService.Services.EventHandlers;
|
||||||
|
|
||||||
public class FileUploadRequestCreatedEventHandler : IIntegrationEventHandler<FileUploadRequestCreatedEvent>
|
public class UploadFileCommandConsumer : IConsumer<UploadFileCommand>
|
||||||
{
|
{
|
||||||
private readonly ILogger<FileUploadRequestCreatedEventHandler> _logger;
|
private readonly ILogger<UploadFileCommandConsumer> _logger;
|
||||||
private readonly AmazonS3Client _amazonS3Client;
|
private readonly AmazonS3Client _amazonS3Client;
|
||||||
private readonly IEventBus _eventBus;
|
|
||||||
private readonly S3Configuration _s3Configuration;
|
private readonly S3Configuration _s3Configuration;
|
||||||
private readonly ProxyConfiguration _proxyConfiguration;
|
private readonly ProxyConfiguration _proxyConfiguration;
|
||||||
|
|
||||||
public FileUploadRequestCreatedEventHandler(ILogger<FileUploadRequestCreatedEventHandler> logger, AmazonS3Client amazonS3Client, IEventBus eventBus, IOptions<S3Configuration> s3Configuration, IOptions<ProxyConfiguration> proxyConfiguration)
|
public UploadFileCommandConsumer(
|
||||||
|
ILogger<UploadFileCommandConsumer> logger,
|
||||||
|
AmazonS3Client amazonS3Client,
|
||||||
|
IOptions<S3Configuration> s3Configuration,
|
||||||
|
IOptions<ProxyConfiguration> proxyConfiguration)
|
||||||
{
|
{
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_amazonS3Client = amazonS3Client;
|
_amazonS3Client = amazonS3Client;
|
||||||
_eventBus = eventBus;
|
|
||||||
_proxyConfiguration = proxyConfiguration.Value;
|
_proxyConfiguration = proxyConfiguration.Value;
|
||||||
_s3Configuration = s3Configuration.Value;
|
_s3Configuration = s3Configuration.Value;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Handle(FileUploadRequestCreatedEvent @event)
|
public async Task Consume(ConsumeContext<UploadFileCommand> context)
|
||||||
{
|
{
|
||||||
|
var command = context.Message;
|
||||||
|
|
||||||
var putObjectRequest = new PutObjectRequest();
|
var putObjectRequest = new PutObjectRequest();
|
||||||
putObjectRequest.BucketName = _s3Configuration.Bucket;
|
putObjectRequest.BucketName = _s3Configuration.Bucket;
|
||||||
putObjectRequest.Key = @event.FilePath;
|
putObjectRequest.Key = command.FilePath;
|
||||||
putObjectRequest.UseChunkEncoding = false; // Needed to avoid an error with Garage
|
putObjectRequest.UseChunkEncoding = false; // Needed to avoid an error with Garage
|
||||||
|
|
||||||
using MemoryStream memoryStream = new MemoryStream(@event.FileData);
|
using MemoryStream memoryStream = new MemoryStream(command.FileData);
|
||||||
putObjectRequest.InputStream = memoryStream;
|
putObjectRequest.InputStream = memoryStream;
|
||||||
|
|
||||||
var s3Response = await _amazonS3Client.PutObjectAsync(putObjectRequest);
|
var s3Response = await _amazonS3Client.PutObjectAsync(putObjectRequest);
|
||||||
if (s3Response.HttpStatusCode != System.Net.HttpStatusCode.OK)
|
if (s3Response.HttpStatusCode != System.Net.HttpStatusCode.OK)
|
||||||
{
|
{
|
||||||
_logger.LogError("An error occurred while uploading file to S3. Response code: {responsecode}", s3Response.HttpStatusCode);
|
_logger.LogError("An error occurred while uploading file to S3. Response code: {responsecode}", s3Response.HttpStatusCode);
|
||||||
await _eventBus.Publish(new FileUploadRequestStatusUpdateEvent()
|
await context.Publish(new FileUploadCompletedEvent
|
||||||
{
|
{
|
||||||
RequestId = @event.RequestId,
|
RequestId = command.RequestId,
|
||||||
Status = RequestStatus.Failed,
|
Status = RequestStatus.Failed,
|
||||||
ErrorMessage = "An error occurred while uploading file to S3."
|
ErrorMessage = "An error occurred while uploading file to S3."
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await _eventBus.Publish(new FileUploadRequestStatusUpdateEvent()
|
await context.Publish(new FileUploadCompletedEvent
|
||||||
{
|
{
|
||||||
Status = RequestStatus.Success,
|
Status = RequestStatus.Success,
|
||||||
RequestId = @event.RequestId,
|
RequestId = command.RequestId,
|
||||||
FileAccessUrl = _proxyConfiguration.BaseUrl + "/" + @event.FilePath
|
FileAccessUrl = _proxyConfiguration.BaseUrl + "/" + command.FilePath
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,8 +9,10 @@
|
|||||||
"BaseUrl": "https://localhost:7247/api"
|
"BaseUrl": "https://localhost:7247/api"
|
||||||
},
|
},
|
||||||
"RabbitMQ": {
|
"RabbitMQ": {
|
||||||
"ConnectionString": "amqp://localhost",
|
"Host": "localhost",
|
||||||
"ClientIdentifier": "FileService"
|
"VirtualHost": "/",
|
||||||
|
"Username": "guest",
|
||||||
|
"Password": "guest"
|
||||||
},
|
},
|
||||||
"S3": {
|
"S3": {
|
||||||
"Url": "https://s3.orfl.xyz",
|
"Url": "https://s3.orfl.xyz",
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using FictionArchive.Common.Enums;
|
using FictionArchive.Common.Enums;
|
||||||
using FictionArchive.Service.FileService.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.NovelService.Models.Configuration;
|
using FictionArchive.Service.NovelService.Models.Configuration;
|
||||||
using FictionArchive.Service.NovelService.Models.Enums;
|
using FictionArchive.Service.NovelService.Models.Enums;
|
||||||
using FictionArchive.Service.NovelService.Models.Images;
|
using FictionArchive.Service.NovelService.Models.Images;
|
||||||
@@ -8,8 +7,9 @@ using FictionArchive.Service.NovelService.Models.Novels;
|
|||||||
using FictionArchive.Service.NovelService.Models.SourceAdapters;
|
using FictionArchive.Service.NovelService.Models.SourceAdapters;
|
||||||
using FictionArchive.Service.NovelService.Services;
|
using FictionArchive.Service.NovelService.Services;
|
||||||
using FictionArchive.Service.NovelService.Services.SourceAdapters;
|
using FictionArchive.Service.NovelService.Services.SourceAdapters;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
|
using MassTransit;
|
||||||
using HtmlAgilityPack;
|
using HtmlAgilityPack;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Logging.Abstractions;
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
@@ -72,7 +72,8 @@ public class NovelUpdateServiceTests
|
|||||||
private static NovelUpdateService CreateService(
|
private static NovelUpdateService CreateService(
|
||||||
NovelServiceDbContext dbContext,
|
NovelServiceDbContext dbContext,
|
||||||
ISourceAdapter adapter,
|
ISourceAdapter adapter,
|
||||||
IEventBus eventBus,
|
IPublishEndpoint publishEndpoint,
|
||||||
|
ISendEndpointProvider sendEndpointProvider,
|
||||||
string pendingImageUrl = "https://pending/placeholder.jpg")
|
string pendingImageUrl = "https://pending/placeholder.jpg")
|
||||||
{
|
{
|
||||||
var options = Options.Create(new NovelUpdateServiceConfiguration
|
var options = Options.Create(new NovelUpdateServiceConfiguration
|
||||||
@@ -80,7 +81,7 @@ public class NovelUpdateServiceTests
|
|||||||
PendingImageUrl = pendingImageUrl
|
PendingImageUrl = pendingImageUrl
|
||||||
});
|
});
|
||||||
|
|
||||||
return new NovelUpdateService(dbContext, NullLogger<NovelUpdateService>.Instance, new[] { adapter }, eventBus, options);
|
return new NovelUpdateService(dbContext, NullLogger<NovelUpdateService>.Instance, new[] { adapter }, publishEndpoint, sendEndpointProvider, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -102,13 +103,15 @@ public class NovelUpdateServiceTests
|
|||||||
ImageData = new List<ImageData> { image1, image2 }
|
ImageData = new List<ImageData> { image1, image2 }
|
||||||
}));
|
}));
|
||||||
|
|
||||||
var publishedEvents = new List<FileUploadRequestCreatedEvent>();
|
var publishedCommands = new List<UploadFileCommand>();
|
||||||
var eventBus = Substitute.For<IEventBus>();
|
var publishEndpoint = Substitute.For<IPublishEndpoint>();
|
||||||
eventBus.Publish(Arg.Do<FileUploadRequestCreatedEvent>(publishedEvents.Add)).Returns(Task.CompletedTask);
|
var sendEndpointProvider = Substitute.For<ISendEndpointProvider>();
|
||||||
eventBus.Publish(Arg.Any<object>(), Arg.Any<string>()).Returns(Task.CompletedTask);
|
var sendEndpoint = Substitute.For<ISendEndpoint>();
|
||||||
|
sendEndpointProvider.GetSendEndpoint(Arg.Any<Uri>()).Returns(Task.FromResult(sendEndpoint));
|
||||||
|
sendEndpoint.Send(Arg.Do<UploadFileCommand>(publishedCommands.Add), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||||
|
|
||||||
var pendingImageUrl = "https://pending/placeholder.jpg";
|
var pendingImageUrl = "https://pending/placeholder.jpg";
|
||||||
var service = CreateService(dbContext, adapter, eventBus, pendingImageUrl);
|
var service = CreateService(dbContext, adapter, publishEndpoint, sendEndpointProvider, pendingImageUrl);
|
||||||
|
|
||||||
var updatedChapter = await service.PullChapterContents(novel.Id, volume.Id, chapter.Order);
|
var updatedChapter = await service.PullChapterContents(novel.Id, volume.Id, chapter.Order);
|
||||||
|
|
||||||
@@ -127,10 +130,10 @@ public class NovelUpdateServiceTests
|
|||||||
.Should()
|
.Should()
|
||||||
.BeEquivalentTo(updatedChapter.Images.Select(img => img.Id.ToString()));
|
.BeEquivalentTo(updatedChapter.Images.Select(img => img.Id.ToString()));
|
||||||
|
|
||||||
publishedEvents.Should().HaveCount(2);
|
publishedCommands.Should().HaveCount(2);
|
||||||
publishedEvents.Select(e => e.RequestId).Should().BeEquivalentTo(updatedChapter.Images.Select(i => i.Id));
|
publishedCommands.Select(e => e.RequestId).Should().BeEquivalentTo(updatedChapter.Images.Select(i => i.Id));
|
||||||
publishedEvents.Select(e => e.FileData).Should().BeEquivalentTo(new[] { image1.Data, image2.Data });
|
publishedCommands.Select(e => e.FileData).Should().BeEquivalentTo(new[] { image1.Data, image2.Data });
|
||||||
publishedEvents.Should().OnlyContain(e => e.FilePath.StartsWith($"{novel.Id}/Images/Chapter-{updatedChapter.Id}/"));
|
publishedCommands.Should().OnlyContain(e => e.FilePath.StartsWith($"{novel.Id}/Images/Chapter-{updatedChapter.Id}/"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -151,11 +154,12 @@ public class NovelUpdateServiceTests
|
|||||||
ImageData = new List<ImageData> { image }
|
ImageData = new List<ImageData> { image }
|
||||||
}));
|
}));
|
||||||
|
|
||||||
var eventBus = Substitute.For<IEventBus>();
|
var publishEndpoint = Substitute.For<IPublishEndpoint>();
|
||||||
eventBus.Publish(Arg.Any<FileUploadRequestCreatedEvent>()).Returns(Task.CompletedTask);
|
var sendEndpointProvider = Substitute.For<ISendEndpointProvider>();
|
||||||
eventBus.Publish(Arg.Any<object>(), Arg.Any<string>()).Returns(Task.CompletedTask);
|
var sendEndpoint = Substitute.For<ISendEndpoint>();
|
||||||
|
sendEndpointProvider.GetSendEndpoint(Arg.Any<Uri>()).Returns(Task.FromResult(sendEndpoint));
|
||||||
|
|
||||||
var service = CreateService(dbContext, adapter, eventBus);
|
var service = CreateService(dbContext, adapter, publishEndpoint, sendEndpointProvider);
|
||||||
|
|
||||||
var updatedChapter = await service.PullChapterContents(novel.Id, volume.Id, chapter.Order);
|
var updatedChapter = await service.PullChapterContents(novel.Id, volume.Id, chapter.Order);
|
||||||
|
|
||||||
@@ -186,8 +190,9 @@ public class NovelUpdateServiceTests
|
|||||||
await dbContext.SaveChangesAsync();
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
var adapter = Substitute.For<ISourceAdapter>();
|
var adapter = Substitute.For<ISourceAdapter>();
|
||||||
var eventBus = Substitute.For<IEventBus>();
|
var publishEndpoint = Substitute.For<IPublishEndpoint>();
|
||||||
var service = CreateService(dbContext, adapter, eventBus);
|
var sendEndpointProvider = Substitute.For<ISendEndpointProvider>();
|
||||||
|
var service = CreateService(dbContext, adapter, publishEndpoint, sendEndpointProvider);
|
||||||
|
|
||||||
var newUrl = "https://cdn.example.com/uploaded/cover.jpg";
|
var newUrl = "https://cdn.example.com/uploaded/cover.jpg";
|
||||||
|
|
||||||
@@ -228,8 +233,9 @@ public class NovelUpdateServiceTests
|
|||||||
await dbContext.SaveChangesAsync();
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
var adapter = Substitute.For<ISourceAdapter>();
|
var adapter = Substitute.For<ISourceAdapter>();
|
||||||
var eventBus = Substitute.For<IEventBus>();
|
var publishEndpoint = Substitute.For<IPublishEndpoint>();
|
||||||
var service = CreateService(dbContext, adapter, eventBus, pendingUrl);
|
var sendEndpointProvider = Substitute.For<ISendEndpointProvider>();
|
||||||
|
var service = CreateService(dbContext, adapter, publishEndpoint, sendEndpointProvider, pendingUrl);
|
||||||
|
|
||||||
var newUrl = "https://cdn.example.com/uploaded/image.jpg";
|
var newUrl = "https://cdn.example.com/uploaded/image.jpg";
|
||||||
|
|
||||||
@@ -277,8 +283,9 @@ public class NovelUpdateServiceTests
|
|||||||
await dbContext.SaveChangesAsync();
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
var adapter = Substitute.For<ISourceAdapter>();
|
var adapter = Substitute.For<ISourceAdapter>();
|
||||||
var eventBus = Substitute.For<IEventBus>();
|
var publishEndpoint = Substitute.For<IPublishEndpoint>();
|
||||||
var service = CreateService(dbContext, adapter, eventBus, pendingUrl);
|
var sendEndpointProvider = Substitute.For<ISendEndpointProvider>();
|
||||||
|
var service = CreateService(dbContext, adapter, publishEndpoint, sendEndpointProvider, pendingUrl);
|
||||||
|
|
||||||
var newUrl = "https://cdn.example.com/uploaded/img1.jpg";
|
var newUrl = "https://cdn.example.com/uploaded/img1.jpg";
|
||||||
|
|
||||||
|
|||||||
@@ -1,27 +1,20 @@
|
|||||||
using FictionArchive.Service.NovelService.Models.Enums;
|
|
||||||
using FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
|
||||||
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;
|
||||||
using FictionArchive.Service.NovelService.Services.SourceAdapters;
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
using HotChocolate.Authorization;
|
using HotChocolate.Authorization;
|
||||||
using HotChocolate.Types;
|
using HotChocolate.Types;
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.NovelService.GraphQL;
|
namespace FictionArchive.Service.NovelService.GraphQL;
|
||||||
|
|
||||||
public class Mutation
|
public class Mutation
|
||||||
{
|
{
|
||||||
[Authorize]
|
[Authorize]
|
||||||
public async Task<NovelUpdateRequestedEvent> ImportNovel(string novelUrl, NovelUpdateService service)
|
public async Task<ImportNovelCommand> ImportNovel(string novelUrl, NovelUpdateService service)
|
||||||
{
|
{
|
||||||
return await service.QueueNovelImport(novelUrl);
|
return await service.QueueNovelImport(novelUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Authorize]
|
[Authorize]
|
||||||
public async Task<ChapterPullRequestedEvent> FetchChapterContents(
|
public async Task<PullChapterContentCommand> FetchChapterContents(
|
||||||
uint novelId,
|
uint novelId,
|
||||||
uint volumeId,
|
uint volumeId,
|
||||||
uint chapterOrder,
|
uint chapterOrder,
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
|
||||||
|
|
||||||
public class ChapterPullRequestedEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
public uint NovelId { get; set; }
|
|
||||||
public uint VolumeId { get; set; }
|
|
||||||
public uint ChapterOrder { get; set; }
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
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; }
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
|
||||||
|
|
||||||
public class NovelUpdateRequestedEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
public string NovelUrl { get; set; }
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
using FictionArchive.Common.Enums;
|
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
|
||||||
|
|
||||||
public class TranslationRequestCompletedEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Maps this event back to a triggering request.
|
|
||||||
/// </summary>
|
|
||||||
public Guid? TranslationRequestId { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// The resulting text.
|
|
||||||
/// </summary>
|
|
||||||
public string? TranslatedText { get; set; }
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
using FictionArchive.Common.Enums;
|
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
|
||||||
|
|
||||||
public class TranslationRequestCreatedEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
public Guid TranslationRequestId { get; set; }
|
|
||||||
public Language From { get; set; }
|
|
||||||
public Language To { get; set; }
|
|
||||||
public string Body { get; set; }
|
|
||||||
public string TranslationEngineKey { get; set; }
|
|
||||||
}
|
|
||||||
@@ -1,14 +1,13 @@
|
|||||||
using FictionArchive.Common.Extensions;
|
using FictionArchive.Common.Extensions;
|
||||||
using FictionArchive.Service.NovelService.GraphQL;
|
using FictionArchive.Service.NovelService.GraphQL;
|
||||||
using FictionArchive.Service.NovelService.Models.Configuration;
|
using FictionArchive.Service.NovelService.Models.Configuration;
|
||||||
using FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.NovelService.Services;
|
using FictionArchive.Service.NovelService.Services;
|
||||||
using FictionArchive.Service.NovelService.Services.EventHandlers;
|
using FictionArchive.Service.NovelService.Services.Consumers;
|
||||||
using FictionArchive.Service.NovelService.Services.SourceAdapters;
|
using FictionArchive.Service.NovelService.Services.SourceAdapters;
|
||||||
using FictionArchive.Service.NovelService.Services.SourceAdapters.Novelpia;
|
using FictionArchive.Service.NovelService.Services.SourceAdapters.Novelpia;
|
||||||
using FictionArchive.Service.Shared;
|
using FictionArchive.Service.Shared;
|
||||||
using FictionArchive.Service.Shared.Extensions;
|
using FictionArchive.Service.Shared.Extensions;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
using FictionArchive.Service.Shared.MassTransit;
|
||||||
using FictionArchive.Service.Shared.Services.GraphQL;
|
using FictionArchive.Service.Shared.Services.GraphQL;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
@@ -25,18 +24,19 @@ public class Program
|
|||||||
|
|
||||||
builder.Services.AddMemoryCache();
|
builder.Services.AddMemoryCache();
|
||||||
|
|
||||||
#region Event Bus
|
#region MassTransit
|
||||||
|
|
||||||
if (!isSchemaExport)
|
if (!isSchemaExport)
|
||||||
{
|
{
|
||||||
builder.Services.AddRabbitMQ(opt =>
|
builder.Services.AddFictionArchiveMassTransit<NovelServiceDbContext>(
|
||||||
{
|
builder.Configuration,
|
||||||
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
|
cfg =>
|
||||||
})
|
{
|
||||||
.Subscribe<TranslationRequestCompletedEvent, TranslationRequestCompletedEventHandler>()
|
cfg.AddConsumer<ImportNovelCommandConsumer>();
|
||||||
.Subscribe<NovelUpdateRequestedEvent, NovelUpdateRequestedEventHandler>()
|
cfg.AddConsumer<PullChapterContentCommandConsumer>();
|
||||||
.Subscribe<ChapterPullRequestedEvent, ChapterPullRequestedEventHandler>()
|
cfg.AddConsumer<TranslationCompletedEventConsumer>();
|
||||||
.Subscribe<FileUploadRequestStatusUpdateEvent, FileUploadRequestStatusUpdateEventHandler>();
|
cfg.AddConsumer<FileUploadCompletedEventConsumer>();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using FictionArchive.Common.Enums;
|
||||||
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
|
using MassTransit;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.NovelService.Services.Consumers;
|
||||||
|
|
||||||
|
public class FileUploadCompletedEventConsumer : IConsumer<FileUploadCompletedEvent>
|
||||||
|
{
|
||||||
|
private readonly ILogger<FileUploadCompletedEventConsumer> _logger;
|
||||||
|
private readonly NovelServiceDbContext _dbContext;
|
||||||
|
private readonly NovelUpdateService _novelUpdateService;
|
||||||
|
|
||||||
|
public FileUploadCompletedEventConsumer(
|
||||||
|
ILogger<FileUploadCompletedEventConsumer> logger,
|
||||||
|
NovelServiceDbContext dbContext,
|
||||||
|
NovelUpdateService novelUpdateService)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
_dbContext = dbContext;
|
||||||
|
_novelUpdateService = novelUpdateService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Consume(ConsumeContext<FileUploadCompletedEvent> context)
|
||||||
|
{
|
||||||
|
var @event = context.Message;
|
||||||
|
|
||||||
|
var image = await _dbContext.Images.FindAsync(@event.RequestId);
|
||||||
|
if (image == null)
|
||||||
|
{
|
||||||
|
// Not a request we care about.
|
||||||
|
_logger.LogDebug(
|
||||||
|
"FileUploadCompletedEvent received for unknown image: {RequestId}",
|
||||||
|
@event.RequestId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (@event.Status == RequestStatus.Failed)
|
||||||
|
{
|
||||||
|
_logger.LogError(
|
||||||
|
"Image upload failed for image with id {ImageId}: {ErrorMessage}",
|
||||||
|
image.Id, @event.ErrorMessage);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (@event.Status == RequestStatus.Success)
|
||||||
|
{
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Image upload succeeded for image with id {ImageId}",
|
||||||
|
image.Id);
|
||||||
|
await _novelUpdateService.UpdateImage(image.Id, @event.FileAccessUrl!);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||||
|
using MassTransit;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.NovelService.Services.Consumers;
|
||||||
|
|
||||||
|
public class ImportNovelCommandConsumer : IConsumer<ImportNovelCommand>
|
||||||
|
{
|
||||||
|
private readonly ILogger<ImportNovelCommandConsumer> _logger;
|
||||||
|
private readonly NovelUpdateService _novelUpdateService;
|
||||||
|
|
||||||
|
public ImportNovelCommandConsumer(
|
||||||
|
ILogger<ImportNovelCommandConsumer> logger,
|
||||||
|
NovelUpdateService novelUpdateService)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
_novelUpdateService = novelUpdateService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Consume(ConsumeContext<ImportNovelCommand> context)
|
||||||
|
{
|
||||||
|
var command = context.Message;
|
||||||
|
_logger.LogInformation("Processing ImportNovelCommand for URL: {NovelUrl}", command.NovelUrl);
|
||||||
|
|
||||||
|
await _novelUpdateService.ImportNovel(command.NovelUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||||
|
using MassTransit;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.NovelService.Services.Consumers;
|
||||||
|
|
||||||
|
public class PullChapterContentCommandConsumer : IConsumer<PullChapterContentCommand>
|
||||||
|
{
|
||||||
|
private readonly ILogger<PullChapterContentCommandConsumer> _logger;
|
||||||
|
private readonly NovelUpdateService _novelUpdateService;
|
||||||
|
|
||||||
|
public PullChapterContentCommandConsumer(
|
||||||
|
ILogger<PullChapterContentCommandConsumer> logger,
|
||||||
|
NovelUpdateService novelUpdateService)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
_novelUpdateService = novelUpdateService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Consume(ConsumeContext<PullChapterContentCommand> context)
|
||||||
|
{
|
||||||
|
var command = context.Message;
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Processing PullChapterContentCommand for Novel: {NovelId}, Volume: {VolumeId}, Chapter: {ChapterOrder}",
|
||||||
|
command.NovelId, command.VolumeId, command.ChapterOrder);
|
||||||
|
|
||||||
|
await _novelUpdateService.PullChapterContents(command.NovelId, command.VolumeId, command.ChapterOrder);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using FictionArchive.Service.NovelService.Models.Localization;
|
||||||
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
|
using MassTransit;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.NovelService.Services.Consumers;
|
||||||
|
|
||||||
|
public class TranslationCompletedEventConsumer : IConsumer<TranslationCompletedEvent>
|
||||||
|
{
|
||||||
|
private readonly ILogger<TranslationCompletedEventConsumer> _logger;
|
||||||
|
private readonly NovelServiceDbContext _dbContext;
|
||||||
|
|
||||||
|
public TranslationCompletedEventConsumer(
|
||||||
|
ILogger<TranslationCompletedEventConsumer> logger,
|
||||||
|
NovelServiceDbContext dbContext)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
_dbContext = dbContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Consume(ConsumeContext<TranslationCompletedEvent> context)
|
||||||
|
{
|
||||||
|
var @event = context.Message;
|
||||||
|
|
||||||
|
var localizationRequest = await _dbContext.LocalizationRequests
|
||||||
|
.Include(r => r.KeyRequestedForTranslation)
|
||||||
|
.ThenInclude(lk => lk.Texts)
|
||||||
|
.FirstOrDefaultAsync(lk => lk.Id == @event.TranslationRequestId);
|
||||||
|
|
||||||
|
if (localizationRequest == null)
|
||||||
|
{
|
||||||
|
// Not one of our requests, discard it
|
||||||
|
_logger.LogDebug(
|
||||||
|
"TranslationCompletedEvent received for unknown request: {RequestId}",
|
||||||
|
@event.TranslationRequestId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
localizationRequest.KeyRequestedForTranslation.Texts.Add(new LocalizationText()
|
||||||
|
{
|
||||||
|
Language = localizationRequest.TranslateTo,
|
||||||
|
Text = @event.TranslatedText,
|
||||||
|
TranslationEngine = localizationRequest.Engine
|
||||||
|
});
|
||||||
|
_dbContext.LocalizationRequests.Remove(localizationRequest);
|
||||||
|
await _dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Completed translation for request: {RequestId}",
|
||||||
|
@event.TranslationRequestId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
using FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.NovelService.Services.EventHandlers;
|
|
||||||
|
|
||||||
public class ChapterPullRequestedEventHandler : IIntegrationEventHandler<ChapterPullRequestedEvent>
|
|
||||||
{
|
|
||||||
private readonly NovelUpdateService _novelUpdateService;
|
|
||||||
|
|
||||||
public ChapterPullRequestedEventHandler(NovelUpdateService novelUpdateService)
|
|
||||||
{
|
|
||||||
_novelUpdateService = novelUpdateService;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Handle(ChapterPullRequestedEvent @event)
|
|
||||||
{
|
|
||||||
await _novelUpdateService.PullChapterContents(@event.NovelId, @event.VolumeId, @event.ChapterOrder);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
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,23 +0,0 @@
|
|||||||
using FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.NovelService.Services.EventHandlers;
|
|
||||||
|
|
||||||
public class NovelUpdateRequestedEventHandler : IIntegrationEventHandler<NovelUpdateRequestedEvent>
|
|
||||||
{
|
|
||||||
private readonly ILogger<NovelUpdateRequestedEventHandler> _logger;
|
|
||||||
private readonly IEventBus _eventBus;
|
|
||||||
private readonly NovelUpdateService _novelUpdateService;
|
|
||||||
|
|
||||||
public NovelUpdateRequestedEventHandler(ILogger<NovelUpdateRequestedEventHandler> logger, IEventBus eventBus, NovelUpdateService novelUpdateService)
|
|
||||||
{
|
|
||||||
_logger = logger;
|
|
||||||
_eventBus = eventBus;
|
|
||||||
_novelUpdateService = novelUpdateService;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Handle(NovelUpdateRequestedEvent @event)
|
|
||||||
{
|
|
||||||
await _novelUpdateService.ImportNovel(@event.NovelUrl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
using FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.NovelService.Models.Localization;
|
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.NovelService.Services.EventHandlers;
|
|
||||||
|
|
||||||
public class TranslationRequestCompletedEventHandler : IIntegrationEventHandler<TranslationRequestCompletedEvent>
|
|
||||||
{
|
|
||||||
private readonly ILogger<TranslationRequestCompletedEventHandler> _logger;
|
|
||||||
private readonly NovelServiceDbContext _dbContext;
|
|
||||||
|
|
||||||
public TranslationRequestCompletedEventHandler(ILogger<TranslationRequestCompletedEventHandler> logger, NovelServiceDbContext dbContext)
|
|
||||||
{
|
|
||||||
_logger = logger;
|
|
||||||
_dbContext = dbContext;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Handle(TranslationRequestCompletedEvent @event)
|
|
||||||
{
|
|
||||||
var localizationRequest = await _dbContext.LocalizationRequests.Include(r => r.KeyRequestedForTranslation)
|
|
||||||
.ThenInclude(lk => lk.Texts)
|
|
||||||
.FirstOrDefaultAsync(lk => lk.Id == @event.TranslationRequestId);
|
|
||||||
if (localizationRequest == null)
|
|
||||||
{
|
|
||||||
// Not one of our requests, discard it
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
localizationRequest.KeyRequestedForTranslation.Texts.Add(new LocalizationText()
|
|
||||||
{
|
|
||||||
Language = localizationRequest.TranslateTo,
|
|
||||||
Text = @event.TranslatedText,
|
|
||||||
TranslationEngine = localizationRequest.Engine
|
|
||||||
});
|
|
||||||
_dbContext.LocalizationRequests.Remove(localizationRequest);
|
|
||||||
await _dbContext.SaveChangesAsync();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
using FictionArchive.Common.Enums;
|
using FictionArchive.Common.Enums;
|
||||||
using FictionArchive.Service.FileService.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.NovelService.Models.Configuration;
|
using FictionArchive.Service.NovelService.Models.Configuration;
|
||||||
using FictionArchive.Service.NovelService.Models.Enums;
|
using FictionArchive.Service.NovelService.Models.Enums;
|
||||||
using FictionArchive.Service.NovelService.Models.Images;
|
using FictionArchive.Service.NovelService.Models.Images;
|
||||||
using FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.NovelService.Models.Localization;
|
using FictionArchive.Service.NovelService.Models.Localization;
|
||||||
using FictionArchive.Service.NovelService.Models.Novels;
|
using FictionArchive.Service.NovelService.Models.Novels;
|
||||||
using FictionArchive.Service.NovelService.Models.SourceAdapters;
|
using FictionArchive.Service.NovelService.Models.SourceAdapters;
|
||||||
using FictionArchive.Service.NovelService.Services.SourceAdapters;
|
using FictionArchive.Service.NovelService.Services.SourceAdapters;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||||
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
using HtmlAgilityPack;
|
using HtmlAgilityPack;
|
||||||
|
using MassTransit;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
@@ -20,15 +20,23 @@ public class NovelUpdateService
|
|||||||
private readonly NovelServiceDbContext _dbContext;
|
private readonly NovelServiceDbContext _dbContext;
|
||||||
private readonly ILogger<NovelUpdateService> _logger;
|
private readonly ILogger<NovelUpdateService> _logger;
|
||||||
private readonly IEnumerable<ISourceAdapter> _sourceAdapters;
|
private readonly IEnumerable<ISourceAdapter> _sourceAdapters;
|
||||||
private readonly IEventBus _eventBus;
|
private readonly IPublishEndpoint _publishEndpoint;
|
||||||
|
private readonly ISendEndpointProvider _sendEndpointProvider;
|
||||||
private readonly NovelUpdateServiceConfiguration _novelUpdateServiceConfiguration;
|
private readonly NovelUpdateServiceConfiguration _novelUpdateServiceConfiguration;
|
||||||
|
|
||||||
public NovelUpdateService(NovelServiceDbContext dbContext, ILogger<NovelUpdateService> logger, IEnumerable<ISourceAdapter> sourceAdapters, IEventBus eventBus, IOptions<NovelUpdateServiceConfiguration> novelUpdateServiceConfiguration)
|
public NovelUpdateService(
|
||||||
|
NovelServiceDbContext dbContext,
|
||||||
|
ILogger<NovelUpdateService> logger,
|
||||||
|
IEnumerable<ISourceAdapter> sourceAdapters,
|
||||||
|
IPublishEndpoint publishEndpoint,
|
||||||
|
ISendEndpointProvider sendEndpointProvider,
|
||||||
|
IOptions<NovelUpdateServiceConfiguration> novelUpdateServiceConfiguration)
|
||||||
{
|
{
|
||||||
_dbContext = dbContext;
|
_dbContext = dbContext;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_sourceAdapters = sourceAdapters;
|
_sourceAdapters = sourceAdapters;
|
||||||
_eventBus = eventBus;
|
_publishEndpoint = publishEndpoint;
|
||||||
|
_sendEndpointProvider = sendEndpointProvider;
|
||||||
_novelUpdateServiceConfiguration = novelUpdateServiceConfiguration.Value;
|
_novelUpdateServiceConfiguration = novelUpdateServiceConfiguration.Value;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -393,7 +401,7 @@ public class NovelUpdateService
|
|||||||
// Publish novel created event for new novels
|
// Publish novel created event for new novels
|
||||||
if (existingNovel == null)
|
if (existingNovel == null)
|
||||||
{
|
{
|
||||||
await _eventBus.Publish(new NovelCreatedEvent
|
await _publishEndpoint.Publish(new NovelCreatedEvent
|
||||||
{
|
{
|
||||||
NovelId = novel.Id,
|
NovelId = novel.Id,
|
||||||
Title = novel.Name.Texts.First(t => t.Language == novel.RawLanguage).Text,
|
Title = novel.Name.Texts.First(t => t.Language == novel.RawLanguage).Text,
|
||||||
@@ -408,7 +416,7 @@ public class NovelUpdateService
|
|||||||
{
|
{
|
||||||
foreach (var chapter in volume.Chapters.Where(c => !existingChapterIds.Contains(c.Id)))
|
foreach (var chapter in volume.Chapters.Where(c => !existingChapterIds.Contains(c.Id)))
|
||||||
{
|
{
|
||||||
await _eventBus.Publish(new ChapterCreatedEvent
|
await _publishEndpoint.Publish(new ChapterCreatedEvent
|
||||||
{
|
{
|
||||||
ChapterId = chapter.Id,
|
ChapterId = chapter.Id,
|
||||||
NovelId = novel.Id,
|
NovelId = novel.Id,
|
||||||
@@ -420,10 +428,11 @@ public class NovelUpdateService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Publish cover image event if needed
|
// Send cover image upload command if needed
|
||||||
if (shouldPublishCoverEvent && novel.CoverImage != null && metadata.CoverImage != null)
|
if (shouldPublishCoverEvent && novel.CoverImage != null && metadata.CoverImage != null)
|
||||||
{
|
{
|
||||||
await _eventBus.Publish(new FileUploadRequestCreatedEvent
|
var uploadEndpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("queue:upload-file-command"));
|
||||||
|
await uploadEndpoint.Send(new UploadFileCommand
|
||||||
{
|
{
|
||||||
RequestId = novel.CoverImage.Id,
|
RequestId = novel.CoverImage.Id,
|
||||||
FileData = metadata.CoverImage.Data,
|
FileData = metadata.CoverImage.Data,
|
||||||
@@ -431,7 +440,8 @@ public class NovelUpdateService
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Publish chapter pull events for chapters without body content
|
// Send chapter pull commands for chapters without body content
|
||||||
|
var pullChapterEndpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("queue:pull-chapter-content-command"));
|
||||||
foreach (var volume in novel.Volumes)
|
foreach (var volume in novel.Volumes)
|
||||||
{
|
{
|
||||||
var chaptersNeedingPull = volume.Chapters
|
var chaptersNeedingPull = volume.Chapters
|
||||||
@@ -440,7 +450,7 @@ public class NovelUpdateService
|
|||||||
|
|
||||||
foreach (var chapter in chaptersNeedingPull)
|
foreach (var chapter in chaptersNeedingPull)
|
||||||
{
|
{
|
||||||
await _eventBus.Publish(new ChapterPullRequestedEvent
|
await pullChapterEndpoint.Send(new PullChapterContentCommand
|
||||||
{
|
{
|
||||||
NovelId = novel.Id,
|
NovelId = novel.Id,
|
||||||
VolumeId = volume.Id,
|
VolumeId = volume.Id,
|
||||||
@@ -513,12 +523,13 @@ public class NovelUpdateService
|
|||||||
localizationText.Text = chapterDoc.DocumentNode.OuterHtml;
|
localizationText.Text = chapterDoc.DocumentNode.OuterHtml;
|
||||||
await _dbContext.SaveChangesAsync();
|
await _dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
// Body was updated, raise image request
|
// Body was updated, send upload commands for images
|
||||||
|
var uploadEndpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("queue:upload-file-command"));
|
||||||
int imgCount = 0;
|
int imgCount = 0;
|
||||||
foreach (var image in chapter.Images)
|
foreach (var image in chapter.Images)
|
||||||
{
|
{
|
||||||
var data = rawChapter.ImageData.FirstOrDefault(img => img.Url == image.OriginalPath);
|
var data = rawChapter.ImageData.FirstOrDefault(img => img.Url == image.OriginalPath);
|
||||||
await _eventBus.Publish(new FileUploadRequestCreatedEvent()
|
await uploadEndpoint.Send(new UploadFileCommand
|
||||||
{
|
{
|
||||||
FileData = data.Data,
|
FileData = data.Data,
|
||||||
FilePath = $"{novel.Id}/Images/Chapter-{chapter.Id}/{imgCount++}.jpg",
|
FilePath = $"{novel.Id}/Images/Chapter-{chapter.Id}/{imgCount++}.jpg",
|
||||||
@@ -557,26 +568,28 @@ public class NovelUpdateService
|
|||||||
await _dbContext.SaveChangesAsync();
|
await _dbContext.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<NovelUpdateRequestedEvent> QueueNovelImport(string novelUrl)
|
public async Task<ImportNovelCommand> QueueNovelImport(string novelUrl)
|
||||||
{
|
{
|
||||||
var importNovelRequestEvent = new NovelUpdateRequestedEvent()
|
var command = new ImportNovelCommand
|
||||||
{
|
{
|
||||||
NovelUrl = novelUrl
|
NovelUrl = novelUrl
|
||||||
};
|
};
|
||||||
await _eventBus.Publish(importNovelRequestEvent);
|
var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("queue:import-novel-command"));
|
||||||
return importNovelRequestEvent;
|
await endpoint.Send(command);
|
||||||
|
return command;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ChapterPullRequestedEvent> QueueChapterPull(uint novelId, uint volumeId, uint chapterOrder)
|
public async Task<PullChapterContentCommand> QueueChapterPull(uint novelId, uint volumeId, uint chapterOrder)
|
||||||
{
|
{
|
||||||
var chapterPullEvent = new ChapterPullRequestedEvent()
|
var command = new PullChapterContentCommand
|
||||||
{
|
{
|
||||||
NovelId = novelId,
|
NovelId = novelId,
|
||||||
VolumeId = volumeId,
|
VolumeId = volumeId,
|
||||||
ChapterOrder = chapterOrder
|
ChapterOrder = chapterOrder
|
||||||
};
|
};
|
||||||
await _eventBus.Publish(chapterPullEvent);
|
var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("queue:pull-chapter-content-command"));
|
||||||
return chapterPullEvent;
|
await endpoint.Send(command);
|
||||||
|
return command;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task DeleteNovel(uint novelId)
|
public async Task DeleteNovel(uint novelId)
|
||||||
|
|||||||
@@ -16,8 +16,10 @@
|
|||||||
"DefaultConnection": "Host=localhost;Database=FictionArchive_NovelService;Username=postgres;password=postgres"
|
"DefaultConnection": "Host=localhost;Database=FictionArchive_NovelService;Username=postgres;password=postgres"
|
||||||
},
|
},
|
||||||
"RabbitMQ": {
|
"RabbitMQ": {
|
||||||
"ConnectionString": "amqp://localhost",
|
"Host": "localhost",
|
||||||
"ClientIdentifier": "NovelService"
|
"VirtualHost": "/",
|
||||||
|
"Username": "guest",
|
||||||
|
"Password": "guest"
|
||||||
},
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
"OIDC": {
|
"OIDC": {
|
||||||
|
|||||||
23
FictionArchive.Service.ReportingService/Dockerfile
Normal file
23
FictionArchive.Service.ReportingService/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.ReportingService/FictionArchive.Service.ReportingService.csproj", "FictionArchive.Service.ReportingService/"]
|
||||||
|
RUN dotnet restore "FictionArchive.Service.ReportingService/FictionArchive.Service.ReportingService.csproj"
|
||||||
|
COPY . .
|
||||||
|
WORKDIR "/src/FictionArchive.Service.ReportingService"
|
||||||
|
RUN dotnet build "./FictionArchive.Service.ReportingService.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||||
|
|
||||||
|
FROM build AS publish
|
||||||
|
ARG BUILD_CONFIGURATION=Release
|
||||||
|
RUN dotnet publish "./FictionArchive.Service.ReportingService.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.ReportingService.dll"]
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
15
FictionArchive.Service.ReportingService/GraphQL/Mutation.cs
Normal file
15
FictionArchive.Service.ReportingService/GraphQL/Mutation.cs
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
using HotChocolate;
|
||||||
|
using HotChocolate.Authorization;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.ReportingService.GraphQL;
|
||||||
|
|
||||||
|
public class Mutation
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Placeholder mutation for GraphQL schema requirements.
|
||||||
|
/// The ReportingService is primarily read-only, consuming events from other services.
|
||||||
|
/// </summary>
|
||||||
|
[Authorize(Roles = ["admin"])]
|
||||||
|
[GraphQLDescription("Placeholder mutation. ReportingService is primarily read-only.")]
|
||||||
|
public bool Ping() => true;
|
||||||
|
}
|
||||||
52
FictionArchive.Service.ReportingService/GraphQL/Query.cs
Normal file
52
FictionArchive.Service.ReportingService/GraphQL/Query.cs
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using FictionArchive.Service.ReportingService.Models.Database;
|
||||||
|
using FictionArchive.Service.ReportingService.Models.DTOs;
|
||||||
|
using FictionArchive.Service.ReportingService.Services;
|
||||||
|
using HotChocolate;
|
||||||
|
using HotChocolate.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.ReportingService.GraphQL;
|
||||||
|
|
||||||
|
public class Query
|
||||||
|
{
|
||||||
|
[UseProjection]
|
||||||
|
[UseFiltering]
|
||||||
|
[UseSorting]
|
||||||
|
[GraphQLName("reportingJobs")]
|
||||||
|
public IQueryable<Job> GetReportingJobs(ReportingServiceDbContext dbContext)
|
||||||
|
=> dbContext.Jobs.Include(j => j.History);
|
||||||
|
|
||||||
|
[GraphQLName("reportingJob")]
|
||||||
|
public async Task<JobDto?> GetReportingJob(Guid id, ReportingServiceDbContext dbContext)
|
||||||
|
{
|
||||||
|
var job = await dbContext.Jobs
|
||||||
|
.Include(j => j.History.OrderBy(h => h.Timestamp))
|
||||||
|
.FirstOrDefaultAsync(j => j.Id == id);
|
||||||
|
|
||||||
|
if (job == null) return null;
|
||||||
|
|
||||||
|
return new JobDto
|
||||||
|
{
|
||||||
|
Id = job.Id,
|
||||||
|
JobType = job.JobType,
|
||||||
|
Status = job.Status,
|
||||||
|
CurrentStep = job.CurrentStep,
|
||||||
|
ErrorMessage = job.ErrorMessage,
|
||||||
|
Metadata = job.Metadata != null
|
||||||
|
? JsonSerializer.Deserialize<Dictionary<string, object>>(job.Metadata.RootElement.GetRawText())
|
||||||
|
: null,
|
||||||
|
History = job.History.Select(h => new JobHistoryEntryDto
|
||||||
|
{
|
||||||
|
FromState = h.FromState,
|
||||||
|
ToState = h.ToState,
|
||||||
|
Message = h.Message,
|
||||||
|
Error = h.Error,
|
||||||
|
Timestamp = h.Timestamp
|
||||||
|
}).ToList(),
|
||||||
|
CreatedTime = job.CreatedTime,
|
||||||
|
UpdatedTime = job.UpdatedTime,
|
||||||
|
CompletedTime = job.CompletedTime
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using NodaTime;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.ReportingService.Models.DTOs;
|
||||||
|
|
||||||
|
public class JobDto
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
public required string JobType { get; set; }
|
||||||
|
public required string Status { get; set; }
|
||||||
|
public string? CurrentStep { get; set; }
|
||||||
|
public string? ErrorMessage { get; set; }
|
||||||
|
public Dictionary<string, object>? Metadata { get; set; }
|
||||||
|
public List<JobHistoryEntryDto> History { get; set; } = new();
|
||||||
|
public Instant CreatedTime { get; set; }
|
||||||
|
public Instant UpdatedTime { get; set; }
|
||||||
|
public Instant? CompletedTime { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
using NodaTime;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.ReportingService.Models.DTOs;
|
||||||
|
|
||||||
|
public class JobHistoryEntryDto
|
||||||
|
{
|
||||||
|
public required string FromState { get; set; }
|
||||||
|
public required string ToState { get; set; }
|
||||||
|
public string? Message { get; set; }
|
||||||
|
public string? Error { get; set; }
|
||||||
|
public Instant Timestamp { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using NodaTime;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.ReportingService.Models.Database;
|
||||||
|
|
||||||
|
public class Job
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
public required string JobType { get; set; }
|
||||||
|
public required string Status { get; set; }
|
||||||
|
public string? CurrentStep { get; set; }
|
||||||
|
public string? ErrorMessage { get; set; }
|
||||||
|
public JsonDocument? Metadata { get; set; }
|
||||||
|
public Instant CreatedTime { get; set; }
|
||||||
|
public Instant UpdatedTime { get; set; }
|
||||||
|
public Instant? CompletedTime { get; set; }
|
||||||
|
|
||||||
|
public ICollection<JobHistoryEntry> History { get; set; } = new List<JobHistoryEntry>();
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using NodaTime;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.ReportingService.Models.Database;
|
||||||
|
|
||||||
|
public class JobHistoryEntry
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public Guid JobId { get; set; }
|
||||||
|
public required string FromState { get; set; }
|
||||||
|
public required string ToState { get; set; }
|
||||||
|
public string? Message { get; set; }
|
||||||
|
public string? Error { get; set; }
|
||||||
|
public Instant Timestamp { get; set; }
|
||||||
|
|
||||||
|
public Job Job { get; set; } = null!;
|
||||||
|
}
|
||||||
76
FictionArchive.Service.ReportingService/Program.cs
Normal file
76
FictionArchive.Service.ReportingService/Program.cs
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
using FictionArchive.Common.Extensions;
|
||||||
|
using FictionArchive.Service.ReportingService.GraphQL;
|
||||||
|
using FictionArchive.Service.ReportingService.Services;
|
||||||
|
using FictionArchive.Service.ReportingService.Services.Consumers;
|
||||||
|
using FictionArchive.Service.Shared;
|
||||||
|
using FictionArchive.Service.Shared.Extensions;
|
||||||
|
using FictionArchive.Service.Shared.MassTransit;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.ReportingService;
|
||||||
|
|
||||||
|
public class Program
|
||||||
|
{
|
||||||
|
public static void Main(string[] args)
|
||||||
|
{
|
||||||
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
|
var isSchemaExport = SchemaExportDetector.IsSchemaExportMode(args);
|
||||||
|
|
||||||
|
builder.AddLocalAppsettings();
|
||||||
|
|
||||||
|
builder.Services.AddHealthChecks();
|
||||||
|
|
||||||
|
#region Database
|
||||||
|
|
||||||
|
builder.Services.RegisterDbContext<ReportingServiceDbContext>(
|
||||||
|
builder.Configuration.GetConnectionString("DefaultConnection")!,
|
||||||
|
skipInfrastructure: isSchemaExport);
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region MassTransit
|
||||||
|
|
||||||
|
if (!isSchemaExport)
|
||||||
|
{
|
||||||
|
builder.Services.AddFictionArchiveMassTransit<ReportingServiceDbContext>(
|
||||||
|
builder.Configuration,
|
||||||
|
x =>
|
||||||
|
{
|
||||||
|
x.AddConsumer<JobStateChangedEventConsumer>();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region GraphQL
|
||||||
|
|
||||||
|
builder.Services.AddDefaultGraphQl<Query, Mutation>()
|
||||||
|
.AddAuthorization();
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
// Authentication & Authorization
|
||||||
|
builder.Services.AddOidcAuthentication(builder.Configuration);
|
||||||
|
builder.Services.AddFictionArchiveAuthorization();
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
|
||||||
|
if (!isSchemaExport)
|
||||||
|
{
|
||||||
|
using var scope = app.Services.CreateScope();
|
||||||
|
var dbContext = scope.ServiceProvider.GetRequiredService<ReportingServiceDbContext>();
|
||||||
|
dbContext.UpdateDatabase();
|
||||||
|
}
|
||||||
|
|
||||||
|
app.UseHttpsRedirection();
|
||||||
|
|
||||||
|
app.MapHealthChecks("/healthz");
|
||||||
|
|
||||||
|
app.UseAuthentication();
|
||||||
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
app.MapGraphQL();
|
||||||
|
|
||||||
|
app.RunWithGraphQLCommands(args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||||
|
"iisSettings": {
|
||||||
|
"windowsAuthentication": false,
|
||||||
|
"anonymousAuthentication": true,
|
||||||
|
"iisExpress": {
|
||||||
|
"applicationUrl": "http://localhost:45320",
|
||||||
|
"sslPort": 44320
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"profiles": {
|
||||||
|
"http": {
|
||||||
|
"commandName": "Project",
|
||||||
|
"dotnetRunMessages": true,
|
||||||
|
"launchBrowser": true,
|
||||||
|
"applicationUrl": "http://localhost:5180",
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"https": {
|
||||||
|
"commandName": "Project",
|
||||||
|
"dotnetRunMessages": true,
|
||||||
|
"launchBrowser": true,
|
||||||
|
"launchUrl": "graphql",
|
||||||
|
"applicationUrl": "https://localhost:7320;http://localhost:5180",
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"IIS Express": {
|
||||||
|
"commandName": "IISExpress",
|
||||||
|
"launchBrowser": true,
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using FictionArchive.Service.ReportingService.Models.Database;
|
||||||
|
using FictionArchive.Service.Shared.MassTransit.Contracts;
|
||||||
|
using MassTransit;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.ReportingService.Services.Consumers;
|
||||||
|
|
||||||
|
public class JobStateChangedEventConsumer : IConsumer<JobStateChangedEvent>
|
||||||
|
{
|
||||||
|
private readonly ReportingServiceDbContext _dbContext;
|
||||||
|
private readonly ILogger<JobStateChangedEventConsumer> _logger;
|
||||||
|
|
||||||
|
public JobStateChangedEventConsumer(
|
||||||
|
ReportingServiceDbContext dbContext,
|
||||||
|
ILogger<JobStateChangedEventConsumer> logger)
|
||||||
|
{
|
||||||
|
_dbContext = dbContext;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Consume(ConsumeContext<JobStateChangedEvent> context)
|
||||||
|
{
|
||||||
|
var @event = context.Message;
|
||||||
|
|
||||||
|
var job = await _dbContext.Jobs.FindAsync(@event.JobId);
|
||||||
|
|
||||||
|
if (job == null)
|
||||||
|
{
|
||||||
|
job = new Job
|
||||||
|
{
|
||||||
|
Id = @event.JobId,
|
||||||
|
JobType = @event.JobType,
|
||||||
|
Status = @event.ToState,
|
||||||
|
CreatedTime = @event.Timestamp,
|
||||||
|
UpdatedTime = @event.Timestamp,
|
||||||
|
Metadata = @event.Metadata != null
|
||||||
|
? JsonSerializer.SerializeToDocument(@event.Metadata)
|
||||||
|
: null
|
||||||
|
};
|
||||||
|
_dbContext.Jobs.Add(job);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
job.Status = @event.ToState;
|
||||||
|
job.UpdatedTime = @event.Timestamp;
|
||||||
|
|
||||||
|
if (@event.Error != null)
|
||||||
|
{
|
||||||
|
job.ErrorMessage = @event.Error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (@event.ToState is "Completed" or "Failed")
|
||||||
|
{
|
||||||
|
job.CompletedTime = @event.Timestamp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var historyEntry = new JobHistoryEntry
|
||||||
|
{
|
||||||
|
JobId = @event.JobId,
|
||||||
|
FromState = @event.FromState,
|
||||||
|
ToState = @event.ToState,
|
||||||
|
Message = @event.Message,
|
||||||
|
Error = @event.Error,
|
||||||
|
Timestamp = @event.Timestamp
|
||||||
|
};
|
||||||
|
_dbContext.JobHistoryEntries.Add(historyEntry);
|
||||||
|
|
||||||
|
await _dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
_logger.LogDebug("Recorded job state change: {JobId} {FromState} -> {ToState}",
|
||||||
|
@event.JobId, @event.FromState, @event.ToState);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
using FictionArchive.Service.ReportingService.Models.Database;
|
||||||
|
using FictionArchive.Service.Shared.Services.Database;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.ReportingService.Services;
|
||||||
|
|
||||||
|
public class ReportingServiceDbContext : FictionArchiveDbContext
|
||||||
|
{
|
||||||
|
public ReportingServiceDbContext(DbContextOptions options, ILogger<ReportingServiceDbContext> logger)
|
||||||
|
: base(options, logger) { }
|
||||||
|
|
||||||
|
public DbSet<Job> Jobs => Set<Job>();
|
||||||
|
public DbSet<JobHistoryEntry> JobHistoryEntries => Set<JobHistoryEntry>();
|
||||||
|
|
||||||
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
base.OnModelCreating(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity<Job>(entity =>
|
||||||
|
{
|
||||||
|
entity.HasKey(e => e.Id);
|
||||||
|
entity.HasIndex(e => e.JobType);
|
||||||
|
entity.HasIndex(e => e.Status);
|
||||||
|
entity.HasIndex(e => e.CreatedTime);
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity<JobHistoryEntry>(entity =>
|
||||||
|
{
|
||||||
|
entity.HasKey(e => e.Id);
|
||||||
|
entity.HasOne(e => e.Job)
|
||||||
|
.WithMany(j => j.History)
|
||||||
|
.HasForeignKey(e => e.JobId)
|
||||||
|
.OnDelete(DeleteBehavior.Cascade);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
28
FictionArchive.Service.ReportingService/appsettings.json
Normal file
28
FictionArchive.Service.ReportingService/appsettings.json
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"DefaultConnection": "Host=localhost;Database=FictionArchive_ReportingService;Username=postgres;password=postgres"
|
||||||
|
},
|
||||||
|
"RabbitMQ": {
|
||||||
|
"Host": "localhost",
|
||||||
|
"VirtualHost": "/",
|
||||||
|
"Username": "guest",
|
||||||
|
"Password": "guest"
|
||||||
|
},
|
||||||
|
"OIDC": {
|
||||||
|
"Authority": "https://auth.orfl.xyz/application/o/fiction-archive/",
|
||||||
|
"ClientId": "ldi5IpEidq2WW0Ka1lehVskb2SOBjnYRaZCpEyBh",
|
||||||
|
"Audience": "ldi5IpEidq2WW0Ka1lehVskb2SOBjnYRaZCpEyBh",
|
||||||
|
"ValidIssuer": "https://auth.orfl.xyz/application/o/fiction-archive/",
|
||||||
|
"ValidateIssuer": true,
|
||||||
|
"ValidateAudience": true,
|
||||||
|
"ValidateLifetime": true,
|
||||||
|
"ValidateIssuerSigningKey": true
|
||||||
|
},
|
||||||
|
"AllowedHosts": "*"
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"subgraph": "Reporting",
|
||||||
|
"http": {
|
||||||
|
"baseAddress": "http://localhost:5180/graphql"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,6 +19,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="AppAny.Quartz.EntityFrameworkCore.Migrations.PostgreSQL" Version="0.5.1" />
|
<PackageReference Include="AppAny.Quartz.EntityFrameworkCore.Migrations.PostgreSQL" Version="0.5.1" />
|
||||||
|
<PackageReference Include="MassTransit" Version="8.4.0" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
using MassTransit;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using Quartz;
|
using Quartz;
|
||||||
|
|
||||||
@@ -6,30 +6,70 @@ namespace FictionArchive.Service.SchedulerService.Models.JobTemplates;
|
|||||||
|
|
||||||
public class EventJobTemplate : IJob
|
public class EventJobTemplate : IJob
|
||||||
{
|
{
|
||||||
private readonly IEventBus _eventBus;
|
private readonly IPublishEndpoint _publishEndpoint;
|
||||||
|
private readonly ISendEndpointProvider _sendEndpointProvider;
|
||||||
private readonly ILogger<EventJobTemplate> _logger;
|
private readonly ILogger<EventJobTemplate> _logger;
|
||||||
|
|
||||||
public const string EventTypeParameter = "RoutingKey";
|
public const string EventTypeParameter = "MessageType";
|
||||||
public const string EventDataParameter = "MessageData";
|
public const string EventDataParameter = "MessageData";
|
||||||
|
public const string IsCommandParameter = "IsCommand";
|
||||||
public EventJobTemplate(IEventBus eventBus, ILogger<EventJobTemplate> logger)
|
public const string DestinationQueueParameter = "DestinationQueue";
|
||||||
|
|
||||||
|
public EventJobTemplate(
|
||||||
|
IPublishEndpoint publishEndpoint,
|
||||||
|
ISendEndpointProvider sendEndpointProvider,
|
||||||
|
ILogger<EventJobTemplate> logger)
|
||||||
{
|
{
|
||||||
_eventBus = eventBus;
|
_publishEndpoint = publishEndpoint;
|
||||||
|
_sendEndpointProvider = sendEndpointProvider;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Execute(IJobExecutionContext context)
|
public async Task Execute(IJobExecutionContext context)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var eventData = context.MergedJobDataMap.GetString(EventDataParameter);
|
var messageData = context.MergedJobDataMap.GetString(EventDataParameter);
|
||||||
var eventType = context.MergedJobDataMap.GetString(EventTypeParameter);
|
var messageTypeName = context.MergedJobDataMap.GetString(EventTypeParameter);
|
||||||
var eventObject = JsonConvert.DeserializeObject(eventData);
|
var isCommand = context.MergedJobDataMap.GetBoolean(IsCommandParameter);
|
||||||
await _eventBus.Publish(eventObject, eventType);
|
|
||||||
|
var messageType = Type.GetType(messageTypeName!);
|
||||||
|
if (messageType == null)
|
||||||
|
{
|
||||||
|
_logger.LogError("Could not resolve message type: {MessageType}", messageTypeName);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var message = JsonConvert.DeserializeObject(messageData!, messageType);
|
||||||
|
if (message == null)
|
||||||
|
{
|
||||||
|
_logger.LogError("Could not deserialize message data for type: {MessageType}", messageTypeName);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isCommand)
|
||||||
|
{
|
||||||
|
var destinationQueue = context.MergedJobDataMap.GetString(DestinationQueueParameter);
|
||||||
|
if (string.IsNullOrEmpty(destinationQueue))
|
||||||
|
{
|
||||||
|
_logger.LogError("Destination queue not specified for command message");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri($"queue:{destinationQueue}"));
|
||||||
|
await endpoint.Send(message, messageType);
|
||||||
|
_logger.LogInformation("Sent command {MessageType} to queue {Queue}", messageTypeName, destinationQueue);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await _publishEndpoint.Publish(message, messageType);
|
||||||
|
_logger.LogInformation("Published event {MessageType}", messageTypeName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "An error occurred while running an event job.");
|
_logger.LogError(ex, "An error occurred while running an event job.");
|
||||||
|
throw; // Re-throw to let Quartz handle retries
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ using FictionArchive.Service.SchedulerService.GraphQL;
|
|||||||
using FictionArchive.Service.SchedulerService.Services;
|
using FictionArchive.Service.SchedulerService.Services;
|
||||||
using FictionArchive.Service.Shared;
|
using FictionArchive.Service.Shared;
|
||||||
using FictionArchive.Service.Shared.Extensions;
|
using FictionArchive.Service.Shared.Extensions;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
using FictionArchive.Service.Shared.MassTransit;
|
||||||
using Quartz;
|
using Quartz;
|
||||||
using Quartz.Impl.AdoJobStore;
|
using Quartz.Impl.AdoJobStore;
|
||||||
|
|
||||||
@@ -34,14 +34,11 @@ public class Program
|
|||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Event Bus
|
#region MassTransit
|
||||||
|
|
||||||
if (!isSchemaExport)
|
if (!isSchemaExport)
|
||||||
{
|
{
|
||||||
builder.Services.AddRabbitMQ(opt =>
|
builder.Services.AddFictionArchiveMassTransit(builder.Configuration);
|
||||||
{
|
|
||||||
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
using System.Data;
|
using System.Data;
|
||||||
using FictionArchive.Service.SchedulerService.Models;
|
using FictionArchive.Service.SchedulerService.Models;
|
||||||
using FictionArchive.Service.SchedulerService.Models.JobTemplates;
|
using FictionArchive.Service.SchedulerService.Models.JobTemplates;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
using Quartz;
|
using Quartz;
|
||||||
using Quartz.Impl.Matchers;
|
using Quartz.Impl.Matchers;
|
||||||
|
|
||||||
|
|||||||
@@ -6,8 +6,10 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"RabbitMQ": {
|
"RabbitMQ": {
|
||||||
"ConnectionString": "amqp://localhost",
|
"Host": "localhost",
|
||||||
"ClientIdentifier": "SchedulerService"
|
"VirtualHost": "/",
|
||||||
|
"Username": "guest",
|
||||||
|
"Password": "guest"
|
||||||
},
|
},
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"DefaultConnection": "Host=localhost;Database=FictionArchive_SchedulerService;Username=postgres;password=postgres"
|
"DefaultConnection": "Host=localhost;Database=FictionArchive_SchedulerService;Username=postgres;password=postgres"
|
||||||
|
|||||||
@@ -31,7 +31,9 @@
|
|||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime" Version="9.0.4" />
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime" Version="9.0.4" />
|
||||||
<PackageReference Include="Polly" Version="8.6.5" />
|
<PackageReference Include="Polly" Version="8.6.5" />
|
||||||
<PackageReference Include="RabbitMQ.Client" Version="7.2.0" />
|
<PackageReference Include="MassTransit" Version="8.4.0" />
|
||||||
|
<PackageReference Include="MassTransit.RabbitMQ" Version="8.4.0" />
|
||||||
|
<PackageReference Include="MassTransit.EntityFrameworkCore" Version="8.4.0" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.11" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.11" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Configuration;
|
||||||
|
|
||||||
|
public class MassTransitOptions
|
||||||
|
{
|
||||||
|
public string Host { get; set; } = "localhost";
|
||||||
|
public string VirtualHost { get; set; } = "/";
|
||||||
|
public string Username { get; set; } = "guest";
|
||||||
|
public string Password { get; set; } = "guest";
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||||
|
|
||||||
|
public record ImportNovelCommand : ICommand
|
||||||
|
{
|
||||||
|
public required string NovelUrl { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||||
|
|
||||||
|
public record PullChapterContentCommand : ICommand
|
||||||
|
{
|
||||||
|
public required uint NovelId { get; init; }
|
||||||
|
public required uint VolumeId { get; init; }
|
||||||
|
public required uint ChapterOrder { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
using FictionArchive.Common.Enums;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||||
|
|
||||||
|
public record TranslateTextCommand : ICommand
|
||||||
|
{
|
||||||
|
public Guid TranslationRequestId { get; init; }
|
||||||
|
public Language From { get; init; }
|
||||||
|
public Language To { get; init; }
|
||||||
|
public required string Body { get; init; }
|
||||||
|
public required string TranslationEngineKey { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||||
|
|
||||||
|
public record UploadFileCommand : ICommand
|
||||||
|
{
|
||||||
|
public Guid RequestId { get; init; }
|
||||||
|
public required string FilePath { get; init; }
|
||||||
|
public required byte[] FileData { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
|
|
||||||
|
public record AuthUserAddedEvent : IEvent
|
||||||
|
{
|
||||||
|
public required string OAuthProviderId { get; init; }
|
||||||
|
public required string InviterOAuthProviderId { get; init; }
|
||||||
|
public required string EventUserEmail { get; init; }
|
||||||
|
public required string EventUserUsername { get; init; }
|
||||||
|
}
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
|
|
||||||
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
public record ChapterCreatedEvent : IEvent
|
||||||
|
|
||||||
public class ChapterCreatedEvent : IIntegrationEvent
|
|
||||||
{
|
{
|
||||||
public required uint ChapterId { get; init; }
|
public required uint ChapterId { get; init; }
|
||||||
public required uint NovelId { get; init; }
|
public required uint NovelId { get; init; }
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
using FictionArchive.Common.Enums;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
|
|
||||||
|
public record FileUploadCompletedEvent : IEvent
|
||||||
|
{
|
||||||
|
public Guid RequestId { get; init; }
|
||||||
|
public RequestStatus Status { get; init; }
|
||||||
|
public string? FileAccessUrl { get; init; }
|
||||||
|
public string? ErrorMessage { get; init; }
|
||||||
|
}
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
using FictionArchive.Common.Enums;
|
using FictionArchive.Common.Enums;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
|
|
||||||
public class NovelCreatedEvent : IIntegrationEvent
|
public record NovelCreatedEvent : IEvent
|
||||||
{
|
{
|
||||||
public required uint NovelId { get; init; }
|
public required uint NovelId { get; init; }
|
||||||
public required string Title { get; init; }
|
public required string Title { get; init; }
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
|
|
||||||
|
public record TranslationCompletedEvent : IEvent
|
||||||
|
{
|
||||||
|
public Guid TranslationRequestId { get; init; }
|
||||||
|
public required string TranslatedText { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
|
|
||||||
|
public record UserInvitedEvent : IEvent
|
||||||
|
{
|
||||||
|
public Guid InvitedUserId { get; init; }
|
||||||
|
public required string InvitedUsername { get; init; }
|
||||||
|
public required string InvitedEmail { get; init; }
|
||||||
|
public required string InvitedOAuthProviderId { get; init; }
|
||||||
|
|
||||||
|
public Guid InviterId { get; init; }
|
||||||
|
public required string InviterUsername { get; init; }
|
||||||
|
public required string InviterOAuthProviderId { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Marker interface for commands (do something, single consumer)
|
||||||
|
/// </summary>
|
||||||
|
public interface ICommand { }
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Marker interface for events (something happened, multiple subscribers)
|
||||||
|
/// </summary>
|
||||||
|
public interface IEvent { }
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using NodaTime;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.Shared.MassTransit.Contracts;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Published by sagas on state transitions for centralized job tracking
|
||||||
|
/// </summary>
|
||||||
|
public record JobStateChangedEvent : IEvent
|
||||||
|
{
|
||||||
|
public Guid JobId { get; init; }
|
||||||
|
public required string JobType { get; init; }
|
||||||
|
public required string FromState { get; init; }
|
||||||
|
public required string ToState { get; init; }
|
||||||
|
public string? Message { get; init; }
|
||||||
|
public string? Error { get; init; }
|
||||||
|
public Instant Timestamp { get; init; }
|
||||||
|
public Dictionary<string, object>? Metadata { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
using FictionArchive.Service.Shared.MassTransit.Configuration;
|
||||||
|
using MassTransit;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.Shared.MassTransit;
|
||||||
|
|
||||||
|
public static class MassTransitExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Adds MassTransit with RabbitMQ and Entity Framework outbox
|
||||||
|
/// </summary>
|
||||||
|
public static IServiceCollection AddFictionArchiveMassTransit<TDbContext>(
|
||||||
|
this IServiceCollection services,
|
||||||
|
IConfiguration configuration,
|
||||||
|
Action<IBusRegistrationConfigurator>? configureConsumers = null)
|
||||||
|
where TDbContext : DbContext
|
||||||
|
{
|
||||||
|
services.AddMassTransit(x =>
|
||||||
|
{
|
||||||
|
configureConsumers?.Invoke(x);
|
||||||
|
|
||||||
|
x.AddEntityFrameworkOutbox<TDbContext>(o =>
|
||||||
|
{
|
||||||
|
o.UsePostgres();
|
||||||
|
o.UseBusOutbox();
|
||||||
|
});
|
||||||
|
|
||||||
|
x.UsingRabbitMq((context, cfg) =>
|
||||||
|
{
|
||||||
|
var options = configuration.GetSection("RabbitMQ").Get<MassTransitOptions>()
|
||||||
|
?? new MassTransitOptions();
|
||||||
|
|
||||||
|
cfg.Host(options.Host, options.VirtualHost, h =>
|
||||||
|
{
|
||||||
|
h.Username(options.Username);
|
||||||
|
h.Password(options.Password);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Immediate retries for transient failures
|
||||||
|
cfg.UseMessageRetry(r => r.Intervals(
|
||||||
|
TimeSpan.FromSeconds(1),
|
||||||
|
TimeSpan.FromSeconds(1),
|
||||||
|
TimeSpan.FromSeconds(1)));
|
||||||
|
|
||||||
|
// Delayed redelivery for longer outages
|
||||||
|
cfg.UseDelayedRedelivery(r => r.Intervals(
|
||||||
|
TimeSpan.FromSeconds(5),
|
||||||
|
TimeSpan.FromSeconds(30),
|
||||||
|
TimeSpan.FromMinutes(2),
|
||||||
|
TimeSpan.FromMinutes(10),
|
||||||
|
TimeSpan.FromMinutes(30)));
|
||||||
|
|
||||||
|
cfg.ConfigureEndpoints(context);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds MassTransit with RabbitMQ without outbox (for services without EF)
|
||||||
|
/// </summary>
|
||||||
|
public static IServiceCollection AddFictionArchiveMassTransit(
|
||||||
|
this IServiceCollection services,
|
||||||
|
IConfiguration configuration,
|
||||||
|
Action<IBusRegistrationConfigurator>? configureConsumers = null)
|
||||||
|
{
|
||||||
|
services.AddMassTransit(x =>
|
||||||
|
{
|
||||||
|
configureConsumers?.Invoke(x);
|
||||||
|
|
||||||
|
x.UsingRabbitMq((context, cfg) =>
|
||||||
|
{
|
||||||
|
var options = configuration.GetSection("RabbitMQ").Get<MassTransitOptions>()
|
||||||
|
?? new MassTransitOptions();
|
||||||
|
|
||||||
|
cfg.Host(options.Host, options.VirtualHost, h =>
|
||||||
|
{
|
||||||
|
h.Username(options.Username);
|
||||||
|
h.Password(options.Password);
|
||||||
|
});
|
||||||
|
|
||||||
|
cfg.UseMessageRetry(r => r.Intervals(
|
||||||
|
TimeSpan.FromSeconds(1),
|
||||||
|
TimeSpan.FromSeconds(1),
|
||||||
|
TimeSpan.FromSeconds(1)));
|
||||||
|
|
||||||
|
cfg.UseDelayedRedelivery(r => r.Intervals(
|
||||||
|
TimeSpan.FromSeconds(5),
|
||||||
|
TimeSpan.FromSeconds(30),
|
||||||
|
TimeSpan.FromMinutes(2),
|
||||||
|
TimeSpan.FromMinutes(10),
|
||||||
|
TimeSpan.FromMinutes(30)));
|
||||||
|
|
||||||
|
cfg.ConfigureEndpoints(context);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
public class EventBusBuilder<TEventBus> where TEventBus : class, IEventBus
|
|
||||||
{
|
|
||||||
private readonly IServiceCollection _services;
|
|
||||||
private readonly SubscriptionManager _subscriptionManager;
|
|
||||||
|
|
||||||
public EventBusBuilder(IServiceCollection services)
|
|
||||||
{
|
|
||||||
_services = services;
|
|
||||||
_services.AddSingleton<IEventBus, TEventBus>();
|
|
||||||
|
|
||||||
_subscriptionManager = new SubscriptionManager();
|
|
||||||
_services.AddSingleton<SubscriptionManager>(_subscriptionManager);
|
|
||||||
}
|
|
||||||
|
|
||||||
public EventBusBuilder<TEventBus> Subscribe<TEvent, TEventHandler>() where TEvent : IIntegrationEvent where TEventHandler : class, IIntegrationEventHandler<TEvent>
|
|
||||||
{
|
|
||||||
_services.AddKeyedTransient<IIntegrationEventHandler, TEventHandler>(typeof(TEvent).Name);
|
|
||||||
_subscriptionManager.RegisterSubscription<TEvent>();
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
public static class EventBusExtensions
|
|
||||||
{
|
|
||||||
public static EventBusBuilder<TEventBus> AddEventBus<TEventBus>(this IServiceCollection services)
|
|
||||||
where TEventBus : class, IEventBus
|
|
||||||
{
|
|
||||||
return new EventBusBuilder<TEventBus>(services);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
namespace FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
public interface IEventBus
|
|
||||||
{
|
|
||||||
Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IIntegrationEvent;
|
|
||||||
Task Publish(object integrationEvent, string eventType);
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
using NodaTime;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
public interface IIntegrationEvent
|
|
||||||
{
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
namespace FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
public interface IIntegrationEventHandler<in TEvent> : IIntegrationEventHandler where TEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
Task Handle(TEvent @event);
|
|
||||||
Task IIntegrationEventHandler.Handle(IIntegrationEvent @event) => Handle((TEvent)@event);
|
|
||||||
}
|
|
||||||
|
|
||||||
public interface IIntegrationEventHandler
|
|
||||||
{
|
|
||||||
Task Handle(IIntegrationEvent @event);
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
using RabbitMQ.Client;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
|
||||||
|
|
||||||
public class RabbitMQConnectionProvider
|
|
||||||
{
|
|
||||||
private readonly IConnectionFactory _connectionFactory;
|
|
||||||
|
|
||||||
private IConnection Connection { get; set; }
|
|
||||||
private IChannel DefaultChannel { get; set; }
|
|
||||||
|
|
||||||
public RabbitMQConnectionProvider(IConnectionFactory connectionFactory)
|
|
||||||
{
|
|
||||||
_connectionFactory = connectionFactory;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<IConnection> GetConnectionAsync()
|
|
||||||
{
|
|
||||||
if (Connection == null)
|
|
||||||
{
|
|
||||||
Connection = await _connectionFactory.CreateConnectionAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
return Connection;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<IChannel> GetDefaultChannelAsync()
|
|
||||||
{
|
|
||||||
if (DefaultChannel == null)
|
|
||||||
{
|
|
||||||
DefaultChannel = await (await GetConnectionAsync()).CreateChannelAsync();
|
|
||||||
}
|
|
||||||
return DefaultChannel;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,137 +0,0 @@
|
|||||||
using System.Text;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using Newtonsoft.Json;
|
|
||||||
using NodaTime;
|
|
||||||
using NodaTime.Serialization.JsonNet;
|
|
||||||
using RabbitMQ.Client;
|
|
||||||
using RabbitMQ.Client.Events;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
|
||||||
|
|
||||||
public class RabbitMQEventBus : IEventBus, IHostedService
|
|
||||||
{
|
|
||||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
|
||||||
private readonly RabbitMQConnectionProvider _connectionProvider;
|
|
||||||
private readonly RabbitMQOptions _options;
|
|
||||||
private readonly SubscriptionManager _subscriptionManager;
|
|
||||||
private readonly ILogger<RabbitMQEventBus> _logger;
|
|
||||||
|
|
||||||
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)
|
|
||||||
{
|
|
||||||
_serviceScopeFactory = serviceScopeFactory;
|
|
||||||
_connectionProvider = connectionProvider;
|
|
||||||
_subscriptionManager = subscriptionManager;
|
|
||||||
_logger = logger;
|
|
||||||
_options = options.Value;
|
|
||||||
_jsonSerializerSettings = new JsonSerializerSettings().ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
var routingKey = typeof(TEvent).Name;
|
|
||||||
|
|
||||||
await Publish(integrationEvent, routingKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Publish(object integrationEvent, string eventType)
|
|
||||||
{
|
|
||||||
var channel = await _connectionProvider.GetDefaultChannelAsync();
|
|
||||||
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(integrationEvent));
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task StartAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
_ = Task.Factory.StartNew(async () =>
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var channel = await _connectionProvider.GetDefaultChannelAsync();
|
|
||||||
await channel.ExchangeDeclareAsync(ExchangeName, ExchangeType.Direct,
|
|
||||||
cancellationToken: cancellationToken);
|
|
||||||
|
|
||||||
await channel.BasicQosAsync(prefetchSize: 0, prefetchCount: 1, global: false, cancellationToken: cancellationToken);
|
|
||||||
await channel.QueueDeclareAsync(_options.ClientIdentifier, true, false, false,
|
|
||||||
cancellationToken: cancellationToken);
|
|
||||||
var consumer = new AsyncEventingBasicConsumer(channel);
|
|
||||||
consumer.ReceivedAsync += (sender, @event) =>
|
|
||||||
{
|
|
||||||
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,
|
|
||||||
cancellationToken: cancellationToken);
|
|
||||||
_logger.LogInformation("Subscribed to {SubscriptionKey}", subscription.Key);
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.LogInformation("RabbitMQ EventBus started.");
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
_logger.LogError(e, "An error occurred while starting the RabbitMQ EventBus");
|
|
||||||
}
|
|
||||||
}, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task StopAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task OnReceivedEvent(object sender, BasicDeliverEventArgs @event, IChannel channel)
|
|
||||||
{
|
|
||||||
var eventName = @event.RoutingKey;
|
|
||||||
_logger.LogInformation("Received event {EventName}", eventName);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (!_subscriptionManager.Subscriptions.ContainsKey(eventName))
|
|
||||||
{
|
|
||||||
_logger.LogWarning("Received event without subscription entry.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var eventBody = Encoding.UTF8.GetString(@event.Body.Span);
|
|
||||||
var eventObject = JsonConvert.DeserializeObject(eventBody, _subscriptionManager.Subscriptions[eventName], _jsonSerializerSettings) as IIntegrationEvent;
|
|
||||||
|
|
||||||
using var scope = _serviceScopeFactory.CreateScope();
|
|
||||||
|
|
||||||
foreach (var service in scope.ServiceProvider.GetKeyedServices<IIntegrationEventHandler>(eventName))
|
|
||||||
{
|
|
||||||
await service.Handle(eventObject);
|
|
||||||
}
|
|
||||||
_logger.LogInformation("Finished handling event with name {EventName}", eventName);
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
_logger.LogError(e, "An error occurred while handling an event.");
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
await channel.BasicAckAsync(@event.DeliveryTag, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using RabbitMQ.Client;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
|
||||||
|
|
||||||
public static class RabbitMQExtensions
|
|
||||||
{
|
|
||||||
public static EventBusBuilder<RabbitMQEventBus> AddRabbitMQ(this IServiceCollection services, Action<RabbitMQOptions> configure)
|
|
||||||
{
|
|
||||||
services.Configure(configure);
|
|
||||||
services.AddSingleton<IConnectionFactory, ConnectionFactory>(provider =>
|
|
||||||
{
|
|
||||||
var options = provider.GetService<IOptions<RabbitMQOptions>>();
|
|
||||||
ConnectionFactory factory = new ConnectionFactory();
|
|
||||||
factory.Uri = new Uri(options.Value.ConnectionString);
|
|
||||||
return factory;
|
|
||||||
});
|
|
||||||
services.AddSingleton<RabbitMQConnectionProvider>();
|
|
||||||
services.AddHostedService<RabbitMQEventBus>();
|
|
||||||
return services.AddEventBus<RabbitMQEventBus>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
namespace FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
|
||||||
|
|
||||||
public class RabbitMQOptions
|
|
||||||
{
|
|
||||||
public string ConnectionString { get; set; }
|
|
||||||
public string ClientIdentifier { get; set; }
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
namespace FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
public class SubscriptionManager
|
|
||||||
{
|
|
||||||
public Dictionary<string, Type> Subscriptions { get; } = new Dictionary<string, Type>();
|
|
||||||
|
|
||||||
public void RegisterSubscription<TEvent>()
|
|
||||||
{
|
|
||||||
Subscriptions.Add(typeof(TEvent).Name, typeof(TEvent));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -23,6 +23,7 @@
|
|||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||||
<PackageReference Include="DeepL.net" Version="1.17.0" />
|
<PackageReference Include="DeepL.net" Version="1.17.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2"/>
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2"/>
|
||||||
|
<PackageReference Include="MassTransit" Version="8.4.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
using FictionArchive.Common.Enums;
|
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
using FictionArchive.Service.TranslationService.Models.Enums;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.TranslationService.Models.IntegrationEvents;
|
|
||||||
|
|
||||||
public class TranslationRequestCompletedEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Maps this event back to a triggering request.
|
|
||||||
/// </summary>
|
|
||||||
public Guid? TranslationRequestId { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// The resulting text.
|
|
||||||
/// </summary>
|
|
||||||
public string? TranslatedText { get; set; }
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
using FictionArchive.Common.Enums;
|
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.TranslationService.Models.IntegrationEvents;
|
|
||||||
|
|
||||||
public class TranslationRequestCreatedEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
public Guid TranslationRequestId { get; set; }
|
|
||||||
public Language From { get; set; }
|
|
||||||
public Language To { get; set; }
|
|
||||||
public string Body { get; set; }
|
|
||||||
public string TranslationEngineKey { get; set; }
|
|
||||||
}
|
|
||||||
@@ -2,16 +2,14 @@ using DeepL;
|
|||||||
using FictionArchive.Common.Extensions;
|
using FictionArchive.Common.Extensions;
|
||||||
using FictionArchive.Service.Shared;
|
using FictionArchive.Service.Shared;
|
||||||
using FictionArchive.Service.Shared.Extensions;
|
using FictionArchive.Service.Shared.Extensions;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
using FictionArchive.Service.Shared.MassTransit;
|
||||||
using FictionArchive.Service.Shared.Services.GraphQL;
|
using FictionArchive.Service.Shared.Services.GraphQL;
|
||||||
using FictionArchive.Service.TranslationService.GraphQL;
|
using FictionArchive.Service.TranslationService.GraphQL;
|
||||||
using FictionArchive.Service.TranslationService.Models.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.TranslationService.Services;
|
using FictionArchive.Service.TranslationService.Services;
|
||||||
using FictionArchive.Service.TranslationService.Services.Database;
|
using FictionArchive.Service.TranslationService.Services.Database;
|
||||||
using FictionArchive.Service.TranslationService.Services.EventHandlers;
|
using FictionArchive.Service.TranslationService.Services.EventHandlers;
|
||||||
using FictionArchive.Service.TranslationService.Services.TranslationEngines;
|
using FictionArchive.Service.TranslationService.Services.TranslationEngines;
|
||||||
using FictionArchive.Service.TranslationService.Services.TranslationEngines.DeepLTranslate;
|
using FictionArchive.Service.TranslationService.Services.TranslationEngines.DeepLTranslate;
|
||||||
using RabbitMQ.Client;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.TranslationService;
|
namespace FictionArchive.Service.TranslationService;
|
||||||
|
|
||||||
@@ -26,15 +24,16 @@ public class Program
|
|||||||
|
|
||||||
builder.Services.AddHealthChecks();
|
builder.Services.AddHealthChecks();
|
||||||
|
|
||||||
#region Event Bus
|
#region MassTransit
|
||||||
|
|
||||||
if (!isSchemaExport)
|
if (!isSchemaExport)
|
||||||
{
|
{
|
||||||
builder.Services.AddRabbitMQ(opt =>
|
builder.Services.AddFictionArchiveMassTransit<TranslationServiceDbContext>(
|
||||||
{
|
builder.Configuration,
|
||||||
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
|
x =>
|
||||||
})
|
{
|
||||||
.Subscribe<TranslationRequestCreatedEvent, TranslationRequestCreatedEventHandler>();
|
x.AddConsumer<TranslateTextCommandConsumer>();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||||
|
using FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||||
|
using FictionArchive.Service.TranslationService.Models.Enums;
|
||||||
|
using MassTransit;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.TranslationService.Services.EventHandlers;
|
||||||
|
|
||||||
|
public class TranslateTextCommandConsumer : IConsumer<TranslateTextCommand>
|
||||||
|
{
|
||||||
|
private readonly ILogger<TranslateTextCommandConsumer> _logger;
|
||||||
|
private readonly TranslationEngineService _translationEngineService;
|
||||||
|
|
||||||
|
public TranslateTextCommandConsumer(
|
||||||
|
ILogger<TranslateTextCommandConsumer> logger,
|
||||||
|
TranslationEngineService translationEngineService)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
_translationEngineService = translationEngineService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Consume(ConsumeContext<TranslateTextCommand> context)
|
||||||
|
{
|
||||||
|
var command = context.Message;
|
||||||
|
|
||||||
|
var result = await _translationEngineService.Translate(
|
||||||
|
command.From,
|
||||||
|
command.To,
|
||||||
|
command.Body,
|
||||||
|
command.TranslationEngineKey);
|
||||||
|
|
||||||
|
if (result.Status == TranslationRequestStatus.Success)
|
||||||
|
{
|
||||||
|
await context.Publish(new TranslationCompletedEvent
|
||||||
|
{
|
||||||
|
TranslatedText = result.TranslatedText!,
|
||||||
|
TranslationRequestId = command.TranslationRequestId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
using FictionArchive.Service.TranslationService.Models.Enums;
|
|
||||||
using FictionArchive.Service.TranslationService.Models.IntegrationEvents;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.TranslationService.Services.EventHandlers;
|
|
||||||
|
|
||||||
public class TranslationRequestCreatedEventHandler : IIntegrationEventHandler<TranslationRequestCreatedEvent>
|
|
||||||
{
|
|
||||||
private readonly ILogger<TranslationRequestCreatedEventHandler> _logger;
|
|
||||||
private readonly TranslationEngineService _translationEngineService;
|
|
||||||
private readonly IEventBus _eventBus;
|
|
||||||
|
|
||||||
public TranslationRequestCreatedEventHandler(ILogger<TranslationRequestCreatedEventHandler> logger, TranslationEngineService translationEngineService)
|
|
||||||
{
|
|
||||||
_logger = logger;
|
|
||||||
_translationEngineService = translationEngineService;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task Handle(TranslationRequestCreatedEvent @event)
|
|
||||||
{
|
|
||||||
var result = await _translationEngineService.Translate(@event.From, @event.To, @event.Body, @event.TranslationEngineKey);
|
|
||||||
if (result.Status == TranslationRequestStatus.Success)
|
|
||||||
{
|
|
||||||
await _eventBus.Publish(new TranslationRequestCompletedEvent()
|
|
||||||
{
|
|
||||||
TranslatedText = result.TranslatedText,
|
|
||||||
TranslationRequestId = @event.TranslationRequestId,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +1,21 @@
|
|||||||
using System.Text;
|
|
||||||
using FictionArchive.Common.Enums;
|
using FictionArchive.Common.Enums;
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
|
|
||||||
using FictionArchive.Service.TranslationService.Models;
|
using FictionArchive.Service.TranslationService.Models;
|
||||||
using FictionArchive.Service.TranslationService.Models.Database;
|
using FictionArchive.Service.TranslationService.Models.Database;
|
||||||
using FictionArchive.Service.TranslationService.Models.Enums;
|
using FictionArchive.Service.TranslationService.Models.Enums;
|
||||||
using FictionArchive.Service.TranslationService.Models.IntegrationEvents;
|
|
||||||
using FictionArchive.Service.TranslationService.Services.Database;
|
using FictionArchive.Service.TranslationService.Services.Database;
|
||||||
using FictionArchive.Service.TranslationService.Services.TranslationEngines;
|
using FictionArchive.Service.TranslationService.Services.TranslationEngines;
|
||||||
using RabbitMQ.Client;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.TranslationService.Services;
|
namespace FictionArchive.Service.TranslationService.Services;
|
||||||
|
|
||||||
public class TranslationEngineService
|
public class TranslationEngineService
|
||||||
{
|
{
|
||||||
private readonly IEnumerable<ITranslationEngine> _translationEngines;
|
private readonly IEnumerable<ITranslationEngine> _translationEngines;
|
||||||
private readonly IEventBus _eventBus;
|
|
||||||
private readonly TranslationServiceDbContext _dbContext;
|
private readonly TranslationServiceDbContext _dbContext;
|
||||||
|
|
||||||
public TranslationEngineService(IEnumerable<ITranslationEngine> translationEngines, TranslationServiceDbContext dbContext, IEventBus eventBus)
|
public TranslationEngineService(IEnumerable<ITranslationEngine> translationEngines, TranslationServiceDbContext dbContext)
|
||||||
{
|
{
|
||||||
_translationEngines = translationEngines;
|
_translationEngines = translationEngines;
|
||||||
_dbContext = dbContext;
|
_dbContext = dbContext;
|
||||||
_eventBus = eventBus;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<TranslationResult> Translate(Language from, Language to, string text, string translationEngineKey)
|
public async Task<TranslationResult> Translate(Language from, Language to, string text, string translationEngineKey)
|
||||||
|
|||||||
@@ -12,8 +12,10 @@
|
|||||||
"DefaultConnection": "Host=localhost;Database=FictionArchive_NovelService;Username=postgres;password=postgres"
|
"DefaultConnection": "Host=localhost;Database=FictionArchive_NovelService;Username=postgres;password=postgres"
|
||||||
},
|
},
|
||||||
"RabbitMQ": {
|
"RabbitMQ": {
|
||||||
"ConnectionString": "amqp://localhost",
|
"Host": "localhost",
|
||||||
"ClientIdentifier": "TranslationService"
|
"VirtualHost": "/",
|
||||||
|
"Username": "guest",
|
||||||
|
"Password": "guest"
|
||||||
},
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
"OIDC": {
|
"OIDC": {
|
||||||
|
|||||||
@@ -106,4 +106,393 @@ public class Mutation
|
|||||||
|
|
||||||
return new BookmarkPayload { Success = true };
|
return new BookmarkPayload { Success = true };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
[Error<InvalidOperationException>]
|
||||||
|
public async Task<ReadingListPayload> CreateReadingList(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal,
|
||||||
|
CreateReadingListInput input)
|
||||||
|
{
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Unable to determine current user identity");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(input.Name))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Reading list name is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.Users
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
user = new User { OAuthProviderId = oAuthProviderId };
|
||||||
|
dbContext.Users.Add(user);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
var readingList = new ReadingList
|
||||||
|
{
|
||||||
|
UserId = user.Id,
|
||||||
|
Name = input.Name.Trim(),
|
||||||
|
Description = input.Description?.Trim()
|
||||||
|
};
|
||||||
|
|
||||||
|
dbContext.ReadingLists.Add(readingList);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
return new ReadingListPayload
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
ReadingList = new ReadingListDto
|
||||||
|
{
|
||||||
|
Id = readingList.Id,
|
||||||
|
Name = readingList.Name,
|
||||||
|
Description = readingList.Description,
|
||||||
|
Items = [],
|
||||||
|
ItemCount = 0,
|
||||||
|
CreatedTime = readingList.CreatedTime
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
[Error<InvalidOperationException>]
|
||||||
|
public async Task<ReadingListPayload> UpdateReadingList(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal,
|
||||||
|
UpdateReadingListInput input)
|
||||||
|
{
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Unable to determine current user identity");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(input.Name))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Reading list name is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.Users
|
||||||
|
.AsNoTracking()
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return new ReadingListPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
var readingList = await dbContext.ReadingLists
|
||||||
|
.Include(r => r.Items)
|
||||||
|
.FirstOrDefaultAsync(r => r.Id == input.Id && r.UserId == user.Id);
|
||||||
|
|
||||||
|
if (readingList == null)
|
||||||
|
{
|
||||||
|
return new ReadingListPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
readingList.Name = input.Name.Trim();
|
||||||
|
readingList.Description = input.Description?.Trim();
|
||||||
|
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
return new ReadingListPayload
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
ReadingList = new ReadingListDto
|
||||||
|
{
|
||||||
|
Id = readingList.Id,
|
||||||
|
Name = readingList.Name,
|
||||||
|
Description = readingList.Description,
|
||||||
|
Items = readingList.Items.OrderBy(i => i.Order).Select(i => new ReadingListItemDto
|
||||||
|
{
|
||||||
|
NovelId = i.NovelId,
|
||||||
|
Order = i.Order,
|
||||||
|
AddedTime = i.CreatedTime
|
||||||
|
}),
|
||||||
|
ItemCount = readingList.Items.Count,
|
||||||
|
CreatedTime = readingList.CreatedTime
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
[Error<InvalidOperationException>]
|
||||||
|
public async Task<DeleteReadingListPayload> DeleteReadingList(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal,
|
||||||
|
int id)
|
||||||
|
{
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Unable to determine current user identity");
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.Users
|
||||||
|
.AsNoTracking()
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return new DeleteReadingListPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
var readingList = await dbContext.ReadingLists
|
||||||
|
.FirstOrDefaultAsync(r => r.Id == id && r.UserId == user.Id);
|
||||||
|
|
||||||
|
if (readingList == null)
|
||||||
|
{
|
||||||
|
return new DeleteReadingListPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
dbContext.ReadingLists.Remove(readingList);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
return new DeleteReadingListPayload { Success = true };
|
||||||
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
[Error<InvalidOperationException>]
|
||||||
|
public async Task<ReadingListPayload> AddToReadingList(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal,
|
||||||
|
AddToReadingListInput input)
|
||||||
|
{
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Unable to determine current user identity");
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.Users
|
||||||
|
.AsNoTracking()
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return new ReadingListPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
var readingList = await dbContext.ReadingLists
|
||||||
|
.Include(r => r.Items)
|
||||||
|
.FirstOrDefaultAsync(r => r.Id == input.ReadingListId && r.UserId == user.Id);
|
||||||
|
|
||||||
|
if (readingList == null)
|
||||||
|
{
|
||||||
|
return new ReadingListPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Idempotent: if already in list, return success
|
||||||
|
var existingItem = readingList.Items.FirstOrDefault(i => i.NovelId == input.NovelId);
|
||||||
|
if (existingItem != null)
|
||||||
|
{
|
||||||
|
return new ReadingListPayload
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
ReadingList = new ReadingListDto
|
||||||
|
{
|
||||||
|
Id = readingList.Id,
|
||||||
|
Name = readingList.Name,
|
||||||
|
Description = readingList.Description,
|
||||||
|
Items = readingList.Items.OrderBy(i => i.Order).Select(i => new ReadingListItemDto
|
||||||
|
{
|
||||||
|
NovelId = i.NovelId,
|
||||||
|
Order = i.Order,
|
||||||
|
AddedTime = i.CreatedTime
|
||||||
|
}),
|
||||||
|
ItemCount = readingList.Items.Count,
|
||||||
|
CreatedTime = readingList.CreatedTime
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add at the end (highest order + 1)
|
||||||
|
var maxOrder = readingList.Items.Any() ? readingList.Items.Max(i => i.Order) : -1;
|
||||||
|
var newItem = new ReadingListItem
|
||||||
|
{
|
||||||
|
ReadingListId = readingList.Id,
|
||||||
|
NovelId = input.NovelId,
|
||||||
|
Order = maxOrder + 1
|
||||||
|
};
|
||||||
|
|
||||||
|
dbContext.ReadingListItems.Add(newItem);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
// Reload to get updated items
|
||||||
|
readingList = await dbContext.ReadingLists
|
||||||
|
.AsNoTracking()
|
||||||
|
.Include(r => r.Items.OrderBy(i => i.Order))
|
||||||
|
.FirstAsync(r => r.Id == input.ReadingListId);
|
||||||
|
|
||||||
|
return new ReadingListPayload
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
ReadingList = new ReadingListDto
|
||||||
|
{
|
||||||
|
Id = readingList.Id,
|
||||||
|
Name = readingList.Name,
|
||||||
|
Description = readingList.Description,
|
||||||
|
Items = readingList.Items.Select(i => new ReadingListItemDto
|
||||||
|
{
|
||||||
|
NovelId = i.NovelId,
|
||||||
|
Order = i.Order,
|
||||||
|
AddedTime = i.CreatedTime
|
||||||
|
}),
|
||||||
|
ItemCount = readingList.Items.Count,
|
||||||
|
CreatedTime = readingList.CreatedTime
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
[Error<InvalidOperationException>]
|
||||||
|
public async Task<ReadingListPayload> RemoveFromReadingList(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal,
|
||||||
|
int listId,
|
||||||
|
uint novelId)
|
||||||
|
{
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Unable to determine current user identity");
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.Users
|
||||||
|
.AsNoTracking()
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return new ReadingListPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
var readingList = await dbContext.ReadingLists
|
||||||
|
.Include(r => r.Items)
|
||||||
|
.FirstOrDefaultAsync(r => r.Id == listId && r.UserId == user.Id);
|
||||||
|
|
||||||
|
if (readingList == null)
|
||||||
|
{
|
||||||
|
return new ReadingListPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
var item = readingList.Items.FirstOrDefault(i => i.NovelId == novelId);
|
||||||
|
if (item != null)
|
||||||
|
{
|
||||||
|
dbContext.ReadingListItems.Remove(item);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reload to get updated items
|
||||||
|
readingList = await dbContext.ReadingLists
|
||||||
|
.AsNoTracking()
|
||||||
|
.Include(r => r.Items.OrderBy(i => i.Order))
|
||||||
|
.FirstAsync(r => r.Id == listId);
|
||||||
|
|
||||||
|
return new ReadingListPayload
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
ReadingList = new ReadingListDto
|
||||||
|
{
|
||||||
|
Id = readingList.Id,
|
||||||
|
Name = readingList.Name,
|
||||||
|
Description = readingList.Description,
|
||||||
|
Items = readingList.Items.Select(i => new ReadingListItemDto
|
||||||
|
{
|
||||||
|
NovelId = i.NovelId,
|
||||||
|
Order = i.Order,
|
||||||
|
AddedTime = i.CreatedTime
|
||||||
|
}),
|
||||||
|
ItemCount = readingList.Items.Count,
|
||||||
|
CreatedTime = readingList.CreatedTime
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
[Error<InvalidOperationException>]
|
||||||
|
public async Task<ReadingListPayload> ReorderReadingListItem(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal,
|
||||||
|
ReorderReadingListItemInput input)
|
||||||
|
{
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Unable to determine current user identity");
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.Users
|
||||||
|
.AsNoTracking()
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return new ReadingListPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
var readingList = await dbContext.ReadingLists
|
||||||
|
.Include(r => r.Items)
|
||||||
|
.FirstOrDefaultAsync(r => r.Id == input.ReadingListId && r.UserId == user.Id);
|
||||||
|
|
||||||
|
if (readingList == null)
|
||||||
|
{
|
||||||
|
return new ReadingListPayload { Success = false };
|
||||||
|
}
|
||||||
|
|
||||||
|
var item = readingList.Items.FirstOrDefault(i => i.NovelId == input.NovelId);
|
||||||
|
if (item == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Novel not found in reading list");
|
||||||
|
}
|
||||||
|
|
||||||
|
var oldOrder = item.Order;
|
||||||
|
var newOrder = input.NewOrder;
|
||||||
|
|
||||||
|
// Shift other items
|
||||||
|
if (newOrder < oldOrder)
|
||||||
|
{
|
||||||
|
// Moving up: shift items between newOrder and oldOrder down
|
||||||
|
foreach (var i in readingList.Items.Where(x => x.Order >= newOrder && x.Order < oldOrder))
|
||||||
|
{
|
||||||
|
i.Order++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (newOrder > oldOrder)
|
||||||
|
{
|
||||||
|
// Moving down: shift items between oldOrder and newOrder up
|
||||||
|
foreach (var i in readingList.Items.Where(x => x.Order > oldOrder && x.Order <= newOrder))
|
||||||
|
{
|
||||||
|
i.Order--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
item.Order = newOrder;
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
return new ReadingListPayload
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
ReadingList = new ReadingListDto
|
||||||
|
{
|
||||||
|
Id = readingList.Id,
|
||||||
|
Name = readingList.Name,
|
||||||
|
Description = readingList.Description,
|
||||||
|
Items = readingList.Items.OrderBy(i => i.Order).Select(i => new ReadingListItemDto
|
||||||
|
{
|
||||||
|
NovelId = i.NovelId,
|
||||||
|
Order = i.Order,
|
||||||
|
AddedTime = i.CreatedTime
|
||||||
|
}),
|
||||||
|
ItemCount = readingList.Items.Count,
|
||||||
|
CreatedTime = readingList.CreatedTime
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
using FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
using FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
using FictionArchive.Service.UserNovelDataService.Services;
|
using FictionArchive.Service.UserNovelDataService.Services;
|
||||||
using HotChocolate.Authorization;
|
using HotChocolate.Authorization;
|
||||||
@@ -42,4 +43,94 @@ public class Query
|
|||||||
CreatedTime = b.CreatedTime
|
CreatedTime = b.CreatedTime
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
public async Task<IEnumerable<ReadingListDto>> GetReadingLists(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal)
|
||||||
|
{
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.Users
|
||||||
|
.AsNoTracking()
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var lists = await dbContext.ReadingLists
|
||||||
|
.AsNoTracking()
|
||||||
|
.Include(r => r.Items)
|
||||||
|
.Where(r => r.UserId == user.Id)
|
||||||
|
.OrderByDescending(r => r.LastUpdatedTime)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
return lists.Select(r => new ReadingListDto
|
||||||
|
{
|
||||||
|
Id = r.Id,
|
||||||
|
Name = r.Name,
|
||||||
|
Description = r.Description,
|
||||||
|
ItemCount = r.Items.Count,
|
||||||
|
Items = r.Items.Select(i => new ReadingListItemDto
|
||||||
|
{
|
||||||
|
NovelId = i.NovelId,
|
||||||
|
Order = i.Order,
|
||||||
|
AddedTime = i.CreatedTime
|
||||||
|
}),
|
||||||
|
CreatedTime = r.CreatedTime
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Authorize]
|
||||||
|
public async Task<ReadingListDto?> GetReadingList(
|
||||||
|
UserNovelDataServiceDbContext dbContext,
|
||||||
|
ClaimsPrincipal claimsPrincipal,
|
||||||
|
int id)
|
||||||
|
{
|
||||||
|
var oAuthProviderId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||||
|
if (string.IsNullOrEmpty(oAuthProviderId))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await dbContext.Users
|
||||||
|
.AsNoTracking()
|
||||||
|
.FirstOrDefaultAsync(u => u.OAuthProviderId == oAuthProviderId);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var readingList = await dbContext.ReadingLists
|
||||||
|
.AsNoTracking()
|
||||||
|
.Include(r => r.Items.OrderBy(i => i.Order))
|
||||||
|
.FirstOrDefaultAsync(r => r.Id == id && r.UserId == user.Id);
|
||||||
|
|
||||||
|
if (readingList == null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ReadingListDto
|
||||||
|
{
|
||||||
|
Id = readingList.Id,
|
||||||
|
Name = readingList.Name,
|
||||||
|
Description = readingList.Description,
|
||||||
|
ItemCount = readingList.Items.Count,
|
||||||
|
Items = readingList.Items.Select(i => new ReadingListItemDto
|
||||||
|
{
|
||||||
|
NovelId = i.NovelId,
|
||||||
|
Order = i.Order,
|
||||||
|
AddedTime = i.CreatedTime
|
||||||
|
}),
|
||||||
|
CreatedTime = readingList.CreatedTime
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
289
FictionArchive.Service.UserNovelDataService/Migrations/20260120014840_AddReadingLists.Designer.cs
generated
Normal file
289
FictionArchive.Service.UserNovelDataService/Migrations/20260120014840_AddReadingLists.Designer.cs
generated
Normal file
@@ -0,0 +1,289 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using FictionArchive.Service.UserNovelDataService.Services;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
using NodaTime;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(UserNovelDataServiceDbContext))]
|
||||||
|
[Migration("20260120014840_AddReadingLists")]
|
||||||
|
partial class AddReadingLists
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder
|
||||||
|
.HasAnnotation("ProductVersion", "9.0.11")
|
||||||
|
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||||
|
|
||||||
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Bookmark", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<long>("ChapterId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("NovelId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("UserId", "ChapterId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.HasIndex("UserId", "NovelId");
|
||||||
|
|
||||||
|
b.ToTable("Bookmarks");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Chapter", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("VolumeId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("VolumeId");
|
||||||
|
|
||||||
|
b.ToTable("Chapters");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Novel", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Novels");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingList", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("UserId");
|
||||||
|
|
||||||
|
b.ToTable("ReadingLists");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingListItem", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("NovelId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<int>("Order")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<int>("ReadingListId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("ReadingListId", "NovelId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.HasIndex("ReadingListId", "Order");
|
||||||
|
|
||||||
|
b.ToTable("ReadingListItems");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.User", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("OAuthProviderId")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Users");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("NovelId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("NovelId");
|
||||||
|
|
||||||
|
b.ToTable("Volumes");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Bookmark", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.User", "User")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("UserId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("User");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Chapter", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", "Volume")
|
||||||
|
.WithMany("Chapters")
|
||||||
|
.HasForeignKey("VolumeId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Volume");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingList", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.User", "User")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("UserId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("User");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingListItem", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingList", "ReadingList")
|
||||||
|
.WithMany("Items")
|
||||||
|
.HasForeignKey("ReadingListId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("ReadingList");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.Novel", "Novel")
|
||||||
|
.WithMany("Volumes")
|
||||||
|
.HasForeignKey("NovelId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Novel");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Novel", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Volumes");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingList", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Items");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Chapters");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using NodaTime;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddReadingLists : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "ReadingLists",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<int>(type: "integer", nullable: false)
|
||||||
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
|
UserId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
Name = table.Column<string>(type: "text", nullable: false),
|
||||||
|
Description = table.Column<string>(type: "text", nullable: true),
|
||||||
|
CreatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
|
||||||
|
LastUpdatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_ReadingLists", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_ReadingLists_Users_UserId",
|
||||||
|
column: x => x.UserId,
|
||||||
|
principalTable: "Users",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "ReadingListItems",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<int>(type: "integer", nullable: false)
|
||||||
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
|
ReadingListId = table.Column<int>(type: "integer", nullable: false),
|
||||||
|
NovelId = table.Column<long>(type: "bigint", nullable: false),
|
||||||
|
Order = table.Column<int>(type: "integer", nullable: false),
|
||||||
|
CreatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
|
||||||
|
LastUpdatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_ReadingListItems", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_ReadingListItems_ReadingLists_ReadingListId",
|
||||||
|
column: x => x.ReadingListId,
|
||||||
|
principalTable: "ReadingLists",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_ReadingListItems_ReadingListId_NovelId",
|
||||||
|
table: "ReadingListItems",
|
||||||
|
columns: new[] { "ReadingListId", "NovelId" },
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_ReadingListItems_ReadingListId_Order",
|
||||||
|
table: "ReadingListItems",
|
||||||
|
columns: new[] { "ReadingListId", "Order" });
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_ReadingLists_UserId",
|
||||||
|
table: "ReadingLists",
|
||||||
|
column: "UserId");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "ReadingListItems");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "ReadingLists");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -102,6 +102,70 @@ namespace FictionArchive.Service.UserNovelDataService.Migrations
|
|||||||
b.ToTable("Novels");
|
b.ToTable("Novels");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingList", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("UserId");
|
||||||
|
|
||||||
|
b.ToTable("ReadingLists");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingListItem", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<Instant>("CreatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<Instant>("LastUpdatedTime")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<long>("NovelId")
|
||||||
|
.HasColumnType("bigint");
|
||||||
|
|
||||||
|
b.Property<int>("Order")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<int>("ReadingListId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("ReadingListId", "NovelId")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.HasIndex("ReadingListId", "Order");
|
||||||
|
|
||||||
|
b.ToTable("ReadingListItems");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.User", b =>
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.User", b =>
|
||||||
{
|
{
|
||||||
b.Property<Guid>("Id")
|
b.Property<Guid>("Id")
|
||||||
@@ -169,6 +233,28 @@ namespace FictionArchive.Service.UserNovelDataService.Migrations
|
|||||||
b.Navigation("Volume");
|
b.Navigation("Volume");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingList", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.User", "User")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("UserId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("User");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingListItem", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingList", "ReadingList")
|
||||||
|
.WithMany("Items")
|
||||||
|
.HasForeignKey("ReadingListId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("ReadingList");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.Novel", "Novel")
|
b.HasOne("FictionArchive.Service.UserNovelDataService.Models.Database.Novel", "Novel")
|
||||||
@@ -185,6 +271,11 @@ namespace FictionArchive.Service.UserNovelDataService.Migrations
|
|||||||
b.Navigation("Volumes");
|
b.Navigation("Volumes");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.ReadingList", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Items");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
modelBuilder.Entity("FictionArchive.Service.UserNovelDataService.Models.Database.Volume", b =>
|
||||||
{
|
{
|
||||||
b.Navigation("Chapters");
|
b.Navigation("Chapters");
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
|
||||||
|
public record AddToReadingListInput(int ReadingListId, uint NovelId);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
|
||||||
|
public record CreateReadingListInput(string Name, string? Description);
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
|
||||||
|
public class DeleteReadingListPayload
|
||||||
|
{
|
||||||
|
public bool Success { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using NodaTime;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
|
||||||
|
public class ReadingListDto
|
||||||
|
{
|
||||||
|
public int Id { get; init; }
|
||||||
|
public required string Name { get; init; }
|
||||||
|
public string? Description { get; init; }
|
||||||
|
public IEnumerable<ReadingListItemDto> Items { get; init; } = [];
|
||||||
|
public int ItemCount { get; init; }
|
||||||
|
public Instant CreatedTime { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
using NodaTime;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
|
||||||
|
public class ReadingListItemDto
|
||||||
|
{
|
||||||
|
public uint NovelId { get; init; }
|
||||||
|
public int Order { get; init; }
|
||||||
|
public Instant AddedTime { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
|
||||||
|
public class ReadingListPayload
|
||||||
|
{
|
||||||
|
public ReadingListDto? ReadingList { get; init; }
|
||||||
|
public bool Success { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
|
||||||
|
public record ReorderReadingListItemInput(int ReadingListId, uint NovelId, int NewOrder);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.DTOs;
|
||||||
|
|
||||||
|
public record UpdateReadingListInput(int Id, string Name, string? Description);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using FictionArchive.Service.Shared.Models;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
|
||||||
|
public class ReadingList : BaseEntity<int>
|
||||||
|
{
|
||||||
|
public Guid UserId { get; set; }
|
||||||
|
public virtual User User { get; set; } = null!;
|
||||||
|
|
||||||
|
public required string Name { get; set; }
|
||||||
|
public string? Description { get; set; }
|
||||||
|
|
||||||
|
public virtual ICollection<ReadingListItem> Items { get; set; } = new List<ReadingListItem>();
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
using FictionArchive.Service.Shared.Models;
|
||||||
|
|
||||||
|
namespace FictionArchive.Service.UserNovelDataService.Models.Database;
|
||||||
|
|
||||||
|
public class ReadingListItem : BaseEntity<int>
|
||||||
|
{
|
||||||
|
public int ReadingListId { get; set; }
|
||||||
|
public virtual ReadingList ReadingList { get; set; } = null!;
|
||||||
|
|
||||||
|
public uint NovelId { get; set; }
|
||||||
|
public int Order { get; set; }
|
||||||
|
}
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.UserNovelDataService.Models.IntegrationEvents;
|
|
||||||
|
|
||||||
public class ChapterCreatedEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
public required uint ChapterId { get; init; }
|
|
||||||
public required uint NovelId { get; init; }
|
|
||||||
public required uint VolumeId { get; init; }
|
|
||||||
public required int VolumeOrder { get; init; }
|
|
||||||
public required uint ChapterOrder { get; init; }
|
|
||||||
public required string ChapterTitle { get; init; }
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
using FictionArchive.Common.Enums;
|
|
||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.UserNovelDataService.Models.IntegrationEvents;
|
|
||||||
|
|
||||||
public class NovelCreatedEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
public required uint NovelId { get; init; }
|
|
||||||
public required string Title { get; init; }
|
|
||||||
public required Language OriginalLanguage { get; init; }
|
|
||||||
public required string Source { get; init; }
|
|
||||||
public required string AuthorName { get; init; }
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
using FictionArchive.Service.Shared.Services.EventBus;
|
|
||||||
|
|
||||||
namespace FictionArchive.Service.UserNovelDataService.Models.IntegrationEvents;
|
|
||||||
|
|
||||||
public class UserInvitedEvent : IIntegrationEvent
|
|
||||||
{
|
|
||||||
public Guid InvitedUserId { get; set; }
|
|
||||||
public required string InvitedUsername { get; set; }
|
|
||||||
public required string InvitedEmail { get; set; }
|
|
||||||
public required string InvitedOAuthProviderId { get; set; }
|
|
||||||
|
|
||||||
public Guid InviterId { get; set; }
|
|
||||||
public required string InviterUsername { get; set; }
|
|
||||||
public required string InviterOAuthProviderId { get; set; }
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user