Implements first stage library management system

This commit is contained in:
BinaryAlley committed 2024-11-03 19:43:46 +02:00
1 parent 5e0f94cd82
commit 36352ea9e8
291 files changed
+3733 -1384

No files matched your search

@@ -0,0 +1,153 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.AudioLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the audio metadata of a media element.
/// </summary>
[DebuggerDisplay("{Title}")]
public class AudioMetadata : BaseMetadata
{
/// <summary>
/// Gets the duration of the video in seconds.
/// </summary>
public int DurationInSeconds { get; }
/// <summary>
/// Gets the sample rate of the audio in Hz.
/// </summary>
public int SampleRate { get; }
/// <summary>
/// Gets the number of audio channels.
/// </summary>
public int Channels { get; }
/// <summary>
/// Gets the bit depth of the audio.
/// </summary>
public Optional<int> BitDepth { get; }
/// <summary>
/// Gets the audio codec used.
/// </summary>
public Optional<string> AudioCodec { get; }
/// <summary>
/// Gets the bitrate of the audio in kbps.
/// </summary>
public Optional<int> Bitrate { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AudioMetadata"/> class.
/// </summary>
/// <param name="title">The title of the audio.</param>
/// <param name="originalTitle">The optional original title of the video.</param>
/// <param name="durationInSeconds">The duration of the audio, in seconds.</param>
/// <param name="sampleRate">The sample rate of the audio, in Hz.</param>
/// <param name="channels">The number of audio channels.</param>
/// <param name="releaseInfo">The release information of the audio.</param>
/// <param name="description">The description of the audio.</param>
/// <param name="language">The language of the audio.</param>
/// <param name="originalLanguage">The optional original language of the video.</param>
/// <param name="bitDepth">The bit depth of the audio.</param>
/// <param name="audioCodec">The audio codec used.</param>
/// <param name="genres">The genres of the audio.</param>
/// <param name="tags">The tags associated with the audio.</param>
public AudioMetadata(
string title,
Optional<string> originalTitle,
int durationInSeconds,
int sampleRate,
int channels,
ReleaseInfo releaseInfo,
Optional<string> description,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<int> bitDepth,
Optional<string> audioCodec,
Optional<int> bitrate)
: base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage)
{
DurationInSeconds = durationInSeconds;
SampleRate = sampleRate;
Channels = channels;
BitDepth = bitDepth;
AudioCodec = audioCodec;
Bitrate = bitrate;
}
/// <summary>
/// Creates a new instance of the <see cref="AudioMetadata"/> class.
/// </summary>
/// <param name="title">The title of the audio.</param>
/// <param name="originalTitle">The optional original title of the video.</param>
/// <param name="durationInSeconds">The duration of the audio, in seconds.</param>
/// <param name="sampleRate">The sample rate of the audio, in Hz.</param>
/// <param name="channels">The number of audio channels.</param>
/// <param name="release">The release information of the audio.</param>
/// <param name="description">The description of the audio.</param>
/// <param name="language">The language of the audio.</param>
/// <param name="originalLanguage">The optional original language of the video.</param>
/// <param name="bitDepth">The bit depth of the audio.</param>
/// <param name="audioCodec">The audio codec used.</param>
/// <param name="genres">The genres of the audio.</param>
/// <param name="tags">The tags associated with the audio.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="AudioMetadata"/>, or an error message.
/// </returns>
public static ErrorOr<AudioMetadata> Create(
string title,
Optional<string> originalTitle,
int durationInSeconds,
int sampleRate,
int channels,
ReleaseInfo release,
Optional<string>
description,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<int> bitDepth,
Optional<string> audioCodec,
Optional<int> bitrate)
{
return new AudioMetadata(
title,
originalTitle,
durationInSeconds,
sampleRate,
channels,
release,
description,
genres,
tags,
language,
originalLanguage,
bitDepth,
audioCodec,
bitrate);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
foreach (object component in base.GetEqualityComponents())
yield return component;
yield return DurationInSeconds;
yield return SampleRate;
yield return Channels;
yield return BitDepth;
yield return AudioCodec;
yield return Bitrate;
}
}
@@ -0,0 +1,143 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
/// <summary>
/// Entity representing a file system directory.
/// </summary>
[DebuggerDisplay("{Id.Path}")]
public sealed class Directory : FileSystemItem
{
private readonly List<FileSystemItem> _items = [];
/// <summary>
/// Gets or sets the creation date of the file system item. Can be optional if the information is not available.
/// </summary>
public Optional<DateTime> DateCreated { get; private set; }
/// <summary>
/// Gets or sets the last modification date of the file system item. Can be optional if the information is not available.
/// </summary>
public Optional<DateTime> DateModified { get; private set; }
/// <summary>
/// Gets the collection of file system items that are children to the current directory entity.
/// </summary>
public IReadOnlyCollection<FileSystemItem> Items => _items.AsReadOnly();
/// <summary>
/// Initializes a new instance of the <see cref="Directory"/> class.
/// </summary>
/// <param name="id">The unique identifier of the directory in the file system path.</param>
/// <param name="name">The name of the directory.</param>
/// <param name="dateCreated">The date and time the directory was created. Can be optional if unknown.</param>
/// <param name="dateModified">The date and time the directory was last modified. Can be optional if unknown.</param>
private Directory(FileSystemPathId id, string name, Optional<DateTime> dateCreated, Optional<DateTime> dateModified) : base(id, name, FileSystemItemType.Directory)
{
DateCreated = dateCreated;
DateModified = dateModified;
}
/// <summary>
/// Creates a new instance of the <see cref="Directory"/> class.
/// </summary>
/// <param name="name">The name of the directory.</param>
/// <param name="dateCreated">The date and time the directory was created. Can be optional if unknown.</param>
/// <param name="dateModified">The date and time the directory was last modified. Can be optional if unknown.</param>
/// <param name="status">The status of the file system item.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Directory"/>, or an error message.
/// </returns>
public static ErrorOr<Directory> Create(
string path,
string name,
Optional<DateTime> dateCreated,
Optional<DateTime> dateModified,
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{
// TODO: enforce invariants
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
if (createPathResult.IsError)
return createPathResult.Errors;
Directory newDirectory = new(
createPathResult.Value,
name,
dateCreated,
dateModified);
ErrorOr<Updated> setStatusResult = newDirectory.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newDirectory;
}
/// <summary>
/// Creates a new instance of the <see cref="Directory"/> class.
/// </summary>
/// <param name="name">The name of the directory.</param>
/// <param name="dateCreated">The date and time the directory was created. Can be optional if unknown.</param>
/// <param name="dateModified">The date and time the directory was last modified. Can be optional if unknown.</param>
/// <param name="status">The status of the file system item.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Directory"/>, or an error message.
/// </returns>
public static ErrorOr<Directory> Create(
FileSystemPathId id,
string name,
Optional<DateTime> dateCreated,
Optional<DateTime> dateModified,
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{
// TODO: enforce invariants
Directory newDirectory = new(
id,
name,
dateCreated,
dateModified);
ErrorOr<Updated> setStatusResult = newDirectory.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newDirectory;
}
/// <summary>
/// Updates the last modified date of the file system item.
/// </summary>
/// <param name="date">The new date and time of last modification.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public ErrorOr<Updated> UpdateLastModified(DateTime date)
{
DateModified = date;
return Result.Updated;
}
/// <summary>
/// Adds a file system item to the directory.
/// </summary>
/// <param name="item">The file system item to add.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public ErrorOr<Updated> AddItem(FileSystemItem item)
{
_items.Add(item);
return Result.Updated;
}
/// <summary>
/// Removes a file system item from the directory.
/// </summary>
/// <param name="item">The file system item to remove.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public ErrorOr<Updated> RemoveItem(FileSystemItem item)
{
_items.Remove(item);
return Result.Updated;
}
}
@@ -0,0 +1,152 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
/// <summary>
/// Entity representing a file system file.
/// </summary>
[DebuggerDisplay("{Id.Path}")]
public sealed class File : FileSystemItem
{
/// <summary>
/// Gets or sets the creation date of the file system item. Can be optional if the information is not available.
/// </summary>
public Optional<DateTime> DateCreated { get; private set; }
/// <summary>
/// Gets or sets the last modification date of the file system item. Can be optional if the information is not available.
/// </summary>
public Optional<DateTime> DateModified { get; private set; }
/// <summary>
/// Gets or sets the size in bytes of the current file entity.
/// </summary>
public long Size { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="File"/> class.
/// </summary>
/// <param name="id">The unique identifier of the file in the file system path.</param>
/// <param name="name">The name of the file.</param>
/// <param name="dateCreated">The date and time the file was created. Can be optional if unknown.</param>
/// <param name="dateModified">The date and time the file was last modified. Can be optional if unknown.</param>
/// <param name="size">The size of the file in bytes.</param>
private File(FileSystemPathId id, string name, Optional<DateTime> dateCreated, Optional<DateTime> dateModified, long size) : base(id, name, FileSystemItemType.File)
{
DateCreated = dateCreated;
DateModified = dateModified;
Size = size;
}
/// <summary>
/// Creates a new instance of the <see cref="File"/> class.
/// </summary>
/// <param name="name">The name of the file.</param>
/// <param name="dateCreated">The date and time the file was created. Can be optional if unknown.</param>
/// <param name="dateModified">The date and time the file was last modified. Can be optional if unknown.</param>
/// <param name="size">The size of the file in bytes.</param>
/// <param name="status">The status of the file system item.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="File"/>, or an error message.
/// </returns>
public static ErrorOr<File> Create(
string path,
string name,
Optional<DateTime> dateCreated,
Optional<DateTime> dateModified,
long size,
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{
// TODO: enforce invariants
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
if (createPathResult.IsError)
return createPathResult.Errors;
File newFile = new(
createPathResult.Value,
name,
dateCreated,
dateModified,
size);
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newFile;
}
/// <summary>
/// Creates a new instance of the <see cref="File"/> class.
/// </summary>
/// <param name="id">The unique identifier of the file in the file system path.</param>
/// <param name="name">The name of the file.</param>
/// <param name="dateCreated">The date and time the file was created. Can be optional if unknown.</param>
/// <param name="dateModified">The date and time the file was last modified. Can be optional if unknown.</param>
/// <param name="size">The size of the file in bytes.</param>
/// <param name="status">The status of the file system item.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="File"/>, or an error message.
/// </returns>
public static ErrorOr<File> Create(
FileSystemPathId id,
string name,
Optional<DateTime> dateCreated,
Optional<DateTime> dateModified,
long size,
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{
// TODO: enforce invariants
File newFile = new(
id,
name,
dateCreated,
dateModified,
size);
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newFile;
}
/// <summary>
/// Updates the last modified date of the file system item.
/// </summary>
/// <param name="date">The new date and time of last modification.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public ErrorOr<Updated> UpdateLastModified(DateTime date)
{
DateModified = date;
return Result.Updated;
}
/// <summary>
/// Updates the size of the file.
/// </summary>
/// <param name="newSize">The new size, in bytes.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public ErrorOr<Updated> UpdateSize(long newSize)
{
Size = newSize;
return Result.Updated;
}
/// <summary>
/// Renames the file system item to the specified new name.
/// </summary>
/// <param name="newName">The new name for the file system item.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public ErrorOr<Updated> Rename(string newName)
{
if (string.IsNullOrWhiteSpace(newName))
return Errors.FileSystemManagement.NameCannotBeEmpty;
Name = newName;
return Result.Updated;
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
/// <summary>
/// Entity representing a file system root item on Unix platforms.
/// </summary>
[DebuggerDisplay("{Id.Path}")]
public sealed class UnixRootItem : FileSystemItem
{
private readonly List<FileSystemItem> _items = [];
private const string PATH = "/";
/// <summary>
/// Gets the collection of file system items that are children to the current file system root entity.
/// </summary>
public IReadOnlyCollection<FileSystemItem> Items => _items.AsReadOnly();
/// <summary>
/// Initializes a new instance of the <see cref="UnixRootItem"/> class.
/// </summary>
/// <param name="id">The unique identifier of the root item in the file system path.</param>
/// <param name="name">The name of the root item.</param>
private UnixRootItem(FileSystemPathId id, string name) : base(id, name, FileSystemItemType.Root)
{
}
/// <summary>
/// Creates a new instance of the <see cref="UnixRootItem"/> class.
/// </summary>
/// <param name="status">The status of the file system root item.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="UnixRootItem"/>, or an error message.
/// </returns>
public static ErrorOr<UnixRootItem> Create(FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(PATH);
if (createPathResult.IsError)
return createPathResult.Errors;
UnixRootItem newRoot = new(createPathResult.Value, PATH);
ErrorOr<Updated> setStatusResult = newRoot.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newRoot;
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
/// <summary>
/// Entity representing a file system root item on Windows platforms.
/// </summary>
[DebuggerDisplay("{Id.Path}")]
public sealed class WindowsRootItem : FileSystemItem
{
private readonly List<FileSystemItem> _items = [];
/// <summary>
/// Gets the collection of file system items that are children to the current file system root entity.
/// </summary>
public IReadOnlyCollection<FileSystemItem> Items => _items.AsReadOnly();
/// <summary>
/// Initializes a new instance of the <see cref="WindowsRootItem"/> class.
/// </summary>
/// <param name="id">The unique identifier of the root item in the file system path.</param>
/// <param name="name">The name of the root item.</param>
private WindowsRootItem(FileSystemPathId id, string name) : base(id, name, FileSystemItemType.Root)
{
}
/// <summary>
/// Creates a new instance of the <see cref="WindowsRootItem"/> class.
/// </summary>
/// <param name="path">The path of the file system root item.</param>
/// <param name="name">The name of the file system root item.</param>
/// <param name="status">The status of the file system root item.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="WindowsRootItem"/>, or an error message.
/// </returns>
public static ErrorOr<WindowsRootItem> Create(
string path,
string name,
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{
// TODO: enforce invariants
ErrorOr<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
if (createPathResult.IsError)
return createPathResult.Errors;
WindowsRootItem newRoot = new(
createPathResult.Value,
name);
ErrorOr<Updated> setStatusResult = newRoot.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newRoot;
}
/// <summary>
/// Creates a new instance of the <see cref="WindowsRootItem"/> class.
/// </summary>
/// <param name="id">The unique identifier of the file system root item in the file system path.</param>
/// <param name="name">The name of the file system root item.</param>
/// <param name="status">The status of the file system root item.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="WindowsRootItem"/>, or an error message.
/// </returns>
public static ErrorOr<WindowsRootItem> Create(
FileSystemPathId id,
string name,
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
{
// TODO: enforce invariants
WindowsRootItem newFile = new(
id,
name);
ErrorOr<Updated> setStatusResult = newFile.SetStatus(status);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return newFile;
}
}
@@ -0,0 +1,75 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
/// <summary>
/// Entity representing a generic file system element.
/// </summary>
[DebuggerDisplay("{Name}")]
public abstract class FileSystemItem : AggregateRoot<FileSystemPathId>
{
/// <summary>
/// Gets or sets the name of the file system item.
/// </summary>
public string Name { get; protected set; }
/// <summary>
/// Gets or sets the optional parent of the file system item.
/// </summary>
public Optional<FileSystemItem> Parent { get; protected set; }
/// <summary>
/// Gets or sets the current status of the file system item. Defaults to Accessible.
/// </summary>
public FileSystemItemStatus Status { get; protected set; } = FileSystemItemStatus.Accessible;
/// <summary>
/// Gets or sets the tpe of the file system item.
/// </summary>
public FileSystemItemType Type { get; protected set; }
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemItem"/> class.
/// </summary>
/// <param name="id">The unique identifier for the file system path.</param>
/// <param name="name">The name of the file system item.</param>
/// <param name="fileSystemItemType">The type of the file system item.</param>
protected FileSystemItem(FileSystemPathId id, string name, FileSystemItemType fileSystemItemType) : base(id)
{
Name = name;
Type = fileSystemItemType;
}
/// <summary>
/// Sets the status of the filesystem item.
/// </summary>
/// <param name="status">The status to be set.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public ErrorOr<Updated> SetStatus(FileSystemItemStatus status)
{
Status = status;
return Result.Updated;
}
/// <summary>
/// Sets the parent of the filesystem item.
/// </summary>
/// <param name="parent">The file system item to be set as parent.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
public ErrorOr<Updated> SetParent(FileSystemItem parent)
{
if (parent is not null)
Parent = parent;
else
return Errors.FileSystemManagement.ParentNodeCannotBeNull;
return Result.Updated;
}
}
@@ -0,0 +1,318 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Directory provider for local file systems.
/// </summary>
internal class DirectoryProviderService : IDirectoryProviderService
{
private readonly IFileSystem _fileSystem;
private readonly IFileSystemPermissionsService _fileSystemPermissionsService;
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryProviderService"/> class.
/// </summary>
/// <param name="fileSystem">Injected service used to interact with the local filesystem.</param>
/// <param name="fileSystemPermissionsService">Injected service used to determine local filesystem permissions.</param>
public DirectoryProviderService(IFileSystem fileSystem, IFileSystemPermissionsService fileSystemPermissionsService)
{
_fileSystem = fileSystem;
_fileSystemPermissionsService = fileSystemPermissionsService;
}
/// <summary>
/// Retrieves a list of subdirectory paths from the specified path.
/// </summary>
/// <param name="path">The path from which to retrieve the subdirectory paths.</param>
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of directory paths or an error.</returns>
public ErrorOr<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false))
return Errors.Permission.UnauthorizedAccess;
return ErrorOrFactory.From(_fileSystem.Directory.GetDirectories(path.Path)
.Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden)
.OrderBy(path => path)
.Select(path => path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path : path + _fileSystem.Path.DirectorySeparatorChar)
.Select(path => FileSystemPathId.Create(path))
.Where(errorOrPathId => !errorOrPathId.IsError)
.Select(errorOrPathId => errorOrPathId.Value)
.AsEnumerable());
}
/// <summary>
/// Gets the attributes of a file system item identified by <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to retrieve the file system attributes.</param>
/// <returns>The retrieved file system attributes.</returns>
private FileAttributes GetAttributes(string path)
{
try
{
// File.GetAttributes is used for both directories and files
return _fileSystem.File.GetAttributes(path);
}
catch
{
return default;
}
}
/// <summary>
/// Checks if a directory with the specified path exists.
/// </summary>
/// <param name="path">The path of the directory whose existance is checked.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of checking the existance of a directory, or an error.</returns>
public ErrorOr<bool> DirectoryExists(FileSystemPathId path)
{
return _fileSystem.Directory.Exists(path.Path);
}
/// <summary>
/// Retrieves the file name from the specified path.
/// </summary>
/// <param name="path">The path to extract the file name from.</param>
/// <returns>The name of the file without the path, or the last segment of the path if no file name is found.</returns>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a file name or an error.</returns>
public ErrorOr<string> GetFileName(FileSystemPathId path)
{
string inputPath = path.Path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path.Path[..^1] : path.Path;
return _fileSystem.Path.GetFileName(inputPath);
}
/// <summary>
/// Gets the last write time of a specific path.
/// </summary>
/// <param name="path">The path to retrieve the last write time for.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the optional last write time of <paramref name="path"/> if available, or an error.</returns>
public ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false))
return Errors.Permission.UnauthorizedAccess;
return Optional<DateTime>.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path));
}
/// <summary>
/// Gets the creation time of a specific path.
/// </summary>
/// <param name="path">The path to retrieve the creation time for.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the optional creation time of <paramref name="path"/> if available, or an error.</returns>
public ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties, false))
return Errors.Permission.UnauthorizedAccess;
return Optional<DateTime>.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path));
}
/// <summary>
/// Creates a new directory with the specified name, at the specified path.
/// </summary>
/// <param name="path">The path where the directory will be created..</param>
/// <param name="name">The name of the directory that will be created.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the path of a created directory, or an error.</returns>
public ErrorOr<FileSystemPathId> CreateDirectory(FileSystemPathId path, string name)
{
// to create a directory, its parent directory must be writable
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Write, false))
return Errors.Permission.UnauthorizedAccess;
// create the directory and return its absolute path
string directoryPath = _fileSystem.Directory.CreateDirectory(_fileSystem.Path.Combine(path.Path, name)).FullName;
return FileSystemPathId.Create(directoryPath);
}
/// <summary>
/// Copies a directory for the specified path.
/// </summary>
/// <param name="sourcePath">Identifier for the path where the directory to be copied is located.</param>
/// <param name="destinationPath">Identifier for the path where the directory will be copied.</param>
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied directory, or an error.</returns>
public ErrorOr<FileSystemPathId> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
{
// check if the source directory exists
if (!_fileSystem.Directory.Exists(sourcePath.Path))
return Errors.FileSystemManagement.DirectoryNotFound;
string destPath = CreateUniqueDirectoryPath(destinationPath.Path);
try
{
// create the new directory
IDirectoryInfo destDirInfo = _fileSystem.DirectoryInfo.New(_fileSystem.Directory.CreateDirectory(destPath).FullName);
// get the information of the source directory
IDirectoryInfo sourceDirInfo = _fileSystem.DirectoryInfo.New(sourcePath.Path);
// copy all files
foreach (IFileInfo fileInfo in sourceDirInfo.GetFiles())
{
string targetFilePath = _fileSystem.Path.Combine(destPath, fileInfo.Name);
fileInfo.CopyTo(targetFilePath, overrideExisting);
_fileSystem.File.SetAttributes(targetFilePath, fileInfo.Attributes); // preserve file attributes
}
// copy all subdirectories
foreach (IDirectoryInfo subDirInfo in sourceDirInfo.GetDirectories())
{
ErrorOr<FileSystemPathId> newSourcePathResult = FileSystemPathId.Create(subDirInfo.FullName);
if (newSourcePathResult.IsError)
return newSourcePathResult.Errors;
ErrorOr<FileSystemPathId> newDestinationPathResult = FileSystemPathId.Create(_fileSystem.Path.Combine(destPath, subDirInfo.Name));
if (newDestinationPathResult.IsError)
return newDestinationPathResult.Errors;
// recursive call
ErrorOr<FileSystemPathId> copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, overrideExisting);
if (copySubDirResult.IsError)
return copySubDirResult.Errors;
}
return FileSystemPathId.Create(destPath);
}
catch
{
return Errors.FileSystemManagement.DirectoryCopyError;
}
}
/// <summary>
/// Creates a directory path that is unique.
/// </summary>
/// <param name="destinationPath">The path from which to generate the unique directory path.</param>
/// <returns>A unique directory path.</returns>
private string CreateUniqueDirectoryPath(string destinationPath)
{
string destPath = destinationPath;
int copyNumber = 1;
// check if the destination directory exists and create a unique directory name
while (_fileSystem.Directory.Exists(destPath) || _fileSystem.File.Exists(destPath))
destPath = $"{destinationPath} - Copy ({copyNumber++})";
return destPath;
}
/// <summary>
/// Moves a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourcePath">Identifier for the path where the directory to be moved is located.</param>
/// <param name="destinationPath">Identifier for the path where the directory will be moved.</param>
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved directory, or an error.</returns>
public ErrorOr<FileSystemPathId> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
{
// check if the source directory exists
if (!_fileSystem.Directory.Exists(sourcePath.Path))
return Errors.FileSystemManagement.DirectoryNotFound;
try
{
// if the destination directory does not exist, perform a simple move
if (!_fileSystem.Directory.Exists(destinationPath.Path))
_fileSystem.Directory.Move(sourcePath.Path, destinationPath.Path);
else
MergeDirectories(sourcePath.Path, destinationPath.Path, overrideExisting); // if the destination directory exists, perform a merge based on the overwrite policy
return FileSystemPathId.Create(destinationPath.Path);
}
catch
{
return Errors.FileSystemManagement.DirectoryMoveError;
}
}
/// <summary>
/// Merges two directories.
/// </summary>
/// <param name="sourceDir">The source directory to be merged.</param>
/// <param name="destDir">The destination directory to be merged.</param>
/// <param name="overwrite">Whether to override existing files.</param>
private void MergeDirectories(string sourceDir, string destDir, bool overwrite)
{
// merge files from source directory to destination directory
foreach (string sourceFilePath in _fileSystem.Directory.GetFiles(sourceDir))
{
string fileName = _fileSystem.Path.GetFileName(sourceFilePath);
string destFilePath = _fileSystem.Path.Combine(destDir, fileName);
// if a file with the same name exists in the destination
if (_fileSystem.File.Exists(destFilePath))
if (overwrite)
{
// overwrite the file in the destination directory
_fileSystem.File.Delete(destFilePath);
_fileSystem.File.Move(sourceFilePath, destFilePath);
}
else
_fileSystem.File.Move(sourceFilePath, destFilePath); // move the file if it does not exist in the destination directory
}
// recursively merge subdirectories
foreach (string sourceSubDirPath in _fileSystem.Directory.GetDirectories(sourceDir))
{
string subDirName = _fileSystem.Path.GetFileName(sourceSubDirPath);
string destSubDirPath = _fileSystem.Path.Combine(destDir, subDirName);
// if the subdirectory does not exist in the destination, move it
if (!_fileSystem.Directory.Exists(destSubDirPath))
_fileSystem.Directory.Move(sourceSubDirPath, destSubDirPath);
else
MergeDirectories(sourceSubDirPath, destSubDirPath, overwrite); // if the subdirectory exists, recursively merge its contents
}
// after merging the contents, delete the source directory if it's now empty
if (!_fileSystem.Directory.EnumerateFileSystemEntries(sourceDir).Any())
_fileSystem.Directory.Delete(sourceDir);
}
/// <summary>
/// Renames a directory at the specified path.
/// </summary>
/// <param name="path">The path of the directory to be renamed.</param>
/// <param name="name">The new name of the directory.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the absolute path of the renamed directory, or an error.</returns>
public ErrorOr<FileSystemPathId> RenameDirectory(FileSystemPathId path, string name)
{
// to rename a directory, its parent directory must be writable
string? parentDirectory = _fileSystem.Directory.GetParent(path.Path)?.FullName;
if (!string.IsNullOrEmpty(parentDirectory))
{
ErrorOr<FileSystemPathId> parendDirectoryResult = FileSystemPathId.Create(parentDirectory);
if (parendDirectoryResult.IsError)
return parendDirectoryResult.Errors;
string? newDirectory = _fileSystem.Path.Combine(parentDirectory, name);
if (!string.IsNullOrEmpty(newDirectory))
{
ErrorOr<FileSystemPathId> newDirectoryPathResult = FileSystemPathId.Create(newDirectory);
if (newDirectoryPathResult.IsError)
return newDirectoryPathResult.Errors;
if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write, false))
return Errors.Permission.UnauthorizedAccess;
// to rename a directory, it must be executable
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute, false))
return Errors.Permission.UnauthorizedAccess;
_fileSystem.Directory.Move(path.Path, newDirectoryPathResult.Value.Path);
return newDirectoryPathResult.Value;
}
else
return Errors.FileSystemManagement.InvalidPath;
}
else
return Errors.FileSystemManagement.InvalidPath;
}
/// <summary>
/// Deletes a directory at the specified path.
/// </summary>
/// <param name="path">The path of the directory to be deleted.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
public ErrorOr<Deleted> DeleteDirectory(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete, false))
return Errors.Permission.UnauthorizedAccess;
_fileSystem.DirectoryInfo.New(path.Path).Delete(true);
return Result.Deleted;
}
}
@@ -0,0 +1,334 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Service for handling directories.
/// </summary>
public class DirectoryService : IDirectoryService
{
private readonly IPlatformContext _platformContext;
private readonly IEnvironmentContext _environmentContext;
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryService"/> class.
/// </summary>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="platformContextManager">Injected facade service for platform contextual services.</param>
public DirectoryService(IEnvironmentContext environmentContext, IPlatformContextManager platformContextManager)
{
_platformContext = platformContextManager.GetCurrentContext();
_environmentContext = environmentContext;
}
/// <summary>
/// Retrieves subdirectories for the specified string path.
/// </summary>
/// <param name="path">String representation of the file path.</param>
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
public ErrorOr<IEnumerable<Directory>> GetSubdirectories(string path, bool includeHiddenElements)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return GetSubdirectories(fileSystemPathIdResult.Value, includeHiddenElements);
}
/// <summary>
/// Retrieves subdirectories for the given directory.
/// </summary>
/// <param name="directory">Directory object to retrieve subdirectories for.</param>
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
public ErrorOr<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool includeHiddenElements)
{
return GetSubdirectories(directory.Id, includeHiddenElements);
}
/// <summary>
/// Retrieves subdirectories for the specified file system path.
/// </summary>
/// <param name="path">Identifier for the file path.</param>
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
public ErrorOr<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements)
{
// retrieve the list of subdirectories
ErrorOr<IEnumerable<FileSystemPathId>> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, includeHiddenElements);
if (subdirectoryPathsResult.IsError)
return subdirectoryPathsResult.Errors;
List<Directory> result = [];
foreach (FileSystemPathId subPath in subdirectoryPathsResult.Value)
{
// extract directory details
ErrorOr<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(subPath);
ErrorOr<Optional<DateTime>> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(subPath);
ErrorOr<Optional<DateTime>> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(subPath);
// if any error occurred, mark directory as Inaccessible
if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
ErrorOr<Directory> errorDirResult = Directory.Create(subPath, !dirNameResult.IsError ? dirNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None());
if (errorDirResult.IsError)
return errorDirResult.Errors;
ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
result.Add(errorDirResult.Value);
}
else
{
ErrorOr<Directory> subDirectoryResult = Directory.Create(subPath, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value);
if (subDirectoryResult.IsError)
return subDirectoryResult.Errors;
result.Add(subDirectoryResult.Value);
}
}
return result;
}
/// <summary>
/// Creates a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
/// </summary>
/// <param name="path">String representation of the path where the directory will be created.</param>
/// <param name="name">The name of the directory that will be created.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of creating a directory, or an error.</returns>
public ErrorOr<Directory> CreateDirectory(string path, string name)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return CreateDirectory(fileSystemPathIdResult.Value, name);
}
/// <summary>
/// Creates a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
/// </summary>
/// <param name="path">Identifier for the path where the directory will be created.</param>
/// <param name="name">The name of the directory that will be created.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of creating a directory, or an error.</returns>
public ErrorOr<Directory> CreateDirectory(FileSystemPathId path, string name)
{
// first, check if the directory about to be created does not already exist
ErrorOr<FileSystemPathId> combinedPath = _platformContext.PathStrategy.CombinePath(path, name);
if (combinedPath.IsError)
return combinedPath.Errors;
ErrorOr<bool> directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(combinedPath.Value);
if (directoryExists.IsError)
return directoryExists.Errors;
else if (directoryExists.Value == true)
return Errors.FileSystemManagement.DirectoryAlreadyExists;
else
{
// create the new directory
ErrorOr<FileSystemPathId> newDirectoryPathResult = _environmentContext.DirectoryProviderService.CreateDirectory(path, name);
if (newDirectoryPathResult.IsError)
return newDirectoryPathResult.Errors;
ErrorOr<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value);
ErrorOr<Optional<DateTime>> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value);
ErrorOr<Optional<DateTime>> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value);
// if any error occurred, mark directory as Inaccessible
if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
ErrorOr<Directory> errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None());
if (errorDirResult.IsError)
return errorDirResult.Errors;
ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return errorDirResult;
}
else
return Directory.Create(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value);
}
}
/// <summary>
/// Copies a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourcePath">String representation of the path where the directory to be copied is located.</param>
/// <param name="destinationPath">String representation of the path where the directory will be copied.</param>
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a copied directory, or an error.</returns>
public ErrorOr<Directory> CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting)
{
// make sure the paths are in the expected format
if (!sourcePath.EndsWith(_platformContext.PathStrategy.PathSeparator))
sourcePath += _platformContext.PathStrategy.PathSeparator;
if (!destinationPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
destinationPath += _platformContext.PathStrategy.PathSeparator;
ErrorOr<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourcePath);
if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors;
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
if (fileSystemDestinationPathIdResult.IsError)
return fileSystemDestinationPathIdResult.Errors;
return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
}
/// <summary>
/// Copies a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourcePath">Identifier for the path where the directory to be copied is located.</param>
/// <param name="destinationPath">Identifier for the path where the directory will be copied.</param>
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied directory, or an error.</returns>
public ErrorOr<Directory> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
{
ErrorOr<bool> directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath);
if (directoryExists.IsError)
return directoryExists.Errors;
else if (directoryExists.Value == false)
return Errors.FileSystemManagement.DirectoryNotFound;
else
{
// copy the directory
ErrorOr<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, overrideExisting);
throw new NotImplementedException();
}
}
/// <summary>
/// Moves a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourcePath">String representation of the path where the directory to be moved is located.</param>
/// <param name="destinationPath">String representation of the path where the directory will be moved.</param>
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved directory, or an error.</returns>
public ErrorOr<Directory> MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting)
{
// make sure the paths are in the expected format
if (!sourcePath.EndsWith(_platformContext.PathStrategy.PathSeparator))
sourcePath += _platformContext.PathStrategy.PathSeparator;
if (!destinationPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
destinationPath += _platformContext.PathStrategy.PathSeparator;
ErrorOr<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourcePath);
if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors;
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
if (fileSystemDestinationPathIdResult.IsError)
return fileSystemDestinationPathIdResult.Errors;
return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
}
/// <summary>
/// Moves a directory for the specified path.
/// </summary>
/// <param name="sourcePath">Identifier for the path where the directory to be moved is located.</param>
/// <param name="destinationPath">Identifier for the path where the directory will be moved.</param>
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the moved directory, or an error.</returns>
public ErrorOr<Directory> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
{
ErrorOr<bool> directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath);
if (directoryExists.IsError)
return directoryExists.Errors;
else if (directoryExists.Value == false)
return Errors.FileSystemManagement.DirectoryNotFound;
else
{
// move the directory
ErrorOr<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, overrideExisting);
throw new NotImplementedException();
}
}
/// <summary>
/// Renames a directory.
/// </summary>
/// <param name="path">String representation of the directory path.</param>
/// <param name="name">The new name of the directory.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the renamed directory, or an error.</returns>
public ErrorOr<Directory> RenameDirectory(string path, string name)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return RenameDirectory(fileSystemPathIdResult.Value, name);
}
/// <summary>
/// Renames a directory for the specified path.
/// </summary>
/// <param name="path">Identifier for the directory path.</param>
/// <param name="name">The new name of the directory.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the renamed directory, or an error.</returns>
public ErrorOr<Directory> RenameDirectory(FileSystemPathId path, string name)
{
// first, check if the directory about to be created does not already exist
ErrorOr<FileSystemPathId> combinedPath = _platformContext.PathStrategy.CombinePath(path, name);
if (combinedPath.IsError)
return combinedPath.Errors;
ErrorOr<bool> directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(combinedPath.Value);
if (directoryExists.IsError)
return directoryExists.Errors;
else if (directoryExists.Value == true)
return Errors.FileSystemManagement.DirectoryAlreadyExists;
else
{
// rename the directory
ErrorOr<FileSystemPathId> newDirectoryPathResult = _environmentContext.DirectoryProviderService.RenameDirectory(path, name);
if (newDirectoryPathResult.IsError)
return newDirectoryPathResult.Errors;
ErrorOr<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value);
ErrorOr<Optional<DateTime>> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value);
ErrorOr<Optional<DateTime>> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value);
// if any error occurred, mark directory as Inaccessible
if (dirNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
ErrorOr<Directory> errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsError ? dirNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None());
if (errorDirResult.IsError)
return errorDirResult.Errors;
ErrorOr<Updated> setStatusResult = errorDirResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return errorDirResult;
}
else
return Directory.Create(newDirectoryPathResult.Value, dirNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value);
}
}
/// <summary>
/// Delete a directory for the specified string path.
/// </summary>
/// <param name="path">String representation of the directory path.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
public ErrorOr<Deleted> DeleteDirectory(string path)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return DeleteDirectory(fileSystemPathIdResult.Value);
}
/// <summary>
/// Delete a directory for the specified path.
/// </summary>
/// <param name="path">Identifier for the directory path.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
public ErrorOr<Deleted> DeleteDirectory(FileSystemPathId path)
{
return _environmentContext.DirectoryProviderService.DeleteDirectory(path);
}
}
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using System.Collections.Generic;
using System.IO.Abstractions;
using System.Linq;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Service for handling drives.
/// </summary>
public class DriveService : IDriveService
{
private readonly IFileSystem _fileSystem;
private readonly IPlatformContext _platformContext;
/// <summary>
/// Initializes a new instance of the <see cref="DriveService"/> class.
/// </summary>
/// <param name="fileSystem">Injected service used to interact with the local filesystem.</param>
public DriveService(IFileSystem fileSystem, IPlatformContextManager platformContextManager)
{
_fileSystem = fileSystem;
_platformContext = platformContextManager.GetCurrentContext();
}
/// <summary>
/// Retrieves the list of drives.
/// </summary>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of drives or an error.</returns>
public ErrorOr<IEnumerable<FileSystemItem>> GetDrives()
{
if (_platformContext.Platform == PlatformType.Unix)
{
ErrorOr<UnixRootItem> unixRootResult = UnixRootItem.Create(FileSystemItemStatus.Accessible);
if (unixRootResult.IsError)
return unixRootResult.Errors;
return new List<FileSystemItem>() { unixRootResult.Value };
}
else
return ErrorOrFactory.From(_fileSystem.DriveInfo.GetDrives()
.OrderBy(driveInfo => driveInfo.Name)
.Where(driveInfo => driveInfo.IsReady)
.Select(driveInfo =>
{
ErrorOr<FileSystemItem> root;
ErrorOr<WindowsRootItem> windowsRootResult = WindowsRootItem.Create(driveInfo.Name, driveInfo.Name);
if (windowsRootResult.IsError)
return windowsRootResult.Errors;
else
root = windowsRootResult.Value;
return root;
})
.Where(errorOrDrive => !errorOrDrive.IsError)
.Select(errorOrDrive => errorOrDrive.Value)
.AsEnumerable());
}
}
@@ -0,0 +1,278 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// File provider for local file systems.
/// </summary>
internal class FileProviderService : IFileProviderService
{
private readonly IFileSystem _fileSystem;
private readonly IFileSystemPermissionsService _fileSystemPermissionsService;
/// <summary>
/// Initializes a new instance of the <see cref="FileProviderService"/> class.
/// </summary>
/// <param name="fileSystem">Injected service used to interact with the local filesystem.</param>
/// <param name="fileSystemPermissionsService">Injected service used to determine local filesystem permissions.</param>
public FileProviderService(IFileSystem fileSystem, IFileSystemPermissionsService fileSystemPermissionsService)
{
_fileSystem = fileSystem;
_fileSystemPermissionsService = fileSystemPermissionsService;
}
/// <summary>
/// Retrieves a list of file paths at the specified path.
/// </summary>
/// <param name="path">The path for which to retrieve the list of files.</param>
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of file paths or an error.</returns>
public ErrorOr<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path, bool includeHiddenElements)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory))
return Errors.Permission.UnauthorizedAccess;
return ErrorOrFactory.From(_fileSystem.Directory.GetFiles(path.Path)
.Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden)
.OrderBy(path => path)
.Select(path => FileSystemPathId.Create(path))
.Where(errorOrPathId => !errorOrPathId.IsError)
.Select(errorOrPathId => errorOrPathId.Value)
.AsEnumerable());
}
/// <summary>
/// Gets the attributes of a file system item identified by <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to retrieve the file system attributes.</param>
/// <returns>The retrieved file system attributes.</returns>
private FileAttributes GetAttributes(string path)
{
try
{
// File.GetAttributes is used for both directories and files
return _fileSystem.File.GetAttributes(path);
}
catch
{
return default;
}
}
/// <summary>
/// Checks if a file with the specified path exists.
/// </summary>
/// <param name="path">The path of the file whose existance is checked.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of checking the existance of a file, or an error.</returns>
public ErrorOr<bool> FileExists(FileSystemPathId path)
{
return _fileSystem.File.Exists(path.Path);
}
/// <summary>
/// Retrieves the file name from the specified path.
/// </summary>
/// <param name="path">The path to extract the file name from.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the name of the file without the path, or the last segment of the path if no file name is found, or an error.</returns>
public ErrorOr<string> GetFileName(FileSystemPathId path)
{
return _fileSystem.Path.GetFileName(path.Path);
}
/// <summary>
/// Retrieves the contents of a file at the specified path.
/// </summary>
/// <param name="path">The path for which to retrieve the file contents.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the contents of a file at the specified path, or an error.</returns>
public ErrorOr<byte[]> GetFileAsync(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents))
return Errors.Permission.UnauthorizedAccess;
return File.ReadAllBytes(path.Path);
}
/// <summary>
/// Gets the last write time of a file at the specified path.
/// </summary>
/// <param name="path">The path of the file to retrieve the last write time for.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the optional last write time of <paramref name="path"/> if available, or an error.</returns>
public ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
return Errors.Permission.UnauthorizedAccess;
return Optional<DateTime>.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path));
}
/// <summary>
/// Gets the creation time of a file at the specified path.
/// </summary>
/// <param name="path">The path of the file to retrieve the creation time for.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the optional creation time of <paramref name="path"/> if available, or an error.</returns>
public ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
return Errors.Permission.UnauthorizedAccess;
return Optional<DateTime>.FromNullable(_fileSystem.File.GetCreationTime(path.Path));
}
/// <summary>
/// Gets the size of a file at the specified path.
/// </summary>
/// <param name="path">The path of the file to retrieve the size for.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the size of <paramref name="path"/> or an error.</returns>
public ErrorOr<long?> GetSize(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties))
return Errors.Permission.UnauthorizedAccess;
return _fileSystem.FileInfo.New(path.Path)?.Length ?? 0;
}
/// <summary>
/// Copies a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
/// </summary>
/// <param name="sourceFilePath">Identifier for the path where the file to be copied is located.</param>
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be copied.</param>
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied file, or an error.</returns>
public ErrorOr<FileSystemPathId> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
{
// check if the source file exists
if (!_fileSystem.File.Exists(sourceFilePath.Path))
return Errors.FileSystemManagement.FileNotFound;
string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path);
string destinationFilePath = _fileSystem.Path.Combine(destinationDirectoryPath.Path, fileName);
// when copying a file to the same location, just copy it with a new name
if (_fileSystem.Path.GetDirectoryName(sourceFilePath.Path) == destinationDirectoryPath.Path)
destinationFilePath = CreateUniqueFilePath(destinationFilePath);
else
// check if there is already a file with the same name as the copied file, in the destination directory
if (_fileSystem.File.Exists(destinationFilePath))
if (!overrideExisting)
return Errors.FileSystemManagement.FileAlreadyExists;
try
{
_fileSystem.File.Copy(sourceFilePath.Path, destinationFilePath, overrideExisting); // copy the file
_fileSystem.File.SetAttributes(destinationFilePath, _fileSystem.File.GetAttributes(sourceFilePath.Path)); // preserve file attributes
return FileSystemPathId.Create(destinationFilePath);
}
catch
{
return Errors.FileSystemManagement.FileCopyError;
}
}
/// <summary>
/// Creates a file path that is unique
/// </summary>
/// <param name="destinationFilePath">The path from which to generate the unique file path.</param>
/// <returns>A unique directory path.</returns>
private string CreateUniqueFilePath(string destinationFilePath)
{
string? directory = _fileSystem.Path.GetDirectoryName(destinationFilePath);
string? filename = _fileSystem.Path.GetFileNameWithoutExtension(destinationFilePath);
string? extension = _fileSystem.Path.GetExtension(destinationFilePath);
string destFilePath = destinationFilePath;
int copyNumber = 1;
// check if the destination file exists and create a unique file name
if (!string.IsNullOrEmpty(directory) && !string.IsNullOrEmpty(filename) && !string.IsNullOrEmpty(extension))
while (_fileSystem.File.Exists(destFilePath))
destFilePath = _fileSystem.Path.Combine(directory, $"{filename} - Copy ({copyNumber++}){extension}");
return destFilePath;
}
/// <summary>
/// Moves a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
/// </summary>
/// <param name="sourceFilePath">Identifier for the path where the file to be moved is located.</param>
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be moved.</param>
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved file, or an error.</returns>
public ErrorOr<FileSystemPathId> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
{
// check if the source file exists
if (!_fileSystem.File.Exists(sourceFilePath.Path))
return Errors.FileSystemManagement.FileNotFound;
try
{
string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path);
string destinationFilePath = _fileSystem.Path.Combine(destinationDirectoryPath.Path, fileName);
// if the destination file does not exist, perform a simple move
if (!_fileSystem.File.Exists(destinationFilePath))
_fileSystem.File.Move(sourceFilePath.Path, destinationFilePath);
else
if (overrideExisting)
_fileSystem.File.Move(sourceFilePath.Path, destinationFilePath, overrideExisting);
else
return Errors.FileSystemManagement.FileAlreadyExists;
return FileSystemPathId.Create(destinationFilePath);
}
catch
{
return Errors.FileSystemManagement.FileMoveError;
}
}
/// <summary>
/// Renames a file at the specified path.
/// </summary>
/// <param name="path">The path of the file to be renamed.</param>
/// <param name="name">The new name of the file.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the absolute path of the renamed file, or an error.</returns>
public ErrorOr<FileSystemPathId> RenameFile(FileSystemPathId path, string name)
{
string? parentDirectory = _fileSystem.FileInfo.New(path.Path)?.DirectoryName;
if (!string.IsNullOrEmpty(parentDirectory))
{
ErrorOr<FileSystemPathId> parendDirectoryResult = FileSystemPathId.Create(parentDirectory);
if (parendDirectoryResult.IsError)
return parendDirectoryResult.Errors;
string? newFile = _fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name);
if (!string.IsNullOrEmpty(newFile))
{
ErrorOr<FileSystemPathId> newFilePathResult = FileSystemPathId.Create(newFile);
if (newFilePathResult.IsError)
return newFilePathResult.Errors;
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute))
return Errors.Permission.UnauthorizedAccess;
if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write))
return Errors.Permission.UnauthorizedAccess;
_fileSystem.File.Move(path.Path, newFilePathResult.Value.Path);
return newFilePathResult;
}
else
return Errors.FileSystemManagement.InvalidPath;
}
else
return Errors.FileSystemManagement.CannotNavigateUp;
}
/// <summary>
/// Deletes a file at the specified path.
/// </summary>
/// <param name="path">The path of the file to be deleted.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns>
public ErrorOr<Deleted> DeleteFile(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete))
return Errors.Permission.UnauthorizedAccess;
_fileSystem.File.Delete(path.Path);
return Result.Deleted;
}
}
@@ -0,0 +1,325 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Service for handling file system files.
/// </summary>
public class FileService : IFileService
{
private readonly IPlatformContext _platformContext;
private readonly IEnvironmentContext _environmentContext;
/// <summary>
/// Initializes a new instance of the <see cref="FileService"/> class.
/// </summary>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="platformContextManager">Injected facade service for platform contextual services.</param>
public FileService(IEnvironmentContext environmentContext, IPlatformContextManager platformContextManager)
{
_platformContext = platformContextManager.GetCurrentContext();
_environmentContext = environmentContext;
}
/// <summary>
/// Retrieves files for the specified string path.
/// </summary>
/// <param name="path">String representation of the file path.</param>
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
public ErrorOr<IEnumerable<File>> GetFiles(string path, bool includeHiddenElements)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return GetFiles(fileSystemPathIdResult.Value, includeHiddenElements);
}
/// <summary>
/// Retrieves files associated with a given file.
/// </summary>
/// <param name="file">The file object.</param>
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
public ErrorOr<IEnumerable<File>> GetFiles(File file, bool includeHiddenElements)
{
return GetFiles(file.Id, includeHiddenElements);
}
/// <summary>
/// Retrieves files for a specified file path Id.
/// </summary>
/// <param name="path">Identifier for the file path.</param>
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
public ErrorOr<IEnumerable<File>> GetFiles(FileSystemPathId path, bool includeHiddenElements)
{
// retrieve the list of files
ErrorOr<IEnumerable<FileSystemPathId>> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, includeHiddenElements);
if (filePathsResult.IsError)
return filePathsResult.Errors;
List<File> result = [];
IEnumerable<FileSystemPathId> filePaths = filePathsResult.Value;
foreach (FileSystemPathId filePath in filePaths)
{
// extract file details and add to the result list
ErrorOr<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(filePath);
ErrorOr<Optional<DateTime>> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(filePath);
ErrorOr<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(filePath);
ErrorOr<long?> sizeResult = _environmentContext.FileProviderService.GetSize(filePath);
long size = sizeResult.Value ?? 0;
// if any of the details returned an error, set inaccessible status
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
ErrorOr<File> errorFileResult = File.Create(filePath, !fileNameResult.IsError ? fileNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size);
if (errorFileResult.IsError)
return errorFileResult.Errors;
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
result.Add(errorFileResult.Value);
}
else
{
ErrorOr<File> fileResult = File.Create(filePath, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size);
if (fileResult.IsError)
return fileResult.Errors;
result.Add(fileResult.Value);
}
}
return result;
}
/// <summary>
/// Copies a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
/// </summary>
/// <param name="sourceFilePath">String representation of the path where the file to be copied is located.</param>
/// <param name="destinationDirectoryPath">String representation of the path of the directory where the file will be copied.</param>
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a copied file, or an error.</returns>
public ErrorOr<File> CopyFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting)
{
if (string.IsNullOrWhiteSpace(destinationDirectoryPath))
return Errors.FileSystemManagement.InvalidPath;
// make sure the paths are in the expected format
if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator;
ErrorOr<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors;
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
if (fileSystemDestinationPathIdResult.IsError)
return fileSystemDestinationPathIdResult.Errors;
return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
}
/// <summary>
/// Copies a file for the specified path.
/// </summary>
/// <param name="sourceFilePath">Identifier for the path where the file to be copied is located.</param>
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be copied.</param>
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied file, or an error.</returns>
public ErrorOr<File> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
{
ErrorOr<bool> fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
if (fileExists.IsError)
return fileExists.Errors;
else if (fileExists.Value == false)
return Errors.FileSystemManagement.FileNotFound;
else
{
// copy the file
ErrorOr<FileSystemPathId> copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, overrideExisting);
if (copyFileResult.IsError)
return copyFileResult.Errors;
ErrorOr<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(copyFileResult.Value);
ErrorOr<Optional<DateTime>> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(copyFileResult.Value);
ErrorOr<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(copyFileResult.Value);
ErrorOr<long?> sizeResult = _environmentContext.FileProviderService.GetSize(copyFileResult.Value);
long size = sizeResult.Value ?? 0;
// if any of the details returned an error, set inaccessible status
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
ErrorOr<File> errorFileResult = File.Create(copyFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size);
if (errorFileResult.IsError)
return errorFileResult.Errors;
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return errorFileResult;
}
else
return File.Create(copyFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size);
}
}
/// <summary>
/// Moves a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
/// </summary>
/// <param name="sourceFilePath">String representation of the path where the file to be moved is located.</param>
/// <param name="destinationDirectoryPath">String representation of the path of the directory where the file will be moved.</param>
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved file, or an error.</returns>
public ErrorOr<File> MoveFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting)
{
if (string.IsNullOrWhiteSpace(destinationDirectoryPath))
return Errors.FileSystemManagement.InvalidPath;
// make sure the paths are in the expected format
if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator;
ErrorOr<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
if (fileSystemSourcePathIdResult.IsError)
return fileSystemSourcePathIdResult.Errors;
ErrorOr<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
if (fileSystemDestinationPathIdResult.IsError)
return fileSystemDestinationPathIdResult.Errors;
return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
}
/// <summary>
/// Moves a file for the specified path.
/// </summary>
/// <param name="sourceFilePath">Identifier for the path where the file to be moved is located.</param>
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be moved.</param>
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the moved file, or an error.</returns>
public ErrorOr<File> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
{
ErrorOr<bool> fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
if (fileExists.IsError)
return fileExists.Errors;
else if (fileExists.Value == false)
return Errors.FileSystemManagement.FileNotFound;
else
{
// move the file
ErrorOr<FileSystemPathId> moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, overrideExisting);
if (moveFileResult.IsError)
return moveFileResult.Errors;
ErrorOr<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(moveFileResult.Value);
ErrorOr<Optional<DateTime>> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(moveFileResult.Value);
ErrorOr<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(moveFileResult.Value);
ErrorOr<long?> sizeResult = _environmentContext.FileProviderService.GetSize(moveFileResult.Value);
long size = sizeResult.Value ?? 0;
// if any of the details returned an error, set inaccessible status
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
ErrorOr<File> errorFileResult = File.Create(moveFileResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size);
if (errorFileResult.IsError)
return errorFileResult.Errors;
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return errorFileResult;
}
else
return File.Create(moveFileResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size);
}
}
/// <summary>
/// Renames a file.
/// </summary>
/// <param name="path">String representation of the file path.</param>
/// <param name="name">The new name of the file.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the renamed file, or an error.</returns>
public ErrorOr<File> RenameFile(string path, string name)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return RenameFile(fileSystemPathIdResult.Value, name);
}
/// <summary>
/// Renames a file for the specified path.
/// </summary>
/// <param name="path">Identifier for the file path.</param>
/// <param name="name">The new name of the file.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the renamed file, or an error.</returns>
public ErrorOr<File> RenameFile(FileSystemPathId path, string name)
{
// first, check if the directory about to be created does not already exist
ErrorOr<FileSystemPathId> combinedPath = _platformContext.PathStrategy.CombinePath(path, name);
if (combinedPath.IsError)
return combinedPath.Errors;
ErrorOr<bool> fileExists = _environmentContext.FileProviderService.FileExists(combinedPath.Value);
if (fileExists.IsError)
return fileExists.Errors;
else if (fileExists.Value == true)
return Errors.FileSystemManagement.FileAlreadyExists;
else
{
// rename the file
ErrorOr<FileSystemPathId> newFilePathResult = _environmentContext.FileProviderService.RenameFile(path, name);
if (newFilePathResult.IsError)
return newFilePathResult.Errors;
ErrorOr<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(newFilePathResult.Value);
ErrorOr<Optional<DateTime>> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(newFilePathResult.Value);
ErrorOr<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(newFilePathResult.Value);
ErrorOr<long?> sizeResult = _environmentContext.FileProviderService.GetSize(newFilePathResult.Value);
long size = sizeResult.Value ?? 0;
// if any of the details returned an error, set inaccessible status
if (fileNameResult.IsError || dateModifiedResult.IsError || dateCreatedResult.IsError)
{
ErrorOr<File> errorFileResult = File.Create(newFilePathResult.Value, !fileNameResult.IsError ? fileNameResult.Value : null!,
!dateCreatedResult.IsError ? dateCreatedResult.Value : Optional<DateTime>.None(),
!dateModifiedResult.IsError ? dateModifiedResult.Value : Optional<DateTime>.None(), size);
if (errorFileResult.IsError)
return errorFileResult.Errors;
ErrorOr<Updated> setStatusResult = errorFileResult.Value.SetStatus(FileSystemItemStatus.Inaccessible);
if (setStatusResult.IsError)
return setStatusResult.Errors;
return errorFileResult;
}
else
return File.Create(newFilePathResult.Value, fileNameResult.Value, dateCreatedResult.Value, dateModifiedResult.Value, size);
}
}
/// <summary>
/// Delete a file for the specified string path.
/// </summary>
/// <param name="path">String representation of the file path.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns>
public ErrorOr<Deleted> DeleteFile(string path)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return DeleteFile(fileSystemPathIdResult.Value);
}
/// <summary>
/// Delete a file for the specified string path.
/// </summary>
/// <param name="path">Identifier for the file path.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns>
public ErrorOr<Deleted> DeleteFile(FileSystemPathId path)
{
return _environmentContext.FileProviderService.DeleteFile(path);
}
public ErrorOr<bool> ReadFile(FileSystemPathId path)
{
return true;
}
}
@@ -0,0 +1,199 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Mono.Unix;
using Mono.Unix.Native;
using System;
using System.IO;
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Principal;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Service for file system permissions.
/// </summary>
internal class FileSystemPermissionsService : IFileSystemPermissionsService // TODO: refactor towards abstractions that could allow testing
{
private readonly IPlatformContextManager _platformContextManager;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemPermissionsService"/> class.
/// </summary>
/// <param name="platformContextManager">Injected facade service for platform contextual services.</param>
public FileSystemPermissionsService(IPlatformContextManager platformContextManager)
{
_platformContextManager = platformContextManager;
}
/// <summary>
/// Checks if <paramref name="path"/> can be accessed.
/// </summary>
/// <param name="path">The path to be accessed.</param>
/// <param name="accessMode">The mode in which to access the path.</param>
/// <param name="isFile">Indicates whether the path represents a file or directory.</param>
/// <returns><see langword="true"/>, if <paramref name="path"/> can be accessed, <see langword="false"/> otherwise.</returns>
public bool CanAccessPath(FileSystemPathId path, FileAccessMode accessMode, bool isFile = true)
{
PlatformType platformType = _platformContextManager.GetCurrentContext().Platform;
if (platformType == PlatformType.Unix)
return CanAccessPathLinux(path.Path, accessMode);
else if (platformType == PlatformType.Windows)
#pragma warning disable CA1416 // Validate platform compatibility
return CanAccessPathWindows(path.Path, accessMode, isFile);
#pragma warning restore CA1416 // Validate platform compatibility
else
throw new PlatformNotSupportedException("Support for this platform is not compiled into this assembly.");
}
/// <summary>
/// Checks if a the current user has access permissions on Linux for <paramref name="path"/>, with <paramref name="accessMode"/>.
/// </summary>
/// <param name="path">The path for which to check the access.</param>
/// <param name="accessMode">The access mode in which to check that path access.</param>
/// <returns><see langword="true"/> if the current user has rights for the specified path and acccess mode, <see langword="false"/> otherwise.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when trying to check access for a mode that is not supported</exception>
private static bool CanAccessPathLinux(string path, FileAccessMode accessMode)
{
AccessModes modes;
UnixFileSystemInfo fileInfo = new UnixFileInfo(path);
switch (accessMode)
{
case FileAccessMode.ReadProperties:
// we would typically need execute permissions on a directory, to list its contents or view file properties
if (fileInfo.FileType == FileTypes.Directory)
return fileInfo.CanAccess(AccessModes.X_OK);
// for files, just verifying existence might be sufficient for reading properties
return fileInfo.Exists;
case FileAccessMode.ReadContents:
return fileInfo.CanAccess(AccessModes.R_OK);
case FileAccessMode.Write:
modes = AccessModes.W_OK;
break;
case FileAccessMode.Execute:
modes = AccessModes.X_OK;
break;
case FileAccessMode.ListDirectory:
modes = AccessModes.F_OK; // check existence, not an exact match but the closest
break;
case FileAccessMode.Delete:
if (fileInfo.FileType == FileTypes.Directory)
return fileInfo.CanAccess(AccessModes.W_OK | AccessModes.X_OK); // to delete a directory, we need write and execute permissions on the directory itself
else
{
// to delete a file, we need write permission on the parent directory
string? parentDirectoryPath = Path.GetDirectoryName(path);
if (string.IsNullOrEmpty(parentDirectoryPath))
return false; // if path is a root directory or has no parent, deletion is not possible
UnixDirectoryInfo parentDirectoryInfo = new(parentDirectoryPath);
return parentDirectoryInfo.CanAccess(AccessModes.W_OK);
}
default:
throw new ArgumentOutOfRangeException(nameof(accessMode), "Unknown FileAccessMode");
}
return new UnixDirectoryInfo(path).CanAccess(modes);
}
/// <summary>
/// Checks if a the current user has access permissions on Windows for <paramref name="path"/>, with <paramref name="accessMode"/>.
/// </summary>
/// <param name="path">The path for which to check the access.</param>
/// <param name="accessMode">The access mode in which to check that path access.</param>
/// <param name="isFile">Indicates whether the path represents a file or directory.</param>
/// <returns><see langword="true"/> if the current user has rights for the specified path and acccess mode, <see langword="false"/> otherwise.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when trying to check access for a mode that is not supported.</exception>
[SupportedOSPlatform("windows")]
private static bool CanAccessPathWindows(string path, FileAccessMode accessMode, bool isFile = true)
{
// translate to filesystem access modes (multiple can match per case)
FileSystemRights rights = accessMode switch
{
FileAccessMode.ReadProperties => FileSystemRights.ReadAttributes,
FileAccessMode.ReadContents => FileSystemRights.ReadData | FileSystemRights.ReadExtendedAttributes,
FileAccessMode.Write => FileSystemRights.WriteData | FileSystemRights.AppendData,
FileAccessMode.Execute => FileSystemRights.ExecuteFile,
FileAccessMode.ListDirectory => FileSystemRights.ListDirectory,
FileAccessMode.Delete => FileSystemRights.Delete,
_ => throw new ArgumentOutOfRangeException(nameof(accessMode), "Unknown FileAccessMode"),
};
if (rights == FileSystemRights.Delete)
{
// when checking for delete permissions, we need to check the directory the file or directory resides in
string? parentDirectory = Directory.GetParent(path)?.FullName;
if (string.IsNullOrEmpty(parentDirectory))
return false; // the path is either a root directory or has no parent, which we cannot delete
// checking for modify permission on the parent directory since delete requires modifying the parent contents
return HasAccess(FileSystemRights.Modify, parentDirectory, false);
}
else
if (HasAccess(rights, path, isFile))
try
{
switch (accessMode)
{
case FileAccessMode.ReadProperties:
// just accessing file info for properties, without opening it
FileSystemInfo fileSystemInfo = isFile ? new FileInfo(path) : new DirectoryInfo(path);
_ = fileSystemInfo.CreationTime; // trigger potential access denial
break;
case FileAccessMode.ReadContents:
using (FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
stream.Close();
break;
}
return true;
}
catch
{
return false;
}
return false;
}
/// <summary>
/// Checks if the current user or group has the access <paramref name="rights"/> for <paramref name="path"/>, on Windows platforms.
/// </summary>
/// <param name="rights">The rights for which to check access.</param>
/// <param name="path">The path for which to check the access <paramref name="rights"/>.</param>
/// <param name="isFile">Indicates whether the path represents a file or directory.</param>
/// <returns><see langword="true"/>, if the current user or group has <paramref name="rights"/> for <paramref name="path"/>, <see langword="false"/> otherwise.</returns>
[SupportedOSPlatform("windows")]
private static bool HasAccess(FileSystemRights rights, string path, bool isFile = true)
{
bool allowAccess = false;
AuthorizationRuleCollection acl;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new(identity);
// get the collection of authorization rules that apply to the specified directory
try
{
// some paths (ex: C:\Windows\System32\config) throw "unauthorized" exceptions even when trying to check if one is authorized to access them - how dumb is that??...
if (isFile)
{
FileInfo fileInfo = new(path);
acl = fileInfo.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
}
else
{
DirectoryInfo directoryInfo = new(path);
acl = directoryInfo.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
}
foreach (FileSystemAccessRule accessRule in acl)
// Check if the current rule applies to the current user or the groups they belong to
if (identity?.User?.Equals(accessRule.IdentityReference) == true || principal.IsInRole((SecurityIdentifier)accessRule.IdentityReference))
if (accessRule.AccessControlType.Equals(AccessControlType.Deny) && (accessRule.FileSystemRights & rights) == rights)
return false; // if there's a deny rule that matches the specified rights, return false immediately
else if (accessRule.AccessControlType.Equals(AccessControlType.Allow) && (accessRule.FileSystemRights & rights) == rights)
allowAccess = true;
}
catch
{
return false;
}
return allowAccess;
}
}
@@ -0,0 +1,157 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Enums.PhotoLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using System;
using System.IO.Abstractions;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Class defining methods for handling file-related operations.
/// </summary>
public class FileTypeService : IFileTypeService
{
private readonly IFileSystem _fileSystem;
private readonly IFileSystemPermissionsService _fileSystemPermissionsService;
private const int BUFFER_SIZE = 18; // 18 bytes should be more than enough for common images header types
/// <summary>
/// Initializes a new instance of the <see cref="FileTypeService"/> class.
/// </summary>
/// <param name="fileSystem">Injected service used to interact with the local filesystem.</param>
/// <param name="fileSystemPermissionsService">Injected service used to determine local filesystem permissions.</param>
public FileTypeService(IFileSystem fileSystem, IFileSystemPermissionsService fileSystemPermissionsService)
{
_fileSystem = fileSystem;
_fileSystemPermissionsService = fileSystemPermissionsService;
}
/// <summary>
/// Determines if <paramref name="file"/> is of type image or not, and returns its type.
/// </summary>
/// <param name="file">The file to determine if it is an image or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the type of image or an error.</returns>
public async Task<ErrorOr<ImageType>> GetImageTypeAsync(File file, CancellationToken cancellationToken)
{
return await GetImageTypeAsync(file.Id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Determines if a file identified by <paramref name="path"/> is of type image or not, and returns its type.
/// </summary>
/// <param name="path">The path of the file to determine if it is an image or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the type of image or an error.</returns>
public async Task<ErrorOr<ImageType>> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken)
{
// check if the user has access permissions to the provided path
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents))
return Errors.Permission.UnauthorizedAccess;
Memory<byte> buffer = new byte[BUFFER_SIZE];
using FileSystemStream stream = _fileSystem.FileStream.New(path.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
// check if the file's length is less than the buffer size
if (stream.Length < BUFFER_SIZE)
return ImageType.None;
// read only the first bytes of the file, equal to the buffer size
await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
byte[] firstBytes = buffer[..BUFFER_SIZE].ToArray();
// check if its a known image type, based on header bytes
ImageType type = IdentifyHeader(firstBytes);
if (type != ImageType.None)
return type;
// no known image header types were found, check other methods
string content = Encoding.UTF8.GetString(buffer.ToArray());
if (IsSvg(content, path.Path))
return ImageType.SVG;
else if (IsTga(buffer.ToArray()))
return ImageType.TGA;
else
return ImageType.None;
}
/// <summary>
/// Determines if the content of a file identified by <paramref name="path"/> belongs to a SVG.
/// </summary>
/// <param name="initialContent">The initial content of the file to check.</param>
/// <param name="path">Path of the file to check.</param>
/// <returns><see langword="true"/> if the file is a SVG image, <see langword="false"/> otherwise.</returns>
private bool IsSvg(string initialContent, string path)
{
// check if it starts with <svg
if (initialContent.StartsWith("<svg", StringComparison.OrdinalIgnoreCase))
return true;
// check if it starts with <?xml
if (initialContent.StartsWith("<?xml", StringComparison.OrdinalIgnoreCase))
{
// Read more content from the file
using FileSystemStream stream = _fileSystem.FileStream.New(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
byte[] svgBuffer = new byte[1000];
stream.Read(svgBuffer, 0, 1000);
string extendedContent = Encoding.UTF8.GetString(svgBuffer);
// check if the extended content contains <svg
return extendedContent.Contains("<svg", StringComparison.OrdinalIgnoreCase);
}
return false;
}
/// <summary>
/// Determines if the buffer represents a TGA file.
/// </summary>
/// <param name="buffer">Byte array to check.</param>
/// <returns><see langword="true"/> if the file is a TGA image, <see langword="false"/> otherwise.</returns>
private static bool IsTga(byte[] buffer)
{
if (buffer.Length < 18)
return false;
byte imageType = buffer[2];
return imageType is 1 or 2 or 3 or 9 or 10 or 11;
}
/// <summary>
/// Identifies the image type based on the provided header bytes.
/// </summary>
/// <param name="firstBytes">The first bytes of the file, typically used to identify the file type.</param>
/// <returns>The type of the image, or <see cref="{ImageType.None}"/> if unrecognized.</returns>
private static ImageType IdentifyHeader(byte[] firstBytes)
{
if (Encoding.ASCII.GetBytes("BM").SequenceEqual(firstBytes[..2]))
return ImageType.BMP; // BMP
if (Encoding.ASCII.GetBytes("GIF").SequenceEqual(firstBytes[..3]))
return ImageType.GIF; // GIF
if (new byte[] { 137, 80, 78, 71 }.SequenceEqual(firstBytes[..4]))
return ImageType.PNG; // PNG
if (new byte[] { 73, 73, 42 }.SequenceEqual(firstBytes[..3]) || new byte[] { 77, 77, 42 }.SequenceEqual(firstBytes[..3]))
return ImageType.TIFF; // TIFF
if (new byte[] { 255, 216, 255, 224 }.SequenceEqual(firstBytes[..4]))
return ImageType.JPEG; // JPEG
if (new byte[] { 255, 216, 255, 225 }.SequenceEqual(firstBytes[..4]))
return ImageType.JPEG_CANON; // JPEG CANON
if (new byte[] { 255, 216, 255, 226 }.SequenceEqual(firstBytes[..4]))
return ImageType.JPEG_UNKNOWN; // JPEG UNKNOWN
if (new byte[] { 0x00, 0x11, 0x02, 0xFF }.SequenceEqual(firstBytes[..4]))
return ImageType.PICT; // PICT
if (new byte[] { 0x00, 0x00, 0x01, 0x00 }.SequenceEqual(firstBytes[..4]))
return ImageType.ICO; // ICO
if (new byte[] { 0x38, 0x42, 0x50, 0x53 }.SequenceEqual(firstBytes[..4]))
return ImageType.PSD; // PSD
if (new byte[] { 0xFF, 0x4F, 0xFF, 0x51 }.SequenceEqual(firstBytes[..4]))
return ImageType.JPEG2000; // JPEG 2000
if (new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x70, 0x20, 0x20 }.SequenceEqual(firstBytes[..8]))
return ImageType.AVIF; // AVIF
if (new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20 }.SequenceEqual(firstBytes[..8]))
return ImageType.JPEG2000; // JPEG 2000 (variant)
if (new byte[] { 0x52, 0x49, 0x46, 0x46 }.SequenceEqual(firstBytes[..4]) && new byte[] { 0x57, 0x45, 0x42, 0x50 }.SequenceEqual(firstBytes[8..12]))
return ImageType.WEBP; // WEBP
return ImageType.None;
}
}
@@ -0,0 +1,93 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Interface defining the directory provider service.
/// </summary>
public interface IDirectoryProviderService
{
/// <summary>
/// Retrieves a list of subdirectory paths from the specified path.
/// </summary>
/// <param name="path">The path from which to retrieve the subdirectory paths.</param>
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of directory paths or an error.</returns>
ErrorOr<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements);
/// <summary>
/// Checks if a directory with the specified path exists.
/// </summary>
/// <param name="path">The path of the directory whose existance is checked.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of checking the existance of a directory, or an error.</returns>
ErrorOr<bool> DirectoryExists(FileSystemPathId path);
/// <summary>
/// Retrieves the file name from the specified path.
/// </summary>
/// <param name="path">The path to extract the file name from.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a file name or an error.</returns>
ErrorOr<string> GetFileName(FileSystemPathId path);
/// <summary>
/// Gets the last write time of a specific path.
/// </summary>
/// <param name="path">The path to retrieve the last write time for.</param>
/// <returns>The last write time for the specified path, or null if unavailable.</returns>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the optional last write time of <paramref name="path"/> if available, or an error.</returns>
ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path);
/// <summary>
/// Gets the creation time of a specific path.
/// </summary>
/// <param name="path">The path to retrieve the creation time for.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the optional creation time of <paramref name="path"/> if available, or an error.</returns>
ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path);
/// <summary>
/// Creates a new directory with the specified name, at the specified path.
/// </summary>
/// <param name="path">The path where the directory will be created.</param>
/// <param name="name">The name of the directory that will be created.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the path of a created directory, or an error.</returns>
ErrorOr<FileSystemPathId> CreateDirectory(FileSystemPathId path, string name);
/// <summary>
/// Copies a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourcePath">Identifier for the path where the directory to be copied is located.</param>
/// <param name="destinationPath">Identifier for the path where the directory will be copied.</param>
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied directory, or an error.</returns>
ErrorOr<FileSystemPathId> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting);
/// <summary>
/// Moves a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourcePath">Identifier for the path where the directory to be moved is located.</param>
/// <param name="destinationPath">Identifier for the path where the directory will be moved.</param>
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved directory, or an error.</returns>
ErrorOr<FileSystemPathId> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting);
/// <summary>
/// Renames a directory at the specified path.
/// </summary>
/// <param name="path">The path of the directory to be renamed.</param>
/// <param name="name">The new name of the directory.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the absolute path of the renamed directory, or an error.</returns>
ErrorOr<FileSystemPathId> RenameDirectory(FileSystemPathId path, string name);
/// <summary>
/// Deletes a directory at the specified path.
/// </summary>
/// <param name="path">The path of the directory to be deleted.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
ErrorOr<Deleted> DeleteDirectory(FileSystemPathId path);
}
@@ -0,0 +1,79 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Interface for the service for handling directories.
/// </summary>
public interface IDirectoryService
{
/// <summary>
/// Retrieves subdirectories for the specified string path.
/// </summary>
/// <param name="path">String representation of the file path.</param>
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
ErrorOr<IEnumerable<Directory>> GetSubdirectories(string path, bool includeHiddenElements);
/// <summary>
/// Retrieves subdirectories for the given directory.
/// </summary>
/// <param name="directory">Directory object to retrieve subdirectories for.</param>
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
ErrorOr<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool includeHiddenElements);
/// <summary>
/// Retrieves subdirectories for the specified file system path.
/// </summary>
/// <param name="path">Identifier for the file path.</param>
/// <param name="includeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of subdirectories or an error.</returns>
ErrorOr<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements);
/// <summary>
/// Creates a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
/// </summary>
/// <param name="path">String representation of the path where the directory will be created.</param>
/// <param name="name">The name of the directory that will be created.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a created directory, or an error.</returns>
ErrorOr<Directory> CreateDirectory(string path, string name);
/// <summary>
/// Copies a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourcePath">String representation of the path where the directory to be copied is located.</param>
/// <param name="destinationPath">String representation of the path where the directory will be copied.</param>
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a copied directory, or an error.</returns>
ErrorOr<Directory> CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting);
/// <summary>
/// Moves a directory located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourcePath">String representation of the path where the directory to be moved is located.</param>
/// <param name="destinationPath">String representation of the path where the directory will be moved.</param>
/// <param name="overrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved directory, or an error.</returns>
ErrorOr<Directory> MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting);
/// <summary>
/// Renames a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
/// </summary>
/// <param name="path">String representation of the path of the directory that will be renamed.</param>
/// <param name="name">The new name of the directory.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a renamed directory, or an error.</returns>
ErrorOr<Directory> RenameDirectory(string path, string name);
/// <summary>
/// Delete a directory for the specified string path.
/// </summary>
/// <param name="path">String representation of the directory path.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
ErrorOr<Deleted> DeleteDirectory(string path);
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Interface for the service for handling drives.
/// </summary>
public interface IDriveService
{
/// <summary>
/// Retrieves the list of drives.
/// </summary>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of drives or an error.</returns>
ErrorOr<IEnumerable<FileSystemItem>> GetDrives();
}
@@ -0,0 +1,98 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Interface defining the file provider service.
/// </summary>
public interface IFileProviderService
{
/// <summary>
/// Retrieves a list of files at the specified path.
/// </summary>
/// <param name="path">The path for which to retrieve the list of files.</param>
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of file paths, or an error.</returns>
ErrorOr<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path, bool includeHiddenElements);
/// <summary>
/// Retrieves the contents of a file at the specified path.
/// </summary>
/// <param name="path">The path for which to retrieve the file contents.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the contents of a file at the specified path, or an error.</returns>
ErrorOr<byte[]> GetFileAsync(FileSystemPathId path);
/// <summary>
/// Checks if a file with the specified path exists.
/// </summary>
/// <param name="path">The path of the file whose existance is checked.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of checking the existance of a file, or an error.</returns>
ErrorOr<bool> FileExists(FileSystemPathId path);
/// <summary>
/// Retrieves the file name from the specified path.
/// </summary>
/// <param name="path">The path to extract the file name from.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the name of the file without the path, or the last segment of the path if no file name is found, or an error.</returns>
ErrorOr<string> GetFileName(FileSystemPathId path);
/// <summary>
/// Gets the last write time of a file at the specified path.
/// </summary>
/// <param name="path">The path of the file to retrieve the last write time for.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the optional last write time of <paramref name="path"/> if available, or an error.</returns>
ErrorOr<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path);
/// <summary>
/// Gets the creation time of a file at the specified path.
/// </summary>
/// <param name="path">The path of the file to retrieve the creation time for.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the otional creation time of <paramref name="path"/> if available, or an error.</returns>
ErrorOr<Optional<DateTime>> GetCreationTime(FileSystemPathId path);
/// <summary>
/// Gets the size of a file at the specified path.
/// </summary>
/// <param name="path">The path of the file to retrieve the size for.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the size of <paramref name="path"/> or an error.</returns>
ErrorOr<long?> GetSize(FileSystemPathId path);
/// <summary>
/// Copies a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
/// </summary>
/// <param name="sourceFilePath">Identifier for the path where the file to be copied is located.</param>
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be copied.</param>
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the copied file, or an error.</returns>
ErrorOr<FileSystemPathId> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting);
/// <summary>
/// Moves a file located at <paramref name="sourceFilePath"/> to <paramref name="destinationDirectoryPath"/>.
/// </summary>
/// <param name="sourceFilePath">Identifier for the path where the file to be moved is located.</param>
/// <param name="destinationDirectoryPath">Identifier for the path of the directory where the file will be moved.</param>
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved file, or an error.</returns>
ErrorOr<FileSystemPathId> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting);
/// <summary>
/// Renames a file at the specified path.
/// </summary>
/// <param name="path">The path of the file to be renamed.</param>
/// <param name="name">The new name of the file.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the absolute path of the renamed file, or an error.</returns>
ErrorOr<FileSystemPathId> RenameFile(FileSystemPathId path, string name);
/// <summary>
/// Deletes a file at the specified path.
/// </summary>
/// <param name="path">The path of the file to be deleted.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns>
ErrorOr<Deleted> DeleteFile(FileSystemPathId path);
}
@@ -0,0 +1,71 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Interface for the service for handling file system files.
/// </summary>
public interface IFileService
{
/// <summary>
/// Retrieves files for the specified string path.
/// </summary>
/// <param name="path">String representation of the file path.</param>
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
ErrorOr<IEnumerable<File>> GetFiles(string path, bool includeHiddenElements);
/// <summary>
/// Retrieves files associated with a given file.
/// </summary>
/// <param name="file">The file object.</param>
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
ErrorOr<IEnumerable<File>> GetFiles(File file, bool includeHiddenElements);
/// <summary>
/// Retrieves files for a specified file path ID.
/// </summary>
/// <param name="path">Identifier for the file path.</param>
/// <param name="includeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of files or an error.</returns>
ErrorOr<IEnumerable<File>> GetFiles(FileSystemPathId path, bool includeHiddenElements);
/// <summary>
/// Copies a file located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourcePath">String representation of the path where the file to be copied is located.</param>
/// <param name="destinationPath">String representation of the path where the file will be copied.</param>
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a copied file, or an error.</returns>
ErrorOr<File> CopyFile(string sourcePath, string destinationPath, bool? overrideExisting);
/// <summary>
/// Moves a file located at <paramref name="sourcePath"/> to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourcePath">String representation of the path where the file to be moved is located.</param>
/// <param name="destinationPath">String representation of the path where the file will be moved.</param>
/// <param name="overrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a moved file, or an error.</returns>
ErrorOr<File> MoveFile(string sourcePath, string destinationPath, bool? overrideExisting);
/// <summary>
/// Renames a file with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
/// </summary>
/// <param name="path">String representation of the path of the file that will be renamed.</param>
/// <param name="name">The new name of the file.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a renamed file, or an error.</returns>
ErrorOr<File> RenameFile(string path, string name);
/// <summary>
/// Delete a file for the specified string path.
/// </summary>
/// <param name="path">String representation of the file path.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the result of deleting a file, or an error.</returns>
ErrorOr<Deleted> DeleteFile(string path);
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Interface for file system permission service.
/// </summary>
public interface IFileSystemPermissionsService
{
/// <summary>
/// Checks if <paramref name="path"/> can be accessed.
/// </summary>
/// <param name="path">The path to be accessed.</param>
/// <param name="accessMode">The mode in which to access the path.</param>
/// <param name="isFile">Indicates whether the path represents a file or directory.</param>
/// <returns><see langword="true"/>, if <paramref name="path"/> can be accessed, <see langword="false"/> otherwise.</returns>
bool CanAccessPath(FileSystemPathId path, FileAccessMode accessMode, bool isFile = true);
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.PhotoLibrary;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Interface defining methods for handling file-related operations based on different sources.
/// </summary>
public interface IFileTypeService
{
/// <summary>
/// Determines if <paramref name="file"/> is of type image or not, and returns its type.
/// </summary>
/// <param name="file">The file to determine if it is an image or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the type of image or an error.</returns>
Task<ErrorOr<ImageType>> GetImageTypeAsync(File file, CancellationToken cancellationToken);
/// <summary>
/// Determines if a file identified by <paramref name="path"/> is of type image or not, and returns its type.
/// </summary>
/// <param name="path">The path of the file to determine if it is an image or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the type of image or an error.</returns>
Task<ErrorOr<ImageType>> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken);
}
@@ -0,0 +1,68 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Interface for the service for handling file system paths.
/// </summary>
public interface IPathService
{
/// <summary>
/// Gets the character used to separate path segments.
/// </summary>
char PathSeparator { get; }
/// <summary>
/// Checks if <paramref name="path"/> is a valid path.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
bool IsValidPath(string path);
/// <summary>
/// Checks if <paramref name="path"/> exists.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns><see langword="true"/> if <paramref name="path"/> exists, <see langword="false"/> otherwise.</returns>
bool Exists(string path, bool includeHiddenElements = true);
/// <summary>
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
/// </summary>
/// <param name="path">The path to be combined.</param>
/// <param name="path">The name to be combined with the path.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the combined path, or an error.</returns>
ErrorOr<string> CombinePath(string path, string name);
/// <summary>
/// Parses <paramref name="path"/> into path segments.
/// </summary>
/// <param name="path">The path to be parsed.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments, or an error.</returns>
ErrorOr<IEnumerable<PathSegment>> ParsePath(string path);
/// <summary>
/// Goes up one level from <paramref name="path"/>, and returns the path segments.
/// </summary>
/// <param name="path">The path from which to navigate up one level.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(string path);
/// <summary>
/// Returns a collection of characters that are invalid for paths.
/// </summary>
/// <returns>A collection of characters that are invalid in the context of paths.</returns>
char[] GetInvalidPathCharsForPlatform();
/// <summary>
/// Returns the root portion of the given path.
/// </summary>
/// <param name="path">The path for which to get the root.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the root of <paramref name="path"/>, or an error.</returns>
ErrorOr<PathSegment> GetPathRoot(string path);
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Interface for the service for handling thumbnails.
/// </summary>
public interface IThumbnailService
{
/// <summary>
/// Gets the thumbnail of a file at the specified path.
/// </summary>
/// <param name="path">String representation of the file path.</param>
/// <param name="quality">The quality of the thumbnail to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.</returns>
Task<ErrorOr<Thumbnail>> GetThumbnailAsync(string path, int quality, CancellationToken cancellationToken);
/// <summary>
/// Gets the thumbnail of a file at the specified path.
/// </summary>
/// <param name="path">The path object.</param>
/// <param name="quality">The quality of the thumbnail to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.</returns>
Task<ErrorOr<Thumbnail>> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken);
}
@@ -0,0 +1,125 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Service defining methods for handling path-related operations.
/// </summary>
public class PathService : IPathService
{
private readonly IPlatformContext _platformContext;
/// <summary>
/// Gets the character used to separate path segments.
/// </summary>
public char PathSeparator => _platformContext.PathStrategy.PathSeparator;
/// <summary>
/// Initializes a new instance of the <see cref="PathService"/> class.
/// </summary>
/// <param name="platformContextManager">Injected facade service for platform contextual services.</param>
public PathService(IPlatformContextManager platformContextManager)
{
_platformContext = platformContextManager.GetCurrentContext();
}
/// <summary>
/// Checks if <paramref name="path"/> is a valid path.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
public bool IsValidPath(string path)
{
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return false;
return _platformContext.PathStrategy.IsValidPath(newPathResult.Value);
}
/// <summary>
/// Checks if <paramref name="path"/> exists.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns><see langword="true"/> if <paramref name="path"/> exists, <see langword="false"/> otherwise.</returns>
public bool Exists(string path, bool includeHiddenElements = true)
{
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return false;
return _platformContext.PathStrategy.Exists(newPathResult.Value, includeHiddenElements);
}
/// <summary>
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
/// </summary>
/// <param name="path">The path to be combined.</param>
/// <param name="path">The name to be combined with the path.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the combined path, or an error.</returns>
public ErrorOr<string> CombinePath(string path, string name)
{
if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(name))
return Errors.FileSystemManagement.InvalidPath;
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return newPathResult.Errors;
ErrorOr<FileSystemPathId> combinedPathResult = _platformContext.PathStrategy.CombinePath(newPathResult.Value, name);
if (combinedPathResult.IsError)
return combinedPathResult.Errors;
return combinedPathResult.Value.Path;
}
/// <summary>
/// Parses <paramref name="path"/> into path segments.
/// </summary>
/// <param name="path">The path to be parsed.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments, or an error.</returns>
public ErrorOr<IEnumerable<PathSegment>> ParsePath(string path)
{
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return newPathResult.Errors;
return _platformContext.PathStrategy.ParsePath(newPathResult.Value);
}
/// <summary>
/// Goes up one level from <paramref name="path"/>, and returns the path segments.
/// </summary>
/// <param name="path">The path from which to navigate up one level.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
public ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(string path)
{
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return newPathResult.Errors;
return _platformContext.PathStrategy.GoUpOneLevel(newPathResult.Value);
}
/// <summary>
/// Returns a collection of characters that are invalid for paths.
/// </summary>
/// <returns>A collection of characters that are invalid in the context of paths.</returns>
public char[] GetInvalidPathCharsForPlatform()
{
return _platformContext.PathStrategy.GetInvalidPathCharsForPlatform();
}
/// <summary>
/// Returns the root portion of the given path.
/// </summary>
/// <param name="path">The path for which to get the root.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the root of <paramref name="path"/>, or an error.</returns>
public ErrorOr<PathSegment> GetPathRoot(string path)
{
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsError)
return newPathResult.Errors;
return _platformContext.PathStrategy.GetPathRoot(newPathResult.Value);
}
}
@@ -0,0 +1,189 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.PhotoLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.Processing;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
/// <summary>
/// Service for handling thumbnails.
/// </summary>
public class ThumbnailService : IThumbnailService
{
private readonly IEnvironmentContext _environmentContext;
/// <summary>
/// Initializes a new instance of the <see cref="ThumbnailService"/> class.
/// </summary>
/// <param name="environmentContext">Injected environment context.</param>
public ThumbnailService(IEnvironmentContext environmentContext)
{
_environmentContext = environmentContext;
}
/// <summary>
/// Gets the thumbnail of a file at the specified path.
/// </summary>
/// <param name="path">String representation of the file path.</param>
/// <param name="quality">The quality of the thumbnail to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.</returns>
public async Task<ErrorOr<Thumbnail>> GetThumbnailAsync(string path, int quality, CancellationToken cancellationToken)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
return await GetThumbnailAsync(fileSystemPathIdResult.Value, quality, cancellationToken);
}
/// <summary>
/// Gets the thumbnail of a file at the specified path.
/// </summary>
/// <param name="path">The path of the file for which to get the thumbnail.</param>
/// <param name="quality">The quality of the thumbnail to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of bytes representing the thumbnail of the file at the specified path or an error.</returns>
public async Task<ErrorOr<Thumbnail>> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken)
{
// first, get the type of the image file
ErrorOr<ImageType> imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path, cancellationToken);
if (imageTypeResult.IsError)
return imageTypeResult.Errors;
if (imageTypeResult.Value != ImageType.None)
{
// then, get its bytes
ErrorOr<byte[]> resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path);
if (resultFileContents.IsError)
return resultFileContents.Errors;
byte[] fileContents = resultFileContents.Value;
// finally, resize or adjust quality based on image type
byte[]? adjustedImage = null;
if (imageTypeResult.Value is ImageType.JPEG or ImageType.JPEG_CANON or ImageType.JPEG2000
or ImageType.JPEG_UNKNOWN or ImageType.PNG or ImageType.BMP
or ImageType.WEBP or ImageType.GIF or ImageType.TIFF or ImageType.TGA)
adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality, cancellationToken);
return new Thumbnail(imageTypeResult.Value, adjustedImage ?? fileContents);
}
else
return Errors.Thumbnails.NoThumbnail;
}
/// <summary>
/// Adjusts the quality or compression of an image, based on its format.
/// </summary>
/// <param name="imageBytes">The byte array of the source image.</param>
/// <param name="imageType">The format of the image whose quality is adjusted.</param>
/// <param name="quality">A value between 1 (lowest quality) to 100 (highest quality).</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A byte array representing the processed image.</returns>
private static async Task<byte[]> AdjustImageQualityAsync(byte[] imageBytes, ImageType imageType, int quality, CancellationToken cancellationToken)
{
using MemoryStream inputMemoryStream = new(imageBytes);
using MemoryStream outputMemoryStream = new();
switch (imageType)
{
case ImageType.JPEG:
case ImageType.JPEG2000:
case ImageType.JPEG_CANON:
case ImageType.JPEG_UNKNOWN:
{
using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken);
await image.SaveAsync(outputMemoryStream, new JpegEncoder() { Quality = quality }, cancellationToken);
break;
}
case ImageType.PNG:
{
using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken);
// PNG is lossless; quality adjustments don't apply in the same way - we can adjust compression
int compressionLevel = MapRange(quality, 1, 100, 1, 9);
PngEncoder encoder = new()
{ CompressionLevel = (PngCompressionLevel)compressionLevel };
await image.SaveAsync(outputMemoryStream, encoder, cancellationToken);
break;
}
case ImageType.BMP:
{
using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken);
await image.SaveAsync(outputMemoryStream, new PngEncoder(), cancellationToken); // convert BMP to PNG for compression
break;
}
default:
return imageBytes; // for unsupported formats, just return the original bytes
}
return outputMemoryStream.ToArray();
}
/// <summary>
/// Adjusts the quality or size of an image, based on its format.
/// </summary>
/// <param name="imageBytes">The byte array of the source image.</param>
/// <param name="imageType">The format of the image whose quality is adjusted.</param>
/// <param name="quality">A value between 1 (lowest quality) to 100 (highest quality).</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The bytes of the adjusted image.</returns>
private static async Task<byte[]> AdjustImageResolutionAsync(byte[] imageBytes, ImageType imageType, int quality, CancellationToken cancellationToken)
{
using MemoryStream inputMemoryStream = new(imageBytes);
using MemoryStream outputMemoryStream = new();
Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken);
double ratio = quality / 100.0;
int newWidth = (int)(image.Width * ratio);
int newHeight = (int)(image.Height * ratio);
// ensure new dimensions are not zero
newWidth = Math.Max(1, newWidth);
newHeight = Math.Max(1, newHeight);
ResizeOptions options = new()
{
Size = new Size(newWidth, newHeight),
Mode = ResizeMode.Max
};
// resize the image to the specified size
image.Mutate(ctx => ctx.Resize(options));
// save the resized image and return its bytes
switch (imageType)
{
case ImageType.BMP:
case ImageType.PNG:
case ImageType.GIF:
case ImageType.TGA:
case ImageType.WEBP:
case ImageType.TIFF:
case ImageType.JPEG:
case ImageType.JPEG2000:
case ImageType.JPEG_CANON:
case ImageType.JPEG_UNKNOWN:
await image.SaveAsync(outputMemoryStream, image.Metadata.DecodedImageFormat!, cancellationToken);
break;
default:
return imageBytes; // for unsupported formats, just return the original bytes
}
return outputMemoryStream.ToArray();
}
/// <summary>
/// Maps a given value from a source range to a target range.
/// </summary>
/// <param name="value">The value to map.</param>
/// <param name="fromSource">The inclusive lower bound of the source range.</param>
/// <param name="toSource">The inclusive upper bound of the source range.</param>
/// <param name="fromTarget">The inclusive lower bound of the target range.</param>
/// <param name="toTarget">The inclusive upper bound of the target range.</param>
/// <returns>
/// A value mapped to the target range.
/// </returns>
private static int MapRange(int value, int fromSource, int toSource, int fromTarget, int toTarget)
{
return ((value - fromSource) * (toTarget - fromTarget) / (toSource - fromSource)) + fromTarget;
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
/// <summary>
/// Represents the context for environment-specific operations and services.
/// </summary>
internal class EnvironmentContext : IEnvironmentContext
{
/// <summary>
/// Gets the service for identifying and handling different file types.
/// </summary>
public IFileTypeService FileTypeService { get; private set; }
/// <summary>
/// Gets the service for performing file-related operations.
/// </summary>
public IFileProviderService FileProviderService { get; private set; }
/// <summary>
/// Gets the service for performing directory-related operations.
/// </summary>
public IDirectoryProviderService DirectoryProviderService { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="EnvironmentContext"/> class.
/// </summary>
/// <param name="directoryProviderService">Injected service for directory providers.</param>
/// <param name="fileProviderService">Injected service for file providers.</param>
/// <param name="fileTypeService">Injected service for file type.</param>
public EnvironmentContext(IDirectoryProviderService directoryProviderService, IFileProviderService fileProviderService, IFileTypeService fileTypeService)
{
FileTypeService = fileTypeService;
FileProviderService = fileProviderService;
DirectoryProviderService = directoryProviderService;
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
/// <summary>
/// Interface for defining the contract of an environment-specific context, encapsulating all platform-specific services and strategies.
/// </summary>
public interface IEnvironmentContext
{
/// <summary>
/// Gets the service for identifying and handling different file types.
/// </summary>
IFileTypeService FileTypeService { get; }
/// <summary>
/// Gets the service for providing file system files.
/// </summary>
IFileProviderService FileProviderService { get; }
/// <summary>
/// Gets the service for providing file system directories.
/// </summary>
IDirectoryProviderService DirectoryProviderService { get; }
}
@@ -0,0 +1,65 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
/// <summary>
/// Interface defining methods for handling path-related operations based on different platforms.
/// </summary>
public interface IPathStrategy
{
public char PathSeparator { get; }
/// <summary>
/// Checks if <paramref name="path"/> is a valid path.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
bool IsValidPath(FileSystemPathId path);
/// <summary>
/// Checks if <paramref name="path"/> exists.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns><see langword="true"/> if <paramref name="path"/> exists, <see langword="false"/> otherwise.</returns>
bool Exists(FileSystemPathId path, bool includeHiddenElements = true);
/// <summary>
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
/// </summary>
/// <param name="path">The path to be combined.</param>
/// <param name="path">The name to be combined with the path.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the combined path, or an error.</returns>
ErrorOr<FileSystemPathId> CombinePath(FileSystemPathId path, string name);
/// <summary>
/// Parses <paramref name="path"/> into path segments.
/// </summary>
/// <param name="path">The path to be parsed.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments, or an error.</returns>
ErrorOr<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path);
/// <summary>
/// Goes up one level from <paramref name="path"/>, and returns the path segments.
/// </summary>
/// <param name="path">The path from which to navigate up one level.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(FileSystemPathId path);
/// <summary>
/// Returns a collection of characters that are invalid for paths.
/// </summary>
/// <returns>A collection of characters that are invalid in the context of paths</returns>
char[] GetInvalidPathCharsForPlatform();
/// <summary>
/// Returns the root portion of the given path.
/// </summary>
/// <param name="path">The path for which to get the root.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the root of <paramref name="path"/>, or an error.</returns>
ErrorOr<PathSegment> GetPathRoot(FileSystemPathId path);
}
@@ -0,0 +1,8 @@
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
/// <summary>
/// Interface defining methods for handling path-related operations on UNIX platforms.
/// </summary>
public interface IUnixPathStrategy : IPathStrategy
{
}
@@ -0,0 +1,8 @@
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
/// <summary>
/// Interface defining methods for handling path-related operations on Windows platforms.
/// </summary>
public interface IWindowsPathStrategy : IPathStrategy
{
}
@@ -0,0 +1,172 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
/// <summary>
/// Service defining methods for handling path-related operations on UNIX platforms.
/// </summary>
public class UnixPathStrategy : IUnixPathStrategy
{
private readonly IFileSystem _fileSystem;
public char PathSeparator => '/';
/// <summary>
/// Initializes a new instance of the <see cref="UnixPathStrategy"/> class.
/// </summary>
/// <param name="fileSystem">Injected service used to interact with the local filesystem.</param>
public UnixPathStrategy(IFileSystem fileSystem)
{
_fileSystem = fileSystem;
}
/// <summary>
/// Checks if <paramref name="path"/> is a valid path.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
public bool IsValidPath(FileSystemPathId path)
{
// check for invalid path characters
char[] invalidChars = GetInvalidPathCharsForPlatform();
if (path.Path.IndexOfAny(invalidChars) >= 0)
return false;
// check for relative paths
if (path.Path.StartsWith("./") || path.Path.StartsWith("../"))
return false;
const string PATH_PATTERN = @"^\/([\w\-\.\~!$&'()*+,;=:@\[\] ]+(\/[\w\-\.\~!$&'()*+,;=:@\[\] ]+)*)?\/?$";
return Regex.IsMatch(path.Path, PATH_PATTERN);
}
/// <summary>
/// Checks if <paramref name="path"/> exists.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns><see langword="true"/> if <paramref name="path"/> exists, <see langword="false"/> otherwise.</returns>
public bool Exists(FileSystemPathId path, bool includeHiddenElements = true)
{
if (!_fileSystem.Path.Exists(path.Path))
return false;
bool isHidden;
if (_fileSystem.Directory.Exists(path.Path))
{
IDirectoryInfo dirInfo = _fileSystem.DirectoryInfo.New(path.Path);
isHidden = (dirInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
}
else if (_fileSystem.File.Exists(path.Path))
{
IFileInfo fileInfo = _fileSystem.FileInfo.New(path.Path);
isHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
}
else // path exists but is neither a file nor a directory (drive, etc)
return true;
return includeHiddenElements || !isHidden;
}
/// <summary>
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
/// </summary>
/// <param name="path">The path to be combined.</param>
/// <param name="name">The name to be combined with the path.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the combined path, or an error.</returns>
public ErrorOr<FileSystemPathId> CombinePath(FileSystemPathId path, string name)
{
if (string.IsNullOrWhiteSpace(name))
return Errors.FileSystemManagement.NameCannotBeEmpty;
// trim any directory separator characters from the end of the path
string subpath = path.Path.TrimEnd(PathSeparator);
// if the name begins with a directory separator, remove it
name = name.TrimStart(PathSeparator);
// combine the two parts with the Unix directory separator character
return FileSystemPathId.Create(subpath + PathSeparator + name + PathSeparator);
}
/// <summary>
/// Parses <paramref name="path"/> into path segments.
/// </summary>
/// <param name="path">The path to be parsed.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments, or an error.</returns>
public ErrorOr<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path)
{
// if path starts with anything other than '/', it's considered relative and invalid for this parser
if (!path.Path.StartsWith(PathSeparator))
return Errors.FileSystemManagement.InvalidPath;
// get the path segments
List<string> splitSegments = [.. path.Path.Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries)];
IEnumerable<ErrorOr<PathSegment>> segmentsResults = splitSegments.Select((segment, index) =>
{
bool isDirectory;
if (segment.Contains('.'))
isDirectory = index != splitSegments.Count - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the path ends with a '/'
else
isDirectory = true;
return PathSegment.Create(segment, isDirectory, isDrive: false);
}).Prepend(PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true)); // UNIX paths have '/' as "root drive"
foreach (ErrorOr<PathSegment> segment in segmentsResults)
if (segment.IsError)
return segment.Errors;
return ErrorOrFactory.From(segmentsResults.Select(segmentResult => segmentResult.Value));
}
/// <summary>
/// Goes up one level from <paramref name="path"/>, and returns the path segments.
/// </summary>
/// <param name="path">The path from which to navigate up one level.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
public ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(FileSystemPathId path)
{
// validation: ensure the path is not null or empty
if (!IsValidPath(path))
return Errors.FileSystemManagement.InvalidPath;
// trim trailing slash for consistent processing
string tempPath = path.Path;
if (tempPath.EndsWith('/'))
tempPath = tempPath.TrimEnd(PathSeparator);
// find the last occurrence of a slash
int lastIndex = tempPath.LastIndexOf(PathSeparator);
// if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error
if (lastIndex < 0)
return Errors.FileSystemManagement.CannotNavigateUp;
// return the path up to the last slash, or, if there's only the root slash, return that one instead
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]);
if (newPathResult.IsError)
return newPathResult.Errors;
return ParsePath(newPathResult.Value);
}
/// <summary>
/// Returns a collection of characters that are invalid for paths.
/// </summary>
/// <returns>A collection of characters that are invalid in the context of paths</returns>
public char[] GetInvalidPathCharsForPlatform()
{
return ['\0'];
}
/// <summary>
/// Returns the root portion of the given path.
/// </summary>
/// <param name="path">The path for which to get the root.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the root of <paramref name="path"/>, or an error.</returns>
public ErrorOr<PathSegment> GetPathRoot(FileSystemPathId path)
{
if (!IsValidPath(path))
return Errors.FileSystemManagement.InvalidPath;
// On Unix-like systems, the root is always "/"
if (path.Path.StartsWith(PathSeparator))
return PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true);
return Errors.FileSystemManagement.InvalidPath;
}
}
@@ -0,0 +1,226 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
/// <summary>
/// Service defining methods for handling path-related operations on Windows platforms.
/// </summary>
public class WindowsPathStrategy : IWindowsPathStrategy
{
private readonly IFileSystem _fileSystem;
public char PathSeparator => '\\';
/// <summary>
/// Initializes a new instance of the <see cref="WindowsPathStrategy"/> class.
/// </summary>
/// <param name="fileSystem">Injected service used to interact with the local filesystem.</param>
public WindowsPathStrategy(IFileSystem fileSystem)
{
_fileSystem = fileSystem;
}
/// <summary>
/// Checks if <paramref name="path"/> is a valid path.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <returns><see langword="true"/> if <paramref name="path"/> is a valid path, <see langword="false"/> otherwise.</returns>
public bool IsValidPath(FileSystemPathId path)
{
// check for invalid path characters
char[] invalidChars = GetInvalidPathCharsForPlatform();
if (path.Path.IndexOfAny(invalidChars) >= 0)
return false;
// regular expression to match valid absolute paths
// this allows drive letters (e.g., C:\) and UNC paths (e.g., \\server\share)
const string PATH_PATTERN = @"^(?:[a-zA-Z]:\\|\\\\[a-zA-Z0-9\s()._&+,\[\]-]+\\[a-zA-Z0-9\s()._&+,\[\]-]+)(?:[a-zA-Z0-9\s()._&+,\[\]-]+\\)*[a-zA-Z0-9\s()._&+,\[\]-]*\\?$";
return Regex.IsMatch(path.Path, PATH_PATTERN);
}
/// <summary>
/// Checks if <paramref name="path"/> exists.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns><see langword="true"/> if <paramref name="path"/> exists, <see langword="false"/> otherwise.</returns>
public bool Exists(FileSystemPathId path, bool includeHiddenElements = true)
{
if (!_fileSystem.Path.Exists(path.Path))
return false;
bool isHidden;
if (_fileSystem.Directory.Exists(path.Path))
{
IDirectoryInfo dirInfo = _fileSystem.DirectoryInfo.New(path.Path);
isHidden = (dirInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
}
else if (_fileSystem.File.Exists(path.Path))
{
IFileInfo fileInfo = _fileSystem.FileInfo.New(path.Path);
isHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
}
else // path exists but is neither a file nor a directory (drive, etc)
return true;
return includeHiddenElements || !isHidden;
}
/// <summary>
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
/// </summary>
/// <param name="path">The path to be combined.</param>
/// <param name="name">The name to be combined with the path.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the combined path, or an error.</returns>
public ErrorOr<FileSystemPathId> CombinePath(FileSystemPathId path, string name)
{
if (name == null)
return Errors.FileSystemManagement.NameCannotBeEmpty;
// trim any directory separator characters from the end of the path
string subpath = path.Path.TrimEnd(PathSeparator);
// if the name begins with a directory separator, remove it
name = name.TrimStart(PathSeparator);
// combine the two parts with the Windows directory separator character
return FileSystemPathId.Create(subpath + PathSeparator + name + PathSeparator);
}
/// <summary>
/// Parses <paramref name="path"/> into path segments.
/// </summary>
/// <param name="path">The path to be parsed.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments, or an error.</returns>
public ErrorOr<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path)
{
// Windows paths usually start with a drive letter and colon, e.g., "C:", or "\\" (UNC paths)
if (!(path.Path.StartsWith(@"\\") || (path.Path.Length >= 3 && char.IsLetter(path.Path[0]) && path.Path[1] == ':' && path.Path[2] == PathSeparator)))
return Errors.FileSystemManagement.InvalidPath;
IEnumerable<ErrorOr<PathSegment>> getPathSegmentsResults = GetPathSegments();
foreach (ErrorOr<PathSegment> getPathSegmentsResult in getPathSegmentsResults)
if (getPathSegmentsResult.IsError)
return getPathSegmentsResult.Errors;
return ErrorOrFactory.From(getPathSegmentsResults.Select(getPathSegmentsResult => getPathSegmentsResult.Value));
IEnumerable<ErrorOr<PathSegment>> GetPathSegments()
{
if (path.Path.StartsWith(@"\\"))
{
// handle UNC path
yield return PathSegment.Create(@"\\", isDirectory: false, isDrive: true);
string[] segments = path.Path[2..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < segments.Length; i++)
yield return CreatePathSegment(segments[i], i, segments.Length);
}
else // handle regular Windows path
{
// the drive segment
yield return PathSegment.Create(path.Path[..2], isDirectory: false, isDrive: true);
// extract the other segments
string[] segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < segments.Length; i++)
{
string segment = segments[i];
bool isDirectory;
if (segment.Contains('.'))
isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the next segment also contains a path delimiter
else
isDirectory = true;
yield return PathSegment.Create(segment, isDirectory, isDrive: false);
}
}
}
ErrorOr<PathSegment> CreatePathSegment(string segment, int index, int totalSegments)
{
bool isDirectory = segment.Contains('.')
? index != totalSegments - 1 || path.Path.EndsWith(PathSeparator)
: true;
return PathSegment.Create(segment, isDirectory, isDrive: false);
}
}
/// <summary>
/// Goes up one level from <paramref name="path"/>, and returns the path segments.
/// </summary>
/// <param name="path">The path from which to navigate up one level.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
public ErrorOr<IEnumerable<PathSegment>> GoUpOneLevel(FileSystemPathId path)
{
// validation: ensure the path is not null or empty
if (!IsValidPath(path))
return Errors.FileSystemManagement.InvalidPath;
// trim trailing backslash for consistent processing
string tempPath = path.Path.TrimEnd(PathSeparator);
// check for UNC path
if (tempPath.StartsWith(@"\\"))
{
string[] parts = tempPath.Split(PathSeparator, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length <= 2)
return Errors.FileSystemManagement.CannotNavigateUp;
// if it's a single-level UNC path, return the UNC root
if (parts.Length == 3)
return ParsePath(FileSystemPathId.Create($@"\\{parts[0]}\{parts[1]}").Value);
} // check for drive root (both with and without trailing backslash)
else if ((tempPath.Length == 2 && tempPath[1] == ':') || (tempPath.Length == 3 && tempPath[1] == ':' && tempPath[2] == PathSeparator))
return Errors.FileSystemManagement.CannotNavigateUp;
// find the last occurrence of a backslash
int lastIndex = tempPath.LastIndexOf(PathSeparator);
// if there's no backslash found or it's at the root level, return the root
if (lastIndex <= 2)
return ParsePath(FileSystemPathId.Create(tempPath[..3]).Value);
// return the path up to the last backslash
ErrorOr<FileSystemPathId> newPathResult = FileSystemPathId.Create(tempPath[..lastIndex]);
if (newPathResult.IsError)
return newPathResult.Errors;
return ParsePath(newPathResult.Value);
}
/// <summary>
/// Returns a collection of characters that are invalid for paths.
/// </summary>
/// <returns>A collection of characters that are invalid in the context of paths</returns>
public char[] GetInvalidPathCharsForPlatform()
{
return ['<', '>', '"', '/', '|', '?', '*'];
}
/// <summary>
/// Returns the root portion of the given path.
/// </summary>
/// <param name="path">The path for which to get the root.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing the root of <paramref name="path"/>, or an error.</returns>
public ErrorOr<PathSegment> GetPathRoot(FileSystemPathId path)
{
if (!IsValidPath(path))
return Errors.FileSystemManagement.InvalidPath;
// handle UNC paths (e.g., \\server\share\folder)
if (path.Path.StartsWith(@"\\"))
{
// find the position of the second backslash (after \\server)
int secondBackslash = path.Path.IndexOf('\\', 2);
if (secondBackslash == -1)
return Errors.FileSystemManagement.InvalidPath; // invalid UNC path, missing server name
// find the position of the third backslash (after \\server\share)
int thirdBackslash = path.Path.IndexOf('\\', secondBackslash + 1);
if (thirdBackslash == -1)
thirdBackslash = path.Path.Length; // no third backslash, use entire path
// return the UNC root (\\server\share\)
return PathSegment.Create(path.Path[..thirdBackslash] + "\\", isDirectory: true, isDrive: false);
}
else // handle drive letter paths (e.g., C:\folder)
// check if the path starts with a drive letter followed by a colon (e.g., C:)
// path.Path.Length >= 2: Ensure the path is at least 2 characters long
// char.IsLetter(path.Path[0]): First character should be a letter
// path.Path[1] == ':': Second character should be a colon
if (path.Path.Length >= 2 && char.IsLetter(path.Path[0]) && path.Path[1] == ':')
return PathSegment.Create(path.Path[..2] + "\\", isDirectory: true, isDrive: true); // return the drive root (e.g., C:\)
// if we reach here, the path is neither a valid UNC path nor a valid drive path
return Errors.FileSystemManagement.InvalidPath;
}
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Runtime.InteropServices;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
/// <summary>
/// Interface for checking the type of the current Operating System platform.
/// </summary>
public interface IOperatingSystemInfo
{
/// <summary>
/// Determines if the current Operating System plaform is <paramref name="platform"/>.
/// </summary>
/// <param name="platform">The Operating System platform to check against.</param>
/// <returns><see langword="true"/> if tthe current Operating System platform is equal to <paramref name="platform"/>, <see langword="false"/> otherwise.</returns>
bool IsOSPlatform(OSPlatform platform);
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
/// <summary>
/// Interface for defining the contract of a platform-specific context.
/// </summary>
public interface IPlatformContext
{
/// <summary>
/// Gets the platform for the current platform context.
/// </summary>
PlatformType Platform { get; }
/// <summary>
/// Gets the path strategy for the current platform context.
/// </summary>
IPathStrategy PathStrategy { get; }
}
@@ -0,0 +1,14 @@
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
/// <summary>
/// Interface defining an factory for creating platform contexts.
/// </summary>
public interface IPlatformContextFactory
{
/// <summary>
/// Creates and returns the appropriate platform context.
/// </summary>
/// <typeparam name="TIPlatformContext">The type of platform context to create.</typeparam>
/// <returns>The created platform context.</returns>
TIPlatformContext CreateStrategy<TIPlatformContext>() where TIPlatformContext : IPlatformContext;
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.FileSystem;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
/// <summary>
/// Interface for managing the platform context.
/// </summary>
public interface IPlatformContextManager
{
/// <summary>
/// Gets the current platform context.
/// </summary>
/// <returns>The current platform context.</returns>
IPlatformContext GetCurrentContext();
/// <summary>
/// Sets the current platform context.
/// </summary>
/// <param name="platformType">The platform to be set.</param>
/// <exception cref="ArgumentException">Thrown when an unsupported platform type is provided.</exception>
void SetCurrentPlatform(PlatformType platformType);
}
@@ -0,0 +1,8 @@
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
/// <summary>
/// Interface defining the platform context for UNIX platforms.
/// </summary>
public interface IUnixPlatformContext : IPlatformContext
{
}
@@ -0,0 +1,8 @@
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
/// <summary>
/// Interface defining the platform context for Windows platforms.
/// </summary>
internal interface IWindowsPlatformContext : IPlatformContext
{
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
/// <summary>
/// Class for checking the type of the current Operating System platform.
/// </summary>
[ExcludeFromCodeCoverage]
internal class OperatingSystemInfo : IOperatingSystemInfo
{
/// <summary>
/// Determines if the current Operating System plaform is <paramref name="platform"/>.
/// </summary>
/// <param name="platform">The Operating System platform to check against.</param>
/// <returns><see langword="true"/> if tthe current Operating System platform is equal to <paramref name="platform"/>, <see langword="false"/> otherwise.</returns>
public bool IsOSPlatform(OSPlatform platform)
{
return RuntimeInformation.IsOSPlatform(platform);
}
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.Extensions.DependencyInjection;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
/// <summary>
/// Defines a factory for creating platform contexts.
/// </summary>
public class PlatformContextFactory : IPlatformContextFactory
{
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="PlatformContextFactory"/> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public PlatformContextFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <summary>
/// Creates and returns the appropriate platform context.
/// </summary>
/// <typeparam name="TPlatformContext">The type of platform context to create.</typeparam>
/// <returns>The created platform context.</returns>
public TPlatformContext CreateStrategy<TPlatformContext>() where TPlatformContext : IPlatformContext
{
return _serviceProvider.GetRequiredService<TPlatformContext>() ?? throw new ArgumentException();
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.FileSystem;
using System;
using System.Runtime.InteropServices;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
/// <summary>
/// Service for managing the platform context.
/// </summary>
public class PlatformContextManager : IPlatformContextManager
{
private IPlatformContext? _currentPlatformContext;
private readonly IPlatformContextFactory _platformContextFactory;
private readonly IOperatingSystemInfo _operatingSystemInfo;
/// <summary>
/// Initializes a new instance of the <see cref="PlatformContextManager"/> class.
/// </summary>
/// <param name="platformContextFactory">Injected factory for creating platform contexts.</param>
/// <param name="operatingSystemInfo">Injected class for checking the platform type of the current Operating System.</param>
public PlatformContextManager(IPlatformContextFactory platformContextFactory, IOperatingSystemInfo operatingSystemInfo)
{
_platformContextFactory = platformContextFactory;
_operatingSystemInfo = operatingSystemInfo;
}
/// <summary>
/// Gets the current platform context.
/// </summary>
/// <returns>The current platform context.</returns>
public IPlatformContext GetCurrentContext()
{
// set a default context if none is set
if (_currentPlatformContext is null)
if (_operatingSystemInfo.IsOSPlatform(OSPlatform.Linux))
SetCurrentPlatform(PlatformType.Unix);
else
SetCurrentPlatform(PlatformType.Windows);
return _currentPlatformContext!;
}
/// <summary>
/// Sets the current platform context.
/// </summary>
/// <param name="platformType">The platform to be set.</param>
/// <exception cref="ArgumentException">Thrown when an unsupported platform type is provided.</exception>
public void SetCurrentPlatform(PlatformType platformType)
{
// determine the correct context based on platformType
_currentPlatformContext = platformType switch
{
PlatformType.Unix => _platformContextFactory.CreateStrategy<IUnixPlatformContext>(),
PlatformType.Windows => _platformContextFactory.CreateStrategy<IWindowsPlatformContext>(),
_ => throw new ArgumentException($"Unsupported platform type: {platformType}"),
};
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
/// <summary>
/// Platform context for UNIX platforms.
/// </summary>
internal class UnixPlatformContext : IUnixPlatformContext
{
/// <summary>
/// Gets the platform type, which is Unix for this context.
/// </summary>
public PlatformType Platform { get; } = PlatformType.Unix;
/// <summary>
/// Gets the path strategy for Unix platforms.
/// </summary>
public IPathStrategy PathStrategy { get; }
/// <summary>
/// Initializes a new instance of the <see cref="UnixPlatformContext"/> class.
/// </summary>
/// <param name="unixPathStrategy">Injected service for creating path strategies for UNIX platforms.</param>
public UnixPlatformContext(IUnixPathStrategy unixPathStrategy)
{
PathStrategy = unixPathStrategy;
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
/// <summary>
/// Platform context for Windows platforms.
/// </summary>
public class WindowsPlatformContext : IWindowsPlatformContext
{
/// <summary>
/// Gets the platform type, which is Windows for this context.
/// </summary>
public PlatformType Platform { get; } = PlatformType.Windows;
/// <summary>
/// Gets the path strategy for Windows platforms.
/// </summary>
public IPathStrategy PathStrategy { get; }
/// <summary>
/// Initializes a new instance of the <see cref="WindowsPlatformContext"/> class.
/// </summary>
/// <param name="windowsPathStrategy">Injected service for creating path strategies for Windows platforms.</param>
public WindowsPlatformContext(IWindowsPathStrategy windowsPathStrategy)
{
PathStrategy = windowsPathStrategy;
}
}
@@ -0,0 +1,50 @@
#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.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
/// <summary>
/// Value Object uniquely identifying file system items.
/// </summary>
[DebuggerDisplay("{Path}")]
public sealed class FileSystemPathId : ValueObject
{
/// <summary>
/// Gets the value of this object.
/// </summary>
public string Path { get; }
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemPathId"/> class.
/// </summary>
/// <param name="path">The path of the file system item.</param>
private FileSystemPathId(string path)
{
Path = path;
}
/// <inheritdoc />
public override IEnumerable<object> GetEqualityComponents()
{
yield return Path;
}
/// <summary>
/// Creates a new instance of the <see cref="FileSystemPathId"/> class.
/// </summary>
/// <param name="path">The path of the file system item.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="FileSystemPathId"/> or an error message.
/// </returns>
public static ErrorOr<FileSystemPathId> Create(string path)
{
if (string.IsNullOrWhiteSpace(path))
return Errors.FileSystemManagement.InvalidPath;
return new FileSystemPathId(path);
}
}
@@ -0,0 +1,68 @@
#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.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
/// <summary>
/// Value object uniquely identifying path segments.
/// </summary>
[DebuggerDisplay("{Name}")]
public class PathSegment : ValueObject
{
/// <summary>
/// Gets the name of the path segment.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the value indicating if the current path segment is a file system directory or not.
/// </summary>
public bool IsDirectory { get; }
/// <summary>
/// Gets the value indicating if the current path segment is a file system drive or not.
/// </summary>
public bool IsDrive { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PathSegment"/> class.
/// </summary>
/// <param name="name">The name of the path segment.</param>
/// <param name="isDirectory">Value indicating if the current path segment is a file system directory or not.</param>
/// <param name="isDrive">Value indicating if the current path segment is a file system drive or not.</param>
private PathSegment(string name, bool isDirectory, bool isDrive)
{
Name = name;
IsDirectory = isDirectory;
IsDrive = isDrive;
}
/// <summary>
/// Creates a new instance of the <see cref="PathSegment"/> class.
/// </summary>
/// <param name="name">The name of the path segment.</param>
/// <param name="isDirectory">Value indicating if the current path segment is a file system directory or not.</param>
/// <param name="isDrive">Value indicating if the current path segment is a file system drive or not.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="PathSegment"/> or an error message.
/// </returns>
public static ErrorOr<PathSegment> Create(string name, bool isDirectory, bool isDrive)
{
if (string.IsNullOrWhiteSpace(name))
return Errors.FileSystemManagement.NameCannotBeEmpty;
return new PathSegment(name, isDirectory, isDrive);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Name;
yield return IsDirectory;
yield return IsDrive;
}
}
@@ -0,0 +1,134 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
/// <summary>
/// Value Object for the information about a media stream.
/// </summary>
[DebuggerDisplay("{StreamId}")]
public class StreamInfo : ValueObject
{
/// <summary>
/// Gets the id of the stream.
/// </summary>
public string StreamId { get; }
/// <summary>
/// Gets the MimeType of the stream.
/// </summary>
public string MimeType { get; }
/// <summary>
/// Gets the bitrate of the stream.
/// </summary>
public int Bitrate { get; }
/// <summary>
/// Gets the codec of the stream.
/// </summary>
public string Codec { get; }
/// <summary>
/// Gets the optional resolution of the stream.
/// </summary>
public Optional<string> Resolution { get; }
/// <summary>
/// Gets the optional frame rate of the stream.
/// </summary>
public Optional<float> FrameRate { get; }
/// <summary>
/// Gets the optional sample rate of the stream.
/// </summary>
public Optional<int> SampleRate { get; }
/// <summary>
/// Gets the optional channels of the stream.
/// </summary>
public Optional<int> Channels { get; }
/// <summary>
/// Initializes a new instance of the <see cref="StreamInfo"/> class.
/// </summary>
/// <param name="streamId">The unique identifier for the stream.</param>
/// <param name="mimeType">The MIME type of the stream content.</param>
/// <param name="bitrate">The bitrate of the stream in bits per second.</param>
/// <param name="codec">The codec used for the stream.</param>
/// <param name="resolution">The resolution of the stream (for video).</param>
/// <param name="frameRate">The frame rate of the stream (for video).</param>
/// <param name="sampleRate">The sample rate of the stream (for audio).</param>
/// <param name="channels">The number of channels (for audio).</param>
private StreamInfo(
string streamId,
string mimeType,
int bitrate,
string codec,
Optional<string> resolution,
Optional<float> frameRate,
Optional<int> sampleRate,
Optional<int> channels)
{
StreamId = streamId;
MimeType = mimeType;
Bitrate = bitrate;
Codec = codec;
Resolution = resolution;
FrameRate = frameRate;
SampleRate = sampleRate;
Channels = channels;
}
/// <summary>
/// Creates a new instance of the <see cref="StreamInfo"/> class.
/// </summary>
/// <param name="streamId">The unique identifier for the stream.</param>
/// <param name="mimeType">The MIME type of the stream content.</param>
/// <param name="bitrate">The bitrate of the stream in bits per second.</param>
/// <param name="codec">The codec used for the stream.</param>
/// <param name="resolution">The resolution of the stream (for video).</param>
/// <param name="frameRate">The frame rate of the stream (for video).</param>
/// <param name="sampleRate">The sample rate of the stream (for audio).</param>
/// <param name="channels">The number of channels (for audio).</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="StreamInfo"/>, or an error message.
/// </returns>
public static ErrorOr<StreamInfo> Create(
string streamId,
string mimeType,
int bitrate,
string codec,
Optional<string> resolution,
Optional<float> frameRate,
Optional<int> sampleRate,
Optional<int> channels)
{
if (streamId is null)
return Errors.FileSystemManagement.StreamIdCannotBeEmpty;
if (codec is null)
return Errors.FileSystemManagement.CodecCannotBeEmpty;
if (bitrate <= 0)
return Errors.FileSystemManagement.BitrateMustBeAPositiveNumber;
return new StreamInfo(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return StreamId;
yield return MimeType;
yield return Bitrate;
yield return Codec;
yield return Resolution;
yield return FrameRate;
yield return SampleRate;
yield return Channels;
}
}
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.PhotoLibrary;
using Lumina.Domain.Common.Models.Core;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
/// <summary>
/// Value object for file system thumbnails.
/// </summary>
[DebuggerDisplay("{Type}")]
public class Thumbnail : ValueObject
{
/// <summary>
/// Gets the type of the image represented by this thumbnail.
/// </summary>
public ImageType Type { get; }
/// <summary>
/// Gets the bytes of the image represented by this thumbnail.
/// </summary>
public byte[] Bytes { get; }
/// <summary>
/// Initializes a new instance of the <see cref="Thumbnail"/> class.
/// </summary>
/// <param name="type">The type of the image represented by this thumbnail.</param>
/// <param name="bytes">The bytes of the image represented by this thumbnail.</param>
public Thumbnail(ImageType type, byte[] bytes)
{
Type = type;
Bytes = bytes;
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Type;
yield return Bytes;
}
}
@@ -0,0 +1,133 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.MediaLibrary;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
/// <summary>
/// Aggregate root for a media library.
/// </summary>
[DebuggerDisplay("Id: {Id} Title: {Title}")]
public class Library : AggregateRoot<LibraryId>
{
private readonly List<FileSystemPathId> _contentLocations;
/// <summary>
/// Gets the id of the user owning this media library.
/// </summary>
public UserId UserId { get; private set; }
/// <summary>
/// Gets the type of the media library (e.g., Book, TvShow).
/// </summary>
public LibraryType LibraryType { get; private set; }
/// <summary>
/// Gets the title of the media library.
/// </summary>
public string Title { get; private set; }
/// <summary>
/// Gets the list of file system paths that make up the media library.
/// </summary>
public IReadOnlyCollection<FileSystemPathId> ContentLocations => _contentLocations.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="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>
private Library(
LibraryId id,
UserId userId,
string title,
LibraryType libraryType,
List<FileSystemPathId> contentLocations) : base(id)
{
UserId = userId;
Title = title;
LibraryType = libraryType;
_contentLocations = contentLocations;
}
/// <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="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>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Library"/>, or an error message.
/// </returns>
public static ErrorOr<Library> Create(
Guid userId,
string title,
LibraryType libraryType,
IEnumerable<string> contentLocations)
{
List<FileSystemPathId> tempContentLocations = [];
// go through all the file system paths that make up the media library and create domain objects from them
foreach (string contentLocation in contentLocations)
{
ErrorOr<FileSystemPathId> contentLocationResult = FileSystemPathId.Create(contentLocation);
if (contentLocationResult.IsError)
return contentLocationResult.Errors;
tempContentLocations.Add(contentLocationResult.Value);
}
return new Library(
LibraryId.CreateUnique(),
UserId.Create(userId),
title,
libraryType,
tempContentLocations
);
}
/// <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="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>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Library"/>, or an error message.
/// </returns>
public static ErrorOr<Library> Create(
LibraryId id,
Guid userId,
string title,
LibraryType libraryType,
IEnumerable<string> contentLocations)
{
List<FileSystemPathId> tempContentLocations = [];
// go through all the file system paths that make up the media library and create domain objects from them
foreach (string contentLocation in contentLocations)
{
ErrorOr<FileSystemPathId> contentLocationResult = FileSystemPathId.Create(contentLocation);
if (contentLocationResult.IsError)
return contentLocationResult.Errors;
tempContentLocations.Add(contentLocationResult.Value);
}
return new Library(
id,
UserId.Create(userId),
title,
libraryType,
tempContentLocations
);
}
}
@@ -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.LibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a media library.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class LibraryId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="LibraryId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private LibraryId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryId"/> class.
/// </summary>
/// <returns>The created <see cref="LibraryId"/> instance.</returns>
public static LibraryId CreateUnique()
{
return new LibraryId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="LibraryId"/> instance.</param>
/// <returns>The created <see cref="LibraryId"/> instance.</returns>
public static LibraryId Create(Guid value)
{
return new LibraryId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,93 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate;
/// <summary>
/// Aggregate Root for a media contributor.
/// </summary>
[DebuggerDisplay("{Id}: {Name}")]
public class MediaContributor : AggregateRoot<MediaContributorId>
{
/// <summary>
/// Gets the name of the contributor.
/// </summary>
public MediaContributorName Name { get; private set; }
/// <summary>
/// Gets the role of the contributor.
/// </summary>
public MediaContributorRole Role { get; private set; }
/// <summary>
/// Gets the biography of the contributor.
/// </summary>
public Optional<string> Biography { get; private set; }
/// <summary>
/// Gets the date of birth of the contributor.
/// </summary>
public Optional<DateOnly> DateOfBirth { get; private set; }
/// <summary>
/// Gets the date of death of the contributor.
/// </summary>
public Optional<DateOnly> DateOfDeath { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="MediaContributor"/> class.
/// </summary>
/// <param name="id">The unique identifier of the contributor.</param>
/// <param name="name">The name of the contributor.</param>
/// <param name="role">The role of the contributor.</param>
/// <param name="dateOfBirth">The optional date of birth of the contributor.</param>
/// <param name="dateOfBirth">The optional date of death of the contributor.</param>
private MediaContributor(
MediaContributorId id,
MediaContributorName name,
MediaContributorRole role,
Optional<DateOnly> dateOfBirth,
Optional<DateOnly> dateOfDeath)
{
Id = id;
Name = name;
Role = role;
DateOfBirth = dateOfBirth;
DateOfDeath = dateOfDeath;
}
/// <summary>
/// Creates a new instance of the <see cref="MediaContributor"/> class.
/// </summary>
/// <param name="name">The name of the contributor.</param>
/// <returns>The created <see cref="MediaContributor"/> instance.</returns>
public static ErrorOr<MediaContributor> Create(MediaContributorName name)
{
// TODO: enforce invariants
throw new NotImplementedException();
//return new MediaContributor(id, name);
}
/// <summary>
/// Creates a new instance of the <see cref="MediaContributor"/> class, from a pre-existing <paramref name="id"/>.
/// </summary>
/// <param name="id">The unique identifier of the contributor.</param>
/// <param name="name">The name of the contributor.</param>
/// <returns>The created <see cref="MediaContributor"/> instance.</returns>
public static ErrorOr<MediaContributor> Create(
MediaContributorId id,
MediaContributorName name,
MediaContributorRole role,
Optional<DateOnly> dateOfBirth,
Optional<DateOnly> dateOfDeath)
{
return new MediaContributor(id, name, role, dateOfBirth, dateOfDeath);
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
/// <summary>
/// Value Object for the name of a person.
/// </summary>
[DebuggerDisplay("{DisplayName}")]
public sealed class MediaContributorName : ValueObject
{
/// <summary>
/// Gets the name by which the contributor is popularly known.
/// </summary>
public string DisplayName { get; private set; }
/// <summary>
/// Gets the legal name of the contributor.
/// </summary>
public Optional<string> LegalName { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="MediaContributorName"/> class.
/// </summary>
/// <param name="displayName">The name by which the contributor is popularly known.</param>
/// <param name="legalName">The legal name of the contributor.</param>
private MediaContributorName(string displayName, Optional<string> legalName)
{
DisplayName = displayName;
LegalName = legalName;
}
/// <summary>
/// Creates a new instance of the <see cref="MediaContributorName"/> class.
/// </summary>
/// <param name="displayName">The name by which the contributor is popularly known.</param>
/// <param name="legalName">The legal name of the contributor.</param>
/// <returns>The created <see cref="MediaContributorName"/> instance.</returns>
public static ErrorOr<MediaContributorName> Create(string displayName, Optional<string> legalName)
{
// TODO: enforce invariants
return new MediaContributorName(displayName, legalName);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return DisplayName;
yield return LegalName;
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a media contributor.
/// </summary>
public sealed class MediaContributorId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="MediaContributorId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private MediaContributorId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="MediaContributorId"/> class.
/// </summary>
/// <returns>The created <see cref="MediaContributorId"/> instance.</returns>
public static MediaContributorId CreateUnique()
{
// TODO: enforce invariants
return new MediaContributorId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="MediaContributorId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="MediaContributorId"/> instance.</param>
/// <returns>The created <see cref="MediaContributorId"/> instance.</returns>
public static MediaContributorId Create(Guid value)
{
// TODO: enforce invariants
return new MediaContributorId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
/// <summary>
/// Value Object for the role of a media contributor.
/// </summary>
[DebuggerDisplay("{DisplayName}")]
public sealed class MediaContributorRole : ValueObject
{
/// <summary>
/// Gets the value representing this object.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the category of this object.
/// </summary>
public string Category { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MediaContributorRole"/> class.
/// </summary>
/// <param name="name">The value representing this object.</param>
/// <param name="category">The category of this object.</param>
private MediaContributorRole(string name, string category)
{
Name = name;
Category = category;
}
/// <summary>
/// Creates a new instance of the <see cref="MediaContributorRole"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="name">The value representing this object.</param>
/// <param name="category">The category of this object.</param>
/// <returns>The created <see cref="MediaContributorRole"/> instance.</returns>
public static MediaContributorRole Create(string name, string category)
{
// TODO: enforce invariants
return new MediaContributorRole(name, category);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Name;
yield return Category;
}
}
@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate;
/// <summary>
/// Entity for a movie.
/// </summary>
[DebuggerDisplay("{Id}: {Title}")]
public sealed class Movie : Entity<MovieId>
{
private readonly List<MediaContributorId> _contributors;
private readonly List<Rating> _ratings;
/// <summary>
/// Gets the video metadata of the movie.
/// </summary>
public VideoMetadata Metadata { get; private set; }
/// <summary>
/// Gets the list of ratings for this movie.
/// </summary>
public IReadOnlyCollection<Rating> Ratings => _ratings.AsReadOnly();
/// <summary>
/// Gets the list of media contributors (actors, directors, etc) starring in this movie.
/// </summary>
public IReadOnlyCollection<MediaContributorId> Contributors => _contributors.AsReadOnly();
/// <summary>
/// Initializes a new instance of the <see cref="Movie"/> class.
/// </summary>
/// <param name="id">The unique identifier of the movie.</param>
/// <param name="metadata">The metadata of the movie.</param>
/// <param name="contributors">The list of the contributors of the movie.</param>
/// <param name="ratings">The list of ratings for the movie.</param>
public Movie(MovieId id, VideoMetadata metadata, List<MediaContributorId> contributors, List<Rating> ratings) : base(id)
{
Id = id;
Metadata = metadata;
_contributors = contributors;
_ratings = ratings;
}
#pragma warning disable CS8618
/// <summary>
/// Initializes a new instance of the <see cref="Movie"/> class.
/// </summary>
private Movie() // only needed during reflection
{
}
#pragma warning restore CS8618
/// <summary>
/// Creates a new instance of the <see cref="Movie"/> class.
/// </summary>
/// <param name="metadata">The metadata of the movie.</param>
/// <param name="contributors">The list of media contributors of the movie.</param>
/// <param name="ratings">The list of ratings for the movie.</param>
/// <returns>The created <see cref="Movie"/>.</returns>
public static ErrorOr<Movie> Create(VideoMetadata metadata, List<MediaContributorId> contributors, List<Rating> ratings)
{
// TODO: enforce invariants
return new Movie(MovieId.CreateUnique(), metadata, contributors, ratings);
}
/// <summary>
/// Creates a new instance of the <see cref="Movie"/> class, with a pre-existing <paramref name="id"/>.
/// </summary>
/// <param name="id">The object representing the id of the movie.</param>
/// <param name="metadata">The metadata of the movie.</param>
/// <param name="contributors">The list of media contributors of the movie.</param>
/// <param name="ratings">The list of ratings for the movie.</param>
/// <returns>The created <see cref="Movie"/>.</returns>
public static ErrorOr<Movie> Create(MovieId id, VideoMetadata metadata, List<MediaContributorId> contributors, List<Rating> ratings)
{
// TODO: enforce invariants
return new Movie(id, metadata, contributors, ratings);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.Services;
/// <summary>
/// Interface for the service for managing movie libraries.
/// </summary>
public interface IMovieLibraryService
{
/// <summary>
/// Gets the collection of movies in the library.
/// </summary>
public ICollection<Movie> Movies { get; }
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.Services;
/// <summary>
/// Service for managing movie libraries.
/// </summary>
public sealed class MovieLibraryService : IMovieLibraryService
{
/// <summary>
/// Gets the collection of movies in the library.
/// </summary>
public ICollection<Movie> Movies => throw new NotImplementedException();
}
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a movie.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class MovieId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="MovieId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private MovieId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="MovieId"/> class.
/// </summary>
/// <returns>The created <see cref="MovieId"/> instance.</returns>
public static MovieId CreateUnique()
{
// TODO: enforce invariants
return new MovieId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="MovieId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="MovieId"/> instance.</param>
/// <returns>The created <see cref="MovieId"/> instance.</returns>
public static MovieId Create(Guid value)
{
// TODO: enforce invariants
return new MovieId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,131 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the video metadata of a media element.
/// </summary>
[DebuggerDisplay("{Title}")]
public class VideoMetadata : BaseMetadata
{
/// <summary>
/// Gets the duration of the video in seconds.
/// </summary>
public int DurationInSeconds { get; }
/// <summary>
/// Gets the resolution of the video.
/// </summary>
public string Resolution { get; } // TODO: should be implemented as a value object with width, height, aspet ratio, etc.
/// <summary>
/// Gets the frame rate of the video.
/// </summary>
public Optional<float> FrameRate { get; }
/// <summary>
/// Gets the video codec used.
/// </summary>
public Optional<string> VideoCodec { get; }
/// <summary>
/// Gets the audio codec used.
/// </summary>
public Optional<string> AudioCodec { get; }
/// <summary>
/// Initializes a new instance of the <see cref="VideoMetadata"/> class.
/// </summary>
/// <param name="title">The title of the video.</param>
/// <param name="originalTitle">The optional original title of the video.</param>
/// <param name="durationInSeconds">The duration of the video, in seconds.</param>
/// <param name="resolution">The resolution of the video.</param>
/// <param name="releaseInfo">The release information of the video.</param>
/// <param name="description">The optional description of the video.</param>
/// <param name="language">The language of the video.</param>
/// <param name="originalLanguage">The optional original language of the video.</param>
/// <param name="frameRate">The optional frame rate of the video.</param>
/// <param name="videoCodec">The optional video codec used.</param>
/// <param name="audioCodec">The optional audio codec used.</param>
/// <param name="genres">The genres of the video.</param>
/// <param name="tags">The tags associated with the video.</param>
private VideoMetadata(
string title,
Optional<string> originalTitle,
int durationInSeconds,
string resolution,
Optional<string> description,
ReleaseInfo releaseInfo,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<float> frameRate,
Optional<string> videoCodec,
Optional<string> audioCodec,
List<Genre> genres,
List<Tag> tags)
: base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage)
{
DurationInSeconds = durationInSeconds;
Resolution = resolution ?? throw new ArgumentNullException(nameof(resolution));
FrameRate = frameRate;
VideoCodec = videoCodec;
AudioCodec = audioCodec;
}
/// <summary>
/// Creates a new instance of the <see cref="VideoMetadata"/> class.
/// </summary>
/// <param name="title">The title of the video.</param>
/// <param name="originalTitle">The optional original title of the video.</param>
/// <param name="durationInSeconds">The duration of the video in seconds.</param>
/// <param name="resolution">The resolution of the video.</param>
/// <param name="description">The optional description of the video.</param>
/// <param name="releaseInfo">The release information of the video.</param>
/// <param name="language">The language of the video.</param>
/// <param name="originalLanguage">The optional original language of the video.</param>
/// <param name="frameRate">The optional frame rate of the video.</param>
/// <param name="videoCodec">The optional video codec used.</param>
/// <param name="audioCodec">The optional audio codec used.</param>
/// <param name="genres">The genres of the video.</param>
/// <param name="tags">The tags associated with the video.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="VideoMetadata"/>, or an error message.
/// </returns>
public static ErrorOr<VideoMetadata> Create(
string title,
Optional<string> originalTitle,
int durationInSeconds,
string resolution,
Optional<string> description,
ReleaseInfo releaseInfo,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<float> frameRate,
Optional<string> videoCodec,
Optional<string> audioCodec,
List<Genre> genres,
List<Tag> tags)
{
return new VideoMetadata(title, originalTitle, durationInSeconds, resolution, description, releaseInfo,
language, originalLanguage, frameRate, videoCodec, audioCodec, genres, tags);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
foreach (object component in base.GetEqualityComponents())
yield return component;
yield return DurationInSeconds;
yield return Resolution;
yield return FrameRate;
yield return VideoCodec;
yield return AudioCodec;
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Services;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.Services;
/// <summary>
/// Interface for the service for managing video content.
/// </summary>
public interface IVideoLibraryService
{
/// <summary>
/// Gets the service for managing a movie library.
/// </summary>
public IMovieLibraryService MovieLibraryService { get; }
/// <summary>
/// Gets the service for managing a TV shows library.
/// </summary>
public ITvShowLibraryService TvShowLibraryService { get; }
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Services;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.Services;
/// <summary>
/// Service for managing video content.
/// </summary>
public class VideoLibraryService : IVideoLibraryService
{
/// <summary>
/// Gets the service for managing a movie library.
/// </summary>
public IMovieLibraryService MovieLibraryService { get; private set; }
/// <summary>
/// Gets the service for managing a TV shows library.
/// </summary>
public ITvShowLibraryService TvShowLibraryService { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="VideoLibraryService"/> class.
/// </summary>
/// <param name="movieLibraryService">Injected movie library service.</param>
/// <param name="tvShowLibraryService">Injected TV show library service.</param>
public VideoLibraryService(IMovieLibraryService movieLibraryService, ITvShowLibraryService tvShowLibraryService)
{
MovieLibraryService = movieLibraryService;
TvShowLibraryService = tvShowLibraryService;
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Entities;
/// <summary>
/// Entity for an episode.
/// </summary>
[DebuggerDisplay("{Id}: {Title}")]
public sealed class Episode : Entity<EpisodeId>
{
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Entities;
/// <summary>
/// Entity for a season.
/// </summary>
[DebuggerDisplay("{Id}: {Title}")]
public sealed class Season : Entity<SeasonId>
{
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Services;
/// <summary>
/// Interface for the service for managing TV show libraries.
/// </summary>
public interface ITvShowLibraryService
{
/// <summary>
/// Gets the collection of TV shows in the library.
/// </summary>
public ICollection<TvShow> TvShows { get; }
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Services;
/// <summary>
/// Service for managing TV show libraries.
/// </summary>
public class TvShowLibraryService : ITvShowLibraryService
{
/// <summary>
/// Gets the collection of TV shows in the library.
/// </summary>
public ICollection<TvShow> TvShows => throw new NotImplementedException();
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate;
/// <summary>
/// Entity for a TV show.
/// </summary>
[DebuggerDisplay("{Id}: {Title}")]
public sealed class TvShow : Entity<TvShowId>
{
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of an episode.
/// </summary>
public sealed class EpisodeId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="EpisodeId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private EpisodeId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="EpisodeId"/> class.
/// </summary>
/// <returns>The created <see cref="EpisodeId"/> instance.</returns>
public static EpisodeId CreateUnique()
{
// TODO: enforce invariants
return new EpisodeId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="EpisodeId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="EpisodeId"/> instance.</param>
/// <returns>The created <see cref="EpisodeId"/> instance.</returns>
public static EpisodeId Create(Guid value)
{
// TODO: enforce invariants
return new EpisodeId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a season.
/// </summary>
public sealed class SeasonId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="SeasonId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private SeasonId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="SeasonId"/> class.
/// </summary>
/// <returns>The created <see cref="SeasonId"/> instance.</returns>
public static SeasonId CreateUnique()
{
// TODO: enforce invariants
return new SeasonId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="SeasonId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="SeasonId"/> instance.</param>
/// <returns>The created <see cref="SeasonId"/> instance.</returns>
public static SeasonId Create(Guid value)
{
// TODO: enforce invariants
return new SeasonId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a TV show.
/// </summary>
public sealed class TvShowId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="TvShowId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private TvShowId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="TvShowId"/> class.
/// </summary>
/// <returns>The created <see cref="TvShowId"/> instance.</returns>
public static TvShowId CreateUnique()
{
// TODO: enforce invariants
return new TvShowId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="TvShowId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="TvShowId"/> instance.</param>
/// <returns>The created <see cref="TvShowId"/> instance.</returns>
public static TvShowId Create(Guid value)
{
// TODO: enforce invariants
return new TvShowId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,327 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
/// <summary>
/// Aggregate root for a book.
/// </summary>
[DebuggerDisplay("Id: {Id} Title: {Title}")]
public sealed class Book : AggregateRoot<BookId>
{
private readonly List<MediaContributorId> _contributors;
private readonly List<BookRating> _ratings;
private readonly List<Isbn> _isbns;
/// <summary>
/// Gets the written content metadata of the book.
/// </summary>
public WrittenContentMetadata Metadata { get; private set; }
/// <summary>
/// Gets the format of the book (e.g., Hardcover, Paperback), if applicable.
/// </summary>
public Optional<BookFormat> Format { get; private set; }
/// <summary>
/// Gets the edition of the book, if applicable.
/// </summary>
public Optional<string> Edition { get; private set; }
/// <summary>
/// Gets the volume or book number in the series, if applicable.
/// </summary>
public Optional<int> VolumeNumber { get; private set; }
/// <summary>
/// Gets the series name, if the book is part of a series.
/// </summary>
public Optional<BookSeries> Series { get; private set; }
/// <summary>
/// Gets the ASIN (Amazon Standard Identification Number) of the book, if applicable.
/// </summary>
public Optional<string> ASIN { get; private set; }
/// <summary>
/// Gets the Goodreads ID of the book, if applicable.
/// </summary>
public Optional<string> GoodreadsId { get; private set; }
/// <summary>
/// Gets the Library of Congress Control Number (LCCN) of the book, if applicable.
/// </summary>
public Optional<string> LCCN { get; private set; }
/// <summary>
/// Gets the OCLC Number (WorldCat identifier) of the book, if applicable.
/// </summary>
public Optional<string> OCLCNumber { get; private set; }
/// <summary>
/// Gets the Open Library ID of the book, if applicable.
/// </summary>
public Optional<string> OpenLibraryId { get; private set; }
/// <summary>
/// Gets the LibraryThing ID of the book, if applicable.
/// </summary>
public Optional<string> LibraryThingId { get; private set; }
/// <summary>
/// Gets the Google Books ID of the book, if applicable.
/// </summary>
public Optional<string> GoogleBooksId { get; private set; }
/// <summary>
/// Gets the Barnes & Noble ID of the book, if applicable.
/// </summary>
public Optional<string> BarnesAndNobleId { get; private set; }
/// <summary>
/// Gets the Apple Books ID of the book, if applicable.
/// </summary>
public Optional<string> AppleBooksId { get; private set; }
/// <summary>
/// Gets the list of ISBN (International Standard Book Number) of the book.
/// </summary>
public IReadOnlyCollection<Isbn> ISBNs => _isbns.AsReadOnly();
/// <summary>
/// Gets the list of media contributors (actors, directors, etc) starring in this book.
/// </summary>
public IReadOnlyCollection<MediaContributorId> Contributors => _contributors.AsReadOnly();
/// <summary>
/// Gets the list of ratings for this book.
/// </summary>
public IReadOnlyCollection<BookRating> Ratings => _ratings.AsReadOnly();
/// <summary>
/// Initializes a new instance of the <see cref="Book"/> class.
/// </summary>
/// <param name="id">The unique identifier of the book.</param>
/// <param name="metadata">The metadata of the book.</param>
/// <param name="format">The optional format of the book (e.g., Hardcover, Paperback).</param>
/// <param name="edition">The optional edition of the book.</param>
/// <param name="volumeNumber">The optional volume or book number in the series.</param>
/// <param name="series">The optional series name, if the book is part of a series.</param>
/// <param name="asin">The optional ASIN of the book.</param>
/// <param name="goodreadsId">The optional Goodreads ID of the book.</param>
/// <param name="lccn">The optional LCCN of the book.</param>
/// <param name="oclcNumber">The optional OCLC Number of the book.</param>
/// <param name="openLibraryId">The optional Open Library ID of the book.</param>
/// <param name="libraryThingId">The optional LibraryThing ID of the book.</param>
/// <param name="googleBooksId">The optional Google Books ID of the book.</param>
/// <param name="barnesAndNobleId">The optional Barnes & Noble ID of the book.</param>
/// <param name="appleBooksId">The optional Apple Books ID of the book.</param>
/// <param name="created">The date and time when the entity was created.</param>
/// <param name="updated">The date and time when the entity was last updated.</param>
/// <param name="isbns">The list of ISBNs of the book.</param>
/// <param name="contributors">The list of media contributors of the book.</param>
/// <param name="ratings">The list of ratings for the book.</param>
private Book(
BookId id,
WrittenContentMetadata metadata,
Optional<BookFormat> format,
Optional<string> edition,
Optional<int> volumeNumber,
Optional<BookSeries> series,
Optional<string> asin,
Optional<string> goodreadsId,
Optional<string> lccn,
Optional<string> oclcNumber,
Optional<string> openLibraryId,
Optional<string> libraryThingId,
Optional<string> googleBooksId,
Optional<string> barnesAndNobleId,
Optional<string> appleBooksId,
DateTime created,
Optional<DateTime> updated,
List<Isbn> isbns,
List<MediaContributorId> contributors,
List<BookRating> ratings) : base(id)
{
Id = id;
Metadata = metadata;
Format = format;
Edition = edition;
VolumeNumber = volumeNumber;
Series = series;
ASIN = asin;
GoodreadsId = goodreadsId;
LCCN = lccn;
OCLCNumber = oclcNumber;
OpenLibraryId = openLibraryId;
LibraryThingId = libraryThingId;
GoogleBooksId = googleBooksId;
BarnesAndNobleId = barnesAndNobleId;
AppleBooksId = appleBooksId;
Created = created;
Updated = updated.HasValue ? updated.Value : null;
_isbns = isbns;
_contributors = contributors;
_ratings = ratings;
}
#pragma warning disable CS8618
/// <summary>
/// Initializes a new instance of the <see cref="Book"/> class.
/// </summary>
private Book() // only needed during reflection
{
}
#pragma warning restore CS8618
/// <summary>
/// Creates a new instance of the <see cref="Book"/> class.
/// </summary>
/// <param name="metadata">The metadata of the book.</param>
/// <param name="format">The optional format of the book (e.g., Hardcover, Paperback).</param>
/// <param name="edition">The optional edition of the book.</param>
/// <param name="volumeNumber">The optional volume or book number in the series.</param>
/// <param name="series">The optional series name, if the book is part of a series.</param>
/// <param name="asin">The optional ASIN of the book.</param>
/// <param name="goodreadsId">The optional Goodreads ID of the book.</param>
/// <param name="lccn">The optional LCCN of the book.</param>
/// <param name="oclcNumber">The optional OCLC Number of the book.</param>
/// <param name="openLibraryId">The optional Open Library ID of the book.</param>
/// <param name="libraryThingId">The optional LibraryThing ID of the book.</param>
/// <param name="googleBooksId">The optional Google Books ID of the book.</param>
/// <param name="barnesAndNobleId">The optional Barnes & Noble ID of the book.</param>
/// <param name="appleBooksId">The optional Apple Books ID of the book.</param>
/// <param name="isbns">The list of ISBNs of the book.</param>
/// <param name="contributors">The list of media contributors of the book.</param>
/// <param name="ratings">The list of ratings for the book.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// </returns>
public static ErrorOr<Book> Create(
WrittenContentMetadata metadata,
Optional<BookFormat> format,
Optional<string> edition,
Optional<int> volumeNumber,
Optional<BookSeries> series,
Optional<string> asin,
Optional<string> goodreadsId,
Optional<string> lccn,
Optional<string> oclcNumber,
Optional<string> openLibraryId,
Optional<string> libraryThingId,
Optional<string> googleBooksId,
Optional<string> barnesAndNobleId,
Optional<string> appleBooksId,
List<Isbn> isbns,
List<MediaContributorId> contributors,
List<BookRating> ratings)
{
// TODO: enforce invariants
return new Book(
BookId.CreateUnique(),
metadata,
format,
edition,
volumeNumber,
series,
asin,
goodreadsId,
lccn,
oclcNumber,
openLibraryId,
libraryThingId,
googleBooksId,
barnesAndNobleId,
appleBooksId,
DateTime.UtcNow,
default,
isbns,
contributors,
ratings
);
}
/// <summary>
/// Creates a new instance of the <see cref="Book"/>, with a pre-existing <paramref name="id"/>.
/// </summary>
/// <param name="id">The object representing the id of the book.</param>
/// <param name="metadata">The metadata of the book.</param>
/// <param name="format">The optional format of the book (e.g., Hardcover, Paperback).</param>
/// <param name="edition">The optional edition of the book.</param>
/// <param name="volumeNumber">The optional volume or book number in the series.</param>
/// <param name="series">The optional series name, if the book is part of a series.</param>
/// <param name="asin">The optional ASIN of the book.</param>
/// <param name="goodreadsId">The optional Goodreads ID of the book.</param>
/// <param name="lccn">The optional LCCN of the book.</param>
/// <param name="oclcNumber">The optional OCLC Number of the book.</param>
/// <param name="openLibraryId">The optional Open Library ID of the book.</param>
/// <param name="libraryThingId">The optional LibraryThing ID of the book.</param>
/// <param name="googleBooksId">The optional Google Books ID of the book.</param>
/// <param name="barnesAndNobleId">The optional Barnes & Noble ID of the book.</param>
/// <param name="appleBooksId">The optional Apple Books ID of the book.</param>
/// <param name="created">The date and time when the entity was created.</param>
/// <param name="updated">The date and time when the entity was last updated.</param>
/// <param name="isbns">The list of ISBNs of the book.</param>
/// <param name="contributors">The list of media contributors of the book.</param>
/// <param name="ratings">The list of ratings for the book.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Book"/>, or an error message.
/// </returns>
public static ErrorOr<Book> Create(
BookId id,
WrittenContentMetadata metadata,
Optional<BookFormat> format,
Optional<string> edition,
Optional<int> volumeNumber,
Optional<BookSeries> series,
Optional<string> asin,
Optional<string> goodreadsId,
Optional<string> lccn,
Optional<string> oclcNumber,
Optional<string> openLibraryId,
Optional<string> libraryThingId,
Optional<string> googleBooksId,
Optional<string> barnesAndNobleId,
Optional<string> appleBooksId,
DateTime created,
Optional<DateTime> updated,
List<Isbn> isbns,
List<MediaContributorId> contributors,
List<BookRating> ratings)
{
// TODO: enforce invariants
return new Book(
id,
metadata,
format,
edition,
volumeNumber,
series,
asin,
goodreadsId,
lccn,
oclcNumber,
openLibraryId,
libraryThingId,
googleBooksId,
barnesAndNobleId,
appleBooksId,
created,
updated,
isbns,
contributors,
ratings
);
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
/// <summary>
/// Entity for a book series.
/// </summary>
[DebuggerDisplay("{Id}: {Title}")]
public sealed class BookSeries : Entity<BookSeriesId>
{
private readonly List<Book> _books;
/// <summary>
/// Gets the written content metadata of the book series.
/// </summary>
public WrittenContentMetadata Metadata { get; private set; }
/// <summary>
/// Gets a value indicating whether the series is complete.
/// </summary>
public bool IsComplete { get; private set; }
/// <summary>
/// Gets the collection of books in the series.
/// </summary>
public IReadOnlyCollection<Book> Books => _books.AsReadOnly();
/// <summary>
/// Initializes a new instance of the <see cref="BookSeries"/> class.
/// </summary>
/// <param name="id">The identifier of the book series.</param>
/// <param name="metadata">The metadata of the book series.</param>
/// <param name="isComplete">The current status of the book series.</param>
/// <param name="books">The books of the book series.</param>
private BookSeries(BookSeriesId id, WrittenContentMetadata metadata, bool isComplete, List<Book> books)
: base(id)
{
Id = id;
Metadata = metadata;
IsComplete = isComplete;
_books = books;
}
/// <summary>
/// Creates a new instance of the <see cref="BookSeries"/> class.
/// </summary>
/// <param name="id">The identifier of the book series.</param>
/// <param name="metadata">The metadata of the book series.</param>
/// <param name="isComplete">The current status of the book series.</param>
/// <param name="books">The books of the book series.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="BookSeries"/>, or an error message.
/// </returns>
public static ErrorOr<BookSeries> Create(
BookSeriesId id,
WrittenContentMetadata metadata,
bool isComplete,
List<Book> books)
{
// TODO: enforce invariants
return new BookSeries(
id,
metadata,
isComplete,
books
);
}
/// <summary>
/// Creates a new instance of the <see cref="BookSeries"/> class.
/// </summary>
/// <param name="metadata">The metadata of the book series.</param>
/// <param name="isComplete">The current status of the book series.</param>
/// <param name="books">The books of the book series.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="BookSeries"/>, or an error message.
/// </returns>
public static ErrorOr<BookSeries> Create(
WrittenContentMetadata metadata,
bool isComplete,
List<Book> books)
{
// TODO: enforce invariants
return new BookSeries(
BookSeriesId.CreateUnique(),
metadata,
isComplete,
books
);
}
/// <summary>
/// Adds a book to the series.
/// </summary>
/// <param name="book">The book to be added.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public ErrorOr<Created> AddBook(Book book)
{
if (_books.Contains(book))
return Errors.WrittenContent.TheBookIsAlreadyInTheSeries;
_books.Add(book);
return Result.Created;
}
/// <summary>
/// Removes a book from the series.
/// </summary>
/// <param name="book">The book to be removed.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public ErrorOr<Deleted> RemoveBook(Book book)
{
if (!_books.Contains(book))
return Errors.WrittenContent.TheBookIsNotInTheSeries;
_books.Remove(book);
return Result.Deleted;
}
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services;
/// <summary>
/// Service for managing book libraries.
/// </summary>
public sealed class BookLibraryService : IBookLibraryService
{
/// <summary>
/// Gets the collection of books in the library.
/// </summary>
public ICollection<Book> Books => throw new NotImplementedException();
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services;
/// <summary>
/// Interface for the service for managing book libraries.
/// </summary>
public interface IBookLibraryService
{
/// <summary>
/// Gets the collection of books in the library.
/// </summary>
ICollection<Book> Books { get; }
// ICollection<BookSeries> Series { get; }
// void AddBook(Book book);
// void RemoveBook(Guid bookId);
// void AddSeries(BookSeries series);
// void RemoveSeries(Guid seriesId);
// Book GetBook(Guid bookId);
// BookSeries GetSeries(Guid seriesId);
}
@@ -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.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a book.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class BookId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="BookId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private BookId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="BookId"/> class.
/// </summary>
/// <returns>The created <see cref="BookId"/> instance.</returns>
public static BookId CreateUnique()
{
return new BookId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="BookId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="BookId"/> instance.</param>
/// <returns>The created <see cref="BookId"/> instance.</returns>
public static BookId Create(Guid value)
{
return new BookId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a book library.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class BookLibraryId : EntityId<Guid> // TODO: to be removed
{
/// <summary>
/// Initializes a new instance of the <see cref="BookLibraryId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private BookLibraryId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="BookLibraryId"/> class.
/// </summary>
/// <returns>The created <see cref="BookLibraryId"/> instance.</returns>
public static ErrorOr<BookLibraryId> CreateUnique()
{
// TODO: enforce invariants
return new BookLibraryId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="BookLibraryId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="BookLibraryId"/> instance.</param>
/// <returns>The created <see cref="BookLibraryId"/> instance.</returns>
public static ErrorOr<BookLibraryId> Create(Guid value)
{
// TODO: enforce invariants
return new BookLibraryId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the rating of a media element.
/// </summary>
[DebuggerDisplay("{Value}/{MaxValue}")]
public class BookRating : Rating
{
/// <summary>
/// Gets the optional source of the rating (e.g., "Goodreads", "Amazon").
/// </summary>
public Optional<BookRatingSource> Source { get; }
/// <summary>
/// Initializes a new instance of the <see cref="Rating"/> class.
/// </summary>
/// <param name="value">The numeric value of the rating.</param>
/// <param name="maxValue">The maximum possible rating value.</param>
/// <param name="source">The optional source of the rating.</param>
/// <param name="voteCount">The optional number of votes or reviews.</param>
private BookRating(decimal value, decimal maxValue, Optional<BookRatingSource> source, Optional<int> voteCount)
: base(value, maxValue, voteCount)
{
Source = source;
}
/// <summary>
/// Creates a new instance of the <see cref="Rating"/> class.
/// </summary>
/// <param name="value">The numeric value of the rating.</param>
/// <param name="maxValue">The maximum possible rating value.</param>
/// <param name="source">The optional source of the rating.</param>
/// <param name="voteCount">The optional number of votes or reviews.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Rating"/>, or an error message.
/// </returns>
public static ErrorOr<BookRating> Create(decimal value, decimal maxValue, Optional<BookRatingSource> source, Optional<int> voteCount)
{
if (maxValue < 0 || value < 0)
return Errors.Metadata.RatingValueMustBePositive;
if (value > maxValue)
return Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue;
return new BookRating(value, maxValue, source, voteCount);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
yield return MaxValue;
yield return Source;
yield return VoteCount;
}
/// <summary>
/// Customized ToString() method.
/// </summary>
/// <returns>Custom string value showing relevant data for current class.</returns>
public override string ToString()
{
string baseString = $"{Value}/{MaxValue}";
if (Source.HasValue)
baseString += $" ({Source.Value})";
if (VoteCount.HasValue)
baseString += $" [{VoteCount.Value} votes]";
return baseString;
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the Id of a book series.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class BookSeriesId : ValueObject
{
public Guid Value { get; }
/// <summary>
/// Initializes a new instance of the <see cref="BookSeriesId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private BookSeriesId(Guid value)
{
Value = value;
}
/// <summary>
/// Creates a new instance of the <see cref="BookSeriesId"/> class.
/// </summary>
/// <returns>The created <see cref="BookSeriesId"/> instance.</returns>
public static BookSeriesId CreateUnique()
{
return new BookSeriesId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="BookSeriesId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="BookSeriesId"/> instance.</param>
/// <returns>The created <see cref="BookSeriesId"/> instance.</returns>
public static BookSeriesId Create(Guid value)
{
return new BookSeriesId(value);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,118 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Models.Core;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the ISBN of a book.
/// </summary>
[DebuggerDisplay("{Value} ({Format})")]
public sealed class Isbn : ValueObject
{
private static readonly Regex s_isbn10Regex = new(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$", RegexOptions.Compiled);
private static readonly Regex s_isbn13Regex = new(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$", RegexOptions.Compiled);
/// <summary>
/// Gets the value of the ISBN.
/// </summary>
public string Value { get; private set; }
/// <summary>
/// Gets the format of the ISBN.
/// </summary>
public IsbnFormat Format { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Isbn"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
/// <param name="format">The format of the ISBN representing this object.</param>
private Isbn(string value, IsbnFormat format)
{
Value = value;
Format = format;
}
/// <summary>
/// Creates a new instance of the <see cref="Isbn"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
/// <param name="format">The format of the ISBN representing this object.</param>
/// <returns>The created <see cref="Isbn"/> instance.</returns>
public static ErrorOr<Isbn> Create(string? value, IsbnFormat format)
{
// enforce invariants
if (string.IsNullOrWhiteSpace(value))
return Errors.WrittenContent.IsbnValueCannotBeEmpty;
// remove hyphens and spaces, for validation
string cleanedValue = Regex.Replace(value, @"[-\s]", string.Empty);
switch (format)
{
case IsbnFormat.Isbn10:
if (!IsValidIsbn10(cleanedValue))
return Errors.WrittenContent.InvalidIsbn10Format;
break;
case IsbnFormat.Isbn13:
if (!IsValidIsbn13(cleanedValue))
return Errors.WrittenContent.InvalidIsbn13Format;
break;
default:
return Errors.WrittenContent.UnknownIsbnFormat;
}
return new Isbn(value, format);
}
/// <summary>
/// Validates an ISBN-10 string.
/// </summary>
/// <param name="isbn">The ISBN-10 string to validate, with or without hyphens or spaces.</param>
/// <returns><see langword="true"/> if the ISBN-10 is valid, <see langword="false"/> otherwise.</returns>
public static bool IsValidIsbn10(string isbn)
{
if (!s_isbn10Regex.IsMatch(isbn))
return false;
// remove any hyphens or spaces
isbn = isbn.Replace("-", "").Replace(" ", "").ToUpper();
int sum = 0;
for (int i = 0; i < 9; i++)
sum += (10 - i) * (isbn[i] - '0');
char lastChar = isbn[9];
if (lastChar == 'X')
sum += 10;
else
sum += lastChar - '0';
return sum % 11 == 0;
}
/// <summary>
/// Validates an ISBN-13 string.
/// </summary>
/// <param name="isbn">The ISBN-13 string to validate, with or without hyphens or spaces.</param>
/// <returns><see langword="true"/> if the ISBN-13 is valid, <see langword="false"/> otherwise.</returns>
public static bool IsValidIsbn13(string isbn)
{
if (!s_isbn13Regex.IsMatch(isbn))
return false;
// remove any hyphens or spaces
isbn = isbn.Replace("-", "").Replace(" ", "");
int sum = 0;
for (int i = 0; i < 12; i++)
sum += (i % 2 == 0) ? isbn[i] - '0' : 3 * (isbn[i] - '0');
int checkDigit = (10 - (sum % 10)) % 10;
return checkDigit == (isbn[12] - '0');
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
yield return Format;
}
}
@@ -0,0 +1,115 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
/// <summary>
/// Value Object for the metadata of a written media element.
/// </summary>
[DebuggerDisplay("{Title}")]
public class WrittenContentMetadata : BaseMetadata
{
/// <summary>
/// Gets the publisher of the written content, if applicable.
/// </summary>
public Optional<string> Publisher { get; }
/// <summary>
/// Gets the number of pages in the written content, if applicable.
/// </summary>
public Optional<int> PageCount { get; }
/// <summary>
/// Initializes a new instance of the <see cref="WrittenContentMetadata"/> class.
/// </summary>
/// <param name="title">The title of the written content.</param>
/// <param name="originalTitle">The optional original title of the written content, if applicable.</param>
/// <param name="description">The description of the written content, if applicable.</param>
/// <param name="releaseInfo">The release information of the written content.</param>
/// <param name="genres">The genres of the written content.</param>
/// <param name="tags">The tags associated with the written content.</param>
/// <param name="language">The language of the written content, if applicable.</param>
/// <param name="originalLanguage">The optional original language of the written content, if applicable.</param>
/// <param name="publisher">The publisher of the written content, if applicable.</param>
/// <param name="pageCount">The number of pages in the written content, if applicable.</param>
private WrittenContentMetadata(
string title,
Optional<string> originalTitle,
Optional<string> description,
ReleaseInfo releaseInfo,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<string> publisher,
Optional<int> pageCount)
: base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage)
{
Publisher = publisher;
PageCount = pageCount;
}
/// <summary>
/// Creates a new instance of the <see cref="WrittenContentMetadata"/> class.
/// </summary>
/// <param name="title">The title of the written content.</param>
/// <param name="originalTitle">The optional original title of the written content, if applicable.</param>
/// <param name="description">The description of the written content, if applicable.</param>
/// <param name="releaseInfo">The release information of the written content.</param>
/// <param name="genres">The genres of the written content.</param>
/// <param name="tags">The tags associated with the written content.</param>
/// <param name="language">The language of the written content.</param>
/// <param name="originalLanguage">The optional original language of the written content, if applicable.</param>
/// <param name="publisher">The publisher of the written content, if applicable.</param>
/// <param name="pageCount">The number of pages in the written content, if applicable.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="WrittenContentMetadata"/>, or an error message.
/// </returns>
public static ErrorOr<WrittenContentMetadata> Create(
string title,
Optional<string> originalTitle,
Optional<string> description,
ReleaseInfo releaseInfo,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage,
Optional<string> publisher,
Optional<int> pageCount)
{
if (string.IsNullOrWhiteSpace(title))
return Errors.Metadata.TitleCannotBeEmpty;
if (releaseInfo is null)
return Errors.Metadata.ReleaseInfoCannotBeNull;
if (genres is null)
return Errors.Metadata.GenresListCannotBeNull;
if (tags is null)
return Errors.Metadata.TagsListCannotBeNull;
return new WrittenContentMetadata(
title,
originalTitle,
description,
releaseInfo,
genres, tags,
language,
originalLanguage,
publisher,
pageCount
);
}
/// <inheritdoc/>
public override IEnumerable<object> GetEqualityComponents()
{
foreach (object component in base.GetEqualityComponents())
yield return component;
yield return Publisher;
yield return PageCount;
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Services;
/// <summary>
/// Interface for the service for managing written content.
/// </summary>
public interface IWrittenContentLibraryService
{
/// <summary>
/// Gets the service for managing book libraries.
/// </summary>
public IBookLibraryService BookLibraryService { get; }
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Services;
/// <summary>
/// Service for managing written content.
/// </summary>
public class WrittenContentLibraryService : IWrittenContentLibraryService
{
/// <summary>
/// Gets the service for managing book libraries.
/// </summary>
public IBookLibraryService BookLibraryService { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="WrittenContentLibraryService"/> class.
/// </summary>
/// <param name="bookLibraryService">Injected book library service.</param>
public WrittenContentLibraryService(IBookLibraryService bookLibraryService)
{
BookLibraryService = bookLibraryService;
}
}