Moves media library scanning to domain layer

This commit is contained in:
BinaryAlley committed 2025-02-16 21:45:26 +02:00
1 parent 8b51abe0b2
commit c4246d2e69
209 files changed
+3793 -641

No files matched your search

@@ -9,7 +9,7 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
/// <summary>
/// Domain event raised when a libary is deleted.
/// </summary>
/// <param name="Id">The Id of the domain event.</param>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="Library">The library that was deleted.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {Library.Id} Title: {Library.Title}")]
@@ -9,7 +9,7 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
/// <summary>
/// Domain event raised when a libary is created or updated.
/// </summary>
/// <param name="Id">The Id of the domain event.</param>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="Library">The library that was created or updated.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {Library.Id} Title: {Library.Title}")]
@@ -5,6 +5,8 @@ using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using System;
using System.Collections.Generic;
@@ -17,13 +19,14 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
/// <summary>
/// Aggregate root for a media library.
/// </summary>
[DebuggerDisplay("Id: {Id} Title: {Title}")]
[DebuggerDisplay("Id: {Id}; Title: {Title}")]
public class Library : AggregateRoot<LibraryId>
{
private readonly List<FileSystemPathId> _contentLocations;
private readonly List<ScanId> _scanIds;
/// <summary>
/// Gets the id of the user owning this media library.
/// Gets the object representing the unique identifier of the user owning this media library.
/// </summary>
public UserId UserId { get; private set; }
@@ -68,23 +71,29 @@ public class Library : AggregateRoot<LibraryId>
public bool SaveMetadataInMediaDirectories { get; private set; }
/// <summary>
/// Gets the list of file system paths that make up the media library.
/// Gets the list of objects representing the file system paths that make up the media library.
/// </summary>
public IReadOnlyCollection<FileSystemPathId> ContentLocations => _contentLocations.AsReadOnly();
/// <summary>
/// Gets the list of objects representing the unique identifiers for the library scans that were performed on this media library.
/// </summary>
public IReadOnlyCollection<ScanId> ScanIds => _scanIds.AsReadOnly();
/// <summary>
/// Initializes a new instance of the <see cref="Library"/> class.
/// </summary>
/// <param name="id">The unique identifier of the media library.</param>
/// <param name="userId">The unique identifier of the user owning the media library.</param>
/// <param name="id">The object representing the unique identifier of the media library.</param>
/// <param name="userId">The object representing the unique identifier of the user owning the media library.</param>
/// <param name="title">The title of the media library.</param>
/// <param name="libraryType">The type of the media library (e.g., Book, TvShow).</param>
/// <param name="contentLocations">The list of file system paths that make up the media library.</param>
/// <param name="contentLocations">The list of objects representing the file system paths that make up the media library.</param>
/// <param name="coverImage">The path of the image file used as the cover for the library.</param>
/// <param name="isEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed.</param>
/// <param name="isLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.</param>
/// <param name="downloadMedatadaFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
/// <param name="saveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
/// <param name="scanIds">The list of objects representing the unique identifier of scans of the media library.</param>
private Library(
LibraryId id,
UserId userId,
@@ -95,7 +104,8 @@ public class Library : AggregateRoot<LibraryId>
bool isEnabled,
bool isLocked,
bool downloadMedatadaFromWeb,
bool saveMetadataInMediaDirectories) : base(id)
bool saveMetadataInMediaDirectories,
List<ScanId> scanIds) : base(id)
{
UserId = userId;
Title = title;
@@ -106,13 +116,13 @@ public class Library : AggregateRoot<LibraryId>
IsLocked = isLocked;
DownloadMedatadaFromWeb = downloadMedatadaFromWeb;
SaveMetadataInMediaDirectories = saveMetadataInMediaDirectories;
_domainEvents.Add(new LibrarySavedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow));
_scanIds = scanIds;
}
/// <summary>
/// Creates a new instance of the <see cref="Library"/> class.
/// </summary>
/// <param name="userId">The unique identifier of the user owning the media library.</param>
/// <param name="userId">The object representing the unique identifier of the user owning the media library.</param>
/// <param name="title">The title of the media library.</param>
/// <param name="libraryType">The type of the media library (e.g., Book, TvShow).</param>
/// <param name="contentLocations">The list of file system paths that make up the media library.</param>
@@ -121,11 +131,12 @@ public class Library : AggregateRoot<LibraryId>
/// <param name="isLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.</param>
/// <param name="downloadMedatadaFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
/// <param name="saveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
/// <param name="scanIds">The list of objects representing the unique identifier of scans of the media library.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="Library"/>, or an error message.
/// </returns>
public static ErrorOr<Library> Create(
Guid userId,
UserId userId,
string title,
LibraryType libraryType,
IEnumerable<string> contentLocations,
@@ -133,7 +144,8 @@ public class Library : AggregateRoot<LibraryId>
bool isEnabled,
bool isLocked,
bool downloadMedatadaFromWeb,
bool saveMetadataInMediaDirectories)
bool saveMetadataInMediaDirectories,
List<ScanId> scanIds)
{
List<FileSystemPathId> tempContentLocations = [];
// go through all the file system paths that make up the media library and create domain objects from them
@@ -146,7 +158,7 @@ public class Library : AggregateRoot<LibraryId>
}
return new Library(
LibraryId.CreateUnique(),
UserId.Create(userId),
userId,
title,
libraryType,
tempContentLocations,
@@ -154,15 +166,16 @@ public class Library : AggregateRoot<LibraryId>
isEnabled,
isLocked,
downloadMedatadaFromWeb,
saveMetadataInMediaDirectories
saveMetadataInMediaDirectories,
scanIds
);
}
/// <summary>
/// Creates a new instance of the <see cref="Library"/>, with a pre-existing <paramref name="id"/>.
/// </summary>
/// <param name="id">The object representing the id of the media library.</param>
/// <param name="userId">The object representing the id of the user owning the media library.</param>
/// <param name="id">The object representing the unique identifier of the media library.</param>
/// <param name="userId">The object representing the unique identifier of the user owning the media library.</param>
/// <param name="title">The title of the media library.</param>
/// <param name="libraryType">The type of the media library (e.g., Book, TvShow).</param>
/// <param name="contentLocations">The list of file system paths that make up the media library.</param>
@@ -171,12 +184,13 @@ public class Library : AggregateRoot<LibraryId>
/// <param name="isLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.</param>
/// <param name="downloadMedatadaFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
/// <param name="saveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
/// <param name="scanIds">The list of objects representing the unique identifier of scans of the media library.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="Library"/>, or an error message.
/// </returns>
public static ErrorOr<Library> Create(
LibraryId id,
Guid userId,
UserId userId,
string title,
LibraryType libraryType,
IEnumerable<string> contentLocations,
@@ -184,7 +198,8 @@ public class Library : AggregateRoot<LibraryId>
bool isEnabled,
bool isLocked,
bool downloadMedatadaFromWeb,
bool saveMetadataInMediaDirectories)
bool saveMetadataInMediaDirectories,
List<ScanId> scanIds)
{
List<FileSystemPathId> tempContentLocations = [];
// go through all the file system paths that make up the media library and create domain objects from them
@@ -197,7 +212,7 @@ public class Library : AggregateRoot<LibraryId>
}
return new Library(
id,
UserId.Create(userId),
userId,
title,
libraryType,
tempContentLocations,
@@ -205,10 +220,19 @@ public class Library : AggregateRoot<LibraryId>
isEnabled,
isLocked,
downloadMedatadaFromWeb,
saveMetadataInMediaDirectories
saveMetadataInMediaDirectories,
scanIds
);
}
/// <summary>
/// Initiates the saving of the current library.
/// </summary>
public void Save()
{
_domainEvents.Add(new LibrarySavedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow));
}
/// <summary>
/// Sets the file system path where the cover image was copied to from where it was located when the user selected it, to the internal library.
/// </summary>
@@ -221,13 +245,14 @@ public class Library : AggregateRoot<LibraryId>
/// <summary>
/// Marks the current library as deleted.
/// </summary>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public ErrorOr<Deleted> Delete()
{
// clear all existing events since they become irrelevant when the entity is deleted, and they dont need to be processed
_domainEvents.Clear();
// only add the delete event if it hasn't been added already
if (!_domainEvents.Any(e => e is LibraryDeletedDomainEvent))
if (!_domainEvents.Any(domainEvent => domainEvent is LibraryDeletedDomainEvent))
_domainEvents.Add(new LibraryDeletedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow));
// TODO: perhaps trigger events for removing contents related to the removed library (media metadata, etc)?
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Domain event raised when a libary scan is canceled.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScanId">The unique identifier of the cancelled media library scan.</param>
/// <param name="LibraryId">The unique identifier of the library whose scan was canceled.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {Id}")]
public record LibraryScanCancelledDomainEvent(
Guid Id,
ScanId ScanId,
LibraryId LibraryId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Domain event raised when a libary scan is completed.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="LibraryId">The unique identifier of the library whose scan was completed.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {Id}")]
public record LibraryScanCompletedDomainEvent(
Guid Id,
LibraryId LibraryId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Domain event raised when a libary scan has failed.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScanId">The unique identifier of the failed media library scan.</param>
/// <param name="LibraryId">The unique identifier of the library whose scan has failed.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {Id}")]
public record LibraryScanFailedDomainEvent(
Guid Id,
ScanId ScanId,
LibraryId LibraryId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Domain event raised when a libary's scan progress changes.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScanId">The unique identifier of the failed media library scan.</param>
/// <param name="LibraryId">The unique identifier of the library whose scan progress changes.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {Id}")]
public record LibraryScanProgressChangedDomainEvent(
Guid Id,
ScanId ScanId,
LibraryId LibraryId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Domain event raised when a libary scan is queued.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="ScanId">The unique identifier of the queued media library scan.</param>
/// <param name="LibraryId">The unique identifier of the library whose scan was queued.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {Id}")]
public record LibraryScanQueuedDomainEvent(
Guid Id,
ScanId ScanId,
LibraryId LibraryId,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Domain event raised when a libary scan is started.
/// </summary>
/// <param name="Id">The unique identifier of the domain event.</param>
/// <param name="LibraryScan">The library scan that was started.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {LibraryScan.Id}")]
public record LibraryScanStartedDomainEvent(
Guid Id,
LibraryScan LibraryScan,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -0,0 +1,151 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
/// <summary>
/// Aggregate root for a media library scan.
/// </summary>
[DebuggerDisplay("Id: {Id}")]
public class LibraryScan : AggregateRoot<ScanId>
{
private readonly List<LibraryScan> _pastScans = [];
/// <summary>
/// Gets the object representing the unique identifier of the media library that is scanned.
/// </summary>
public LibraryId LibraryId { get; private set; }
/// <summary>
/// Gets the object representing the unique identifier of the user initiating this media library scan.
/// </summary>
public UserId UserId { get; private set; }
/// <summary>
/// Gets or sets the status of the current media library scan job.
/// </summary>
public LibraryScanJobStatus Status { get; internal set; }
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScan"/> class.
/// </summary>
/// <param name="id">The object representing the unique identifier of the media library scan.</param>
/// <param name="libraryId">The object representing the unique identifier of the media library to be scanned.</param>
/// <param name="userId">The object representing the unique identifier of the user initiating the media library scan.</param>
/// <param name="status">The status of the media library scan.</param>
/// <param name="pastScans">The list of past media library scans the library identified by <paramref name="libraryId"/> had.</param>
private LibraryScan(ScanId id, LibraryId libraryId, UserId userId, LibraryScanJobStatus status, List<LibraryScan> pastScans) : base(id)
{
LibraryId = libraryId;
UserId = userId;
Status = status;
_pastScans = pastScans;
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryScan"/> class.
/// </summary>
/// <param name="libraryId">The object representing the unique identifier of the media library to be scanned.</param>
/// <param name="userId">The object representing the unique identifier of the user initiating the media library scan.</param>
/// <param name="pastScans">The list of past media library scans the library identified by <paramref name="libraryId"/> had.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="LibraryScan"/>, or an error message.
/// </returns>
public static ErrorOr<LibraryScan> Create(LibraryId libraryId, UserId userId, List<LibraryScan> pastScans)
{
return new LibraryScan(ScanId.CreateUnique(), libraryId, userId, LibraryScanJobStatus.Pending, pastScans);
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryScan"/>, with a pre-existing <paramref name="id"/>.
/// </summary>
/// <param name="id">The object representing the unique identifier of the media library scan.</param>
/// <param name="libraryId">The object representing the unique identifier of the media library to be scanned.</param>
/// <param name="userId">The object representing the unique identifier of the user initiating the media library scan.</param>
/// <param name="status">The status of the media library scan.</param>
/// <param name="pastScans">The list of past media library scans the library identified by <paramref name="libraryId"/> had.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="LibraryScan"/>, or an error message.
/// </returns>
public static ErrorOr<LibraryScan> Create(ScanId id, LibraryId libraryId, UserId userId, LibraryScanJobStatus status, List<LibraryScan> pastScans)
{
return new LibraryScan(id, libraryId, userId, status, pastScans);
}
/// <summary>
/// Queues a media library scan.
/// </summary>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public ErrorOr<Success> QueueScan()
{
// there must be no active scan for this library in the past 30 days
if (_pastScans.Any(libraryScan => libraryScan.Status == LibraryScanJobStatus.Running || libraryScan.Status == LibraryScanJobStatus.Pending))
return Errors.LibraryScanning.LibraryAlreadyBeingScanned;
_domainEvents.Add(new LibraryScanQueuedDomainEvent(Guid.NewGuid(), Id, LibraryId, DateTime.UtcNow));
return Result.Success;
}
/// <summary>
/// Starts the media library scan.
/// </summary>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public ErrorOr<Success> StartScan()
{
if (Status == LibraryScanJobStatus.Pending)
Status = LibraryScanJobStatus.Running;
else
return Errors.LibraryScanning.CanOnlyStartPendingScans;
// there must be no active scan for this library in the past 30 days
if (_pastScans.Any(libraryScan => libraryScan.Status == LibraryScanJobStatus.Running || libraryScan.Status == LibraryScanJobStatus.Pending))
return Errors.LibraryScanning.LibraryAlreadyBeingScanned;
_domainEvents.Add(new LibraryScanStartedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow));
return Result.Success;
}
/// <summary>
/// Cancels the media library scan.
/// </summary>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public ErrorOr<Success> CancelScan()
{
if (Status == LibraryScanJobStatus.Running)
Status = LibraryScanJobStatus.Canceled;
else
return Errors.LibraryScanning.CanOnlyCancelRunningScans;
_domainEvents.Add(new LibraryScanCancelledDomainEvent(Guid.NewGuid(), Id, LibraryId, DateTime.UtcNow));
return Result.Success;
}
/// <summary>
/// Marks the media library scan as failed.
/// </summary>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public ErrorOr<Success> FailScan()
{
if (Status == LibraryScanJobStatus.Running)
Status = LibraryScanJobStatus.Failed;
else
return Errors.LibraryScanning.CanOnlyFailRunningScans;
return Result.Success;
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Threading;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
/// <summary>
/// Interface for the tracker used for canceling in-memory media library scans.
/// </summary>
public interface IMediaLibrariesScanCancellationTracker
{
/// <summary>
/// Gets the cancellation token for a scan identified by <paramref name="scanId"/> and <paramref name="userId"/>.
/// </summary>
/// <param name="scanId">The unique identifier of the scan to get the cancellation token for.</param>
/// <param name="userId">The unique identifier of the user who initiated the scan for which to get the cancellation token.</param>
/// <returns>A cancellation token for the specified scan.</returns>
CancellationToken GetTokenForScan(Guid scanId, Guid userId);
/// <summary>
/// Registers a new scan operation for tracking.
/// </summary>
/// <param name="scanId">The unique identifier of the scan operation to track.</param>
/// <param name="userId">The unique identifier of the user who initiated the scan to track.</param>
void RegisterScan(Guid scanId, Guid userId);
/// <summary>
/// Cancels a scan identified by <paramref name="scanId"/> and <paramref name="userId"/>.
/// </summary>
/// <param name="scanId">The unique identifier of the scan operation to cancel.</param>
/// <param name="userId">The unique identifier of the user requesting the cancellation.</param>
void CancelScan(Guid scanId, Guid userId);
/// <summary>
/// Cancels all active scan operations for a user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The unique identifier of the user whose scans should be canceled.</param>
void CancelUserScans(Guid userId);
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums.MediaLibrary;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
/// <summary>
/// Interface for the service used to scan a media library.
/// </summary>
public interface IMediaLibraryScanningService
{
/// <summary>
/// Starts <paramref name="scan"/>.
/// </summary>
/// <param name="scan">The media library scan to start.</param>
/// <param name="libraryType">The type of the media library to be scanned.</param>
/// <param name="downloadMedatadaFromWeb">Whether the library permits downloading data from the web, or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Success>> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMedatadaFromWeb, CancellationToken cancellationToken);
/// <summary>
/// Cancels <paramref name="scan"/>.
/// </summary>
/// <param name="scan">The scan to cancel.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
ErrorOr<Success> CancelScan(LibraryScan scan);
}
@@ -0,0 +1,8 @@
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
/// <summary>
/// Interface for the media library scan job for discovering file system items.
/// </summary>
public interface IFileSystemDiscoveryJob : IMediaLibraryScanJob
{
}
@@ -0,0 +1,8 @@
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
/// <summary>
/// Interface for the media library scan job for comparing hashes.
/// </summary>
public interface IHashComparerJob : IMediaLibraryScanJob
{
}
@@ -0,0 +1,69 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
/// <summary>
/// Interface for the abstract base class defining a media library scan job.
/// </summary>
public interface IMediaLibraryScanJob
{
/// <summary>
/// Gets or sets the Id of the media library scan that this job is part of.
/// </summary>
ScanId ScanId { get; set; }
/// <summary>
/// Gets or sets the Id of the user that initiated the media library scan that this job is part of.
/// </summary>
UserId UserId { get; set; }
/// <summary>
/// Gets or sets the unique identifier of the media library upon which the scan is performed.
/// </summary>
LibraryId LibraryId { get; set; }
/// <summary>
/// Gets or sets the list of child media scan jobs that will be triggered when this job's payload completes execution.
/// </summary>
List<IMediaLibraryScanJob> Children { get; }
/// <summary>
/// Gets or sets the list of parent media scan jobs that will trigger this job when their payload will complete execution.
/// </summary>
List<IMediaLibraryScanJob> Parents { get; }
/// <summary>
/// Gets or sets the status of the current media library scan job.
/// </summary>
LibraryScanJobStatus Status { get; }
/// <summary>
/// Adds a media library scan job to the list of child media library scan jobs that will be triggered when this job's payload completes execution.
/// </summary>
/// <param name="job">The child media library scan job to be added.</param>
void AddChild(IMediaLibraryScanJob job);
/// <summary>
/// Adds a media library scan job to the list of parent media library scan jobs that will trigger this job when their payload will complete execution.
/// </summary>
/// <param name="job">The child media library scan job to be added.</param>
void AddParent(IMediaLibraryScanJob job);
/// <summary>
/// Executes the payload of the media library scan job.
/// </summary>
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
/// <param name="id">The id of the media library scan job.</param>
/// <param name="input">The input data to be processed by this payload.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken);
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
/// <summary>
/// Interface for the media library scan jobs factory.
/// </summary>
internal interface IMediaLibraryScanJobFactory
{
/// <summary>
/// Creates a new media library scan job of type <typeparamref name="TJob"/>.
/// </summary>
/// <param name="libraryId">The unique identifier of the media library upon which the scan is performed.</param>
/// <typeparam name="TJob">The type of media library scan job to create.</typeparam>
/// <returns>A media library scan job of type <typeparamref name="TJob"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the type of the requested media library scan job has not been registered.</exception>
TJob CreateJob<TJob>(LibraryId libraryId) where TJob : IMediaLibraryScanJob;
}
@@ -0,0 +1,9 @@
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
/// <summary>
/// Interface for the media library scan job for retrieving persistence data from any eventual previous scans.
/// </summary>
public interface IRepositoryMetadataDiscoveryJob : IMediaLibraryScanJob
{
}
@@ -0,0 +1,80 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
/// <summary>
/// Abstract class defining a media library scan job.
/// </summary>
public abstract class MediaLibraryScanJob : IMediaLibraryScanJob
{
protected int parentsPayloadsExecuted;
protected ScanJobProgress? _jobProgress;
/// <summary>
/// Gets or sets the Id of the media library scan that this job is part of.
/// </summary>
public required ScanId ScanId { get; set; }
/// <summary>
/// Gets or sets the Id of the user that initiated the media library scan that this job is part of.
/// </summary>
public required UserId UserId { get; set; }
/// <summary>
/// Gets or sets the unique identifier of the media library upon which the scan is performed.
/// </summary>
public required LibraryId LibraryId { get; set; }
/// <summary>
/// Gets or sets the list of child media scan jobs that will be triggered when this job's payload completes execution.
/// </summary>
public List<IMediaLibraryScanJob> Children { get; protected set; } = [];
/// <summary>
/// Gets or sets the list of parent media scan jobs that will trigger this job when their payload will complete execution.
/// </summary>
public List<IMediaLibraryScanJob> Parents { get; protected set; } = [];
/// <summary>
/// Gets or sets the status of the current media library scan job.
/// </summary>
public LibraryScanJobStatus Status { get; protected set; } = LibraryScanJobStatus.Pending;
/// <summary>
/// Adds a media library scan job to the list of child media library scan jobs that will be triggered when this job's payload completes execution.
/// </summary>
/// <param name="job">The child media library scan job to be added.</param>
public void AddChild(IMediaLibraryScanJob job)
{
if (!Children.Contains(job) && !Parents.Contains(job))
Children.Add(job);
}
/// <summary>
/// Adds a media library scan job to the list of parent media library scan jobs that will trigger this job when their payload will complete execution.
/// </summary>
/// <param name="job">The child media library scan job to be added.</param>
public void AddParent(IMediaLibraryScanJob job)
{
if (!Parents.Contains(job) && !Children.Contains(job))
Parents.Add(job);
}
/// <summary>
/// Executes the payload of the media library scan job.
/// </summary>
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
/// <param name="id">The unique identifier of the media library scan job.</param>
/// <param name="input">The input data to be processed by this payload.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public abstract Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken);
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Microsoft.Extensions.DependencyInjection;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
/// <summary>
/// Concrete implementation for the media library scan jobs factory.
/// </summary>
internal class MediaLibraryScanJobFactory : IMediaLibraryScanJobFactory
{
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanJobFactory"/> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public MediaLibraryScanJobFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <summary>
/// Creates a new media library scan job of type <typeparamref name="TJob"/>.
/// </summary>
/// <param name="libraryId">The unique identifier of the media library upon which the scan is performed.</param>
/// <typeparam name="TJob">The type of media library scan job to create.</typeparam>
/// <returns>A media library scan job of type <typeparamref name="TJob"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the type of the requested media library scan job has not been registered.</exception>
public TJob CreateJob<TJob>(LibraryId libraryId) where TJob : IMediaLibraryScanJob
{
// resolve the job from DI
TJob job = _serviceProvider.GetRequiredService<TJob>() ?? throw new ArgumentException("Job type not registered in the DI system.");
job.LibraryId = libraryId;
return job;
}
}
@@ -0,0 +1,92 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
/// <summary>
/// Service used to scan a media library.
/// </summary>
internal class MediaLibraryScanningService : IMediaLibraryScanningService
{
private readonly IMediaLibrariesScanQueue _mediaScanQueue;
private readonly IMediaLibraryScannerFactory _libraryScannerFactory;
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanningService"/> class.
/// </summary>
/// <param name="mediaScanQueue">Injected queue used for processing media libraries scan jobs.</param>
/// <param name="libraryScannerFactory">Injected factory for creating media library scanners.</param>
public MediaLibraryScanningService(
IMediaLibrariesScanQueue mediaScanQueue,
IMediaLibraryScannerFactory libraryScannerFactory,
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker)
{
_mediaScanQueue = mediaScanQueue;
_libraryScannerFactory = libraryScannerFactory;
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
}
/// <summary>
/// Starts <paramref name="scan"/>.
/// </summary>
/// <param name="scan">The media library scan to start.</param>
/// <param name="libraryType">The type of the media library to be scanned.</param>
/// <param name="downloadMedatadaFromWeb">Whether the library permits downloading data from the web, or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<ErrorOr<Success>> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMedatadaFromWeb, CancellationToken cancellationToken)
{
// mark the scan itself as started
ErrorOr<Success> startScanResult = scan.StartScan();
if (startScanResult.IsError)
return startScanResult.Errors;
// register the scan in the tracker for cancellation tokens
_mediaLibrariesScanCancellationTracker.RegisterScan(scan.Id.Value, scan.UserId!.Value);
try
{
// link the user's cancellation token with the scan's token
CancellationTokenSource linkedSource = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken, _mediaLibrariesScanCancellationTracker.GetTokenForScan(scan.Id.Value, scan.UserId!.Value));
// get a media library scanner for the provided media library type
IMediaTypeScanner scanner = _libraryScannerFactory.CreateLibraryScanner(libraryType);
// get the list of scan jobs for the retrieved scanner
List<IMediaLibraryScanJob> jobs = scanner.CreateScanJobsForLibrary(scan.LibraryId, downloadMedatadaFromWeb).ToList();
// enqueue the jobs on the channel from where they will be processed
foreach (IMediaLibraryScanJob job in jobs)
{
job.ScanId = scan.Id;
job.UserId = scan.UserId;
await _mediaScanQueue.Writer.WriteAsync(job, linkedSource.Token).ConfigureAwait(false);
}
}
catch (NotImplementedException) { }
return Result.Success;
}
/// <summary>
/// Cancels <paramref name="scan"/>.
/// </summary>
/// <param name="scan">The media library scan to cancel.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public ErrorOr<Success> CancelScan(LibraryScan scan)
{
// trigger the process that cancels the jobs of the scan
_mediaLibrariesScanCancellationTracker.CancelScan(scan.Id.Value, scan.UserId!.Value);
return Result.Success;
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using System.Threading.Channels;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
/// <summary>
/// Interface for the message queue for handling <see cref="IMediaLibraryScanJob"/> instances.
/// </summary>
public interface IMediaLibrariesScanQueue
{
/// <summary>
/// Gets the writer for the queue, allowing producers to enqueue <see cref="IMediaLibraryScanJob"/> instances.
/// </summary>
public ChannelWriter<IMediaLibraryScanJob> Writer { get; }
/// <summary>
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="IMediaLibraryScanJob"/> instances.
/// </summary>
public ChannelReader<IMediaLibraryScanJob> Reader { get; }
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common;
/// <summary>
/// Interface defining a factory for creating media library scanners.
/// </summary>
internal interface IMediaLibraryScannerFactory
{
/// <summary>
/// Creates a media library scanner based on the provided library type.
/// </summary>
/// <param name="libraryType">The type of the library that determines the type of the created media library scanner.</param>
/// <returns>A media library scanner for the specified media library type.</returns>
IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType);
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common;
/// <summary>
/// Interface defining a media library scanner for a specific media library type.
/// </summary>
public interface IMediaTypeScanner
{
/// <summary>
/// The media library type that this media library scanner supports.
/// </summary>
LibraryType SupportedType { get; }
/// <summary>
/// Creates the media library scan jobs for the provided media library.
/// </summary>
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
/// <param name="downloadMedatadaFromWeb">Whether the library permits downloading data from the web, or not.</param>
/// <returns>A collection of media library scan jobs.</returns>
IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMedatadaFromWeb);
}
@@ -0,0 +1,75 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners;
using Microsoft.Extensions.DependencyInjection;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners.Common;
/// <summary>
/// Defines a factory for creating media library scanners.
/// </summary>
internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory
{
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScannerFactory"/> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public MediaLibraryScannerFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <summary>
/// Creates a media library scanner for the specified library type.
/// </summary>
/// <param name="libraryType">The type of the media library.</param>
/// <returns>A media library scanner for the specified library type.</returns>
public IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType)
{
return libraryType switch
{
// implemented scanners
LibraryType.Book => _serviceProvider.GetRequiredService<IBookLibraryTypeScanner>(),
LibraryType.EBook => throw new NotImplementedException("EBook scanner is not implemented."),
LibraryType.ComicBook => throw new NotImplementedException("ComicBook scanner is not implemented."),
LibraryType.Magazine => throw new NotImplementedException("Magazine scanner is not implemented."),
LibraryType.Newspaper => throw new NotImplementedException("Newspaper scanner is not implemented."),
LibraryType.Manga => throw new NotImplementedException("Manga scanner is not implemented."),
LibraryType.GraphicNovel => throw new NotImplementedException("GraphicNovel scanner is not implemented."),
LibraryType.AcademicPaper => throw new NotImplementedException("AcademicPaper scanner is not implemented."),
LibraryType.SheetMusic => throw new NotImplementedException("SheetMusic scanner is not implemented."),
LibraryType.Movie => throw new NotImplementedException("Movie scanner is not implemented."),
LibraryType.TvShow => throw new NotImplementedException("TvShow scanner is not implemented."),
LibraryType.Documentary => throw new NotImplementedException("Documentary scanner is not implemented."),
LibraryType.Anime => throw new NotImplementedException("Anime scanner is not implemented."),
LibraryType.ConcertVideo => throw new NotImplementedException("ConcertVideo scanner is not implemented."),
LibraryType.TutorialVideo => throw new NotImplementedException("TutorialVideo scanner is not implemented."),
LibraryType.HomeVideo => throw new NotImplementedException("HomeVideo scanner is not implemented."),
LibraryType.YouTubeVideo => throw new NotImplementedException("YouTubeVideo scanner is not implemented."),
LibraryType.MusicVideo => throw new NotImplementedException("MusicVideo scanner is not implemented."),
LibraryType.LiveRecordingVideo => throw new NotImplementedException("LiveRecordingVideo scanner is not implemented."),
LibraryType.InterviewVideo => throw new NotImplementedException("InterviewVideo scanner is not implemented."),
LibraryType.CoverSongVideo => throw new NotImplementedException("CoverSongVideo scanner is not implemented."),
LibraryType.PodcastVideo => throw new NotImplementedException("PodcastVideo scanner is not implemented."),
LibraryType.Music => throw new NotImplementedException("Music scanner is not implemented."),
LibraryType.Audiobook => throw new NotImplementedException("Audiobook scanner is not implemented."),
LibraryType.LiveRecordingAudio => throw new NotImplementedException("LiveRecordingAudio scanner is not implemented."),
LibraryType.InterviewAudio => throw new NotImplementedException("InterviewAudio scanner is not implemented."),
LibraryType.CoverSongAudio => throw new NotImplementedException("CoverSongAudio scanner is not implemented."),
LibraryType.Remix => throw new NotImplementedException("Remix scanner is not implemented."),
LibraryType.SoundEffect => throw new NotImplementedException("SoundEffect scanner is not implemented."),
LibraryType.PodcastAudio => throw new NotImplementedException("PodcastAudio scanner is not implemented."),
LibraryType.Photo => throw new NotImplementedException("Photo scanner is not implemented."),
LibraryType.Playlist => throw new NotImplementedException("Playlist scanner is not implemented."),
LibraryType.Collection => throw new NotImplementedException("Collection scanner is not implemented."),
LibraryType.Subtitles => throw new NotImplementedException("Subtitles scanner is not implemented."),
LibraryType.Lyrics => throw new NotImplementedException("Lyrics scanner is not implemented."),
// catch-all for unknown or unsupported types
_ => throw new ArgumentOutOfRangeException(nameof(libraryType), $"No scanner exists for library type '{libraryType}'.")
};
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a media library scan.
/// </summary>
[DebuggerDisplay("Value: {Value}")]
public sealed class ScanId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="ScanId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private ScanId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="ScanId"/> class.
/// </summary>
/// <returns>The created <see cref="ScanId"/> instance.</returns>
public static ScanId CreateUnique()
{
return new ScanId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="ScanId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="ScanId"/> instance.</param>
/// <returns>The created <see cref="ScanId"/> instance.</returns>
public static ScanId Create(Guid value)
{
return new ScanId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Value Object representing a progress snapshot of a media library scan job.
/// </summary>
[DebuggerDisplay("CompletedItems: {CompletedItems}; TotalItems: {TotalItems}; CurrentOperation: {CurrentOperation}")]
public sealed class ScanJobProgress : ValueObject
{
/// <summary>
/// Gets the number of completed items of the media library scan job.
/// </summary>
public int CompletedItems { get; }
/// <summary>
/// Gets the total number of items of the media library scan job.
/// </summary>
public int TotalItems { get; }
/// <summary>
/// Gets the current operation being performed by the media library scan job.
/// </summary>
public string CurrentOperation { get; } = string.Empty;
/// <summary>
/// Gets the ratio between the total number and the completed number of items, as a percentage.
/// </summary>
public decimal ProgressPercentage => CompletedItems * 100.0m / TotalItems;
/// <summary>
/// Initializes a new instance of the <see cref="ScanJobProgress"/> class.
/// </summary>
/// <param name="completedItems">The number of completed items of the media library scan job.</param>
/// <param name="totalItems">The total number of items of the media library scan job.</param>
/// <param name="currentOperation">The current operation being performed by the media library scan job.</param>
private ScanJobProgress(int completedItems, int totalItems, string currentOperation)
{
CompletedItems = completedItems;
TotalItems = totalItems;
CurrentOperation = currentOperation;
}
/// <summary>
/// Creates a new instance of the <see cref="ScanJobProgress"/> class.
/// </summary>
/// <param name="completedItems">The number of completed items of the media library scan job.</param>
/// <param name="totalItems">The total number of items of the media library scan job.</param>
/// <param name="currentOperation">The current operation being performed by the media library scan job.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="ScanJobProgress"/>, or an error message.
/// </returns>
public static ErrorOr<ScanJobProgress> Create(int completedItems, int totalItems, string currentOperation)
{
if (totalItems <= 0)
return Errors.LibraryScanning.TotalScanJobItemsCountMustBePositive;
if (completedItems < 0)
return Errors.LibraryScanning.CompletedScanJobItemsCountMustBePositive;
if (completedItems > totalItems)
return Errors.LibraryScanning.CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount;
if (string.IsNullOrWhiteSpace(currentOperation))
return Errors.LibraryScanning.ScanJobCurrentOperationCannotBeEmpty;
return new ScanJobProgress(completedItems, totalItems, currentOperation);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return CompletedItems;
yield return TotalItems;
yield return CurrentOperation;
}
/// <summary>
/// Customized ToString() method.
/// </summary>
/// <returns>Custom string value showing relevant data for current class.</returns>
public override string ToString()
{
return $"CompletedItems: {CompletedItems}; TotalItems: {TotalItems}; CurrentOperation: {CurrentOperation}";
}
}