Standardizes the remaining boolean names across the stack

This commit is contained in:
BinaryAlley committed 2026-09-13 16:48:42 +03:00
1 parent 3e0c3b624f
commit 39f4a04459
40 files changed
+1062 -448

No files matched your search

@@ -1,7 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.Common;
using System.Collections.Generic;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -9,15 +11,22 @@ using System.Threading.Tasks;
namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
/// <summary>
/// Interface defining the "get all" action for interacting with a generic persistance medium.
/// Interface defining the "get all" action for interacting with a generic persistence medium.
/// </summary>
/// <typeparam name="TModel">The type used as a result for the "get all" action. It should implement <see cref="IStorageEntity"/>.</typeparam>
public interface IGetAllRepositoryAction<TModel> where TModel : IStorageEntity
{
/// <summary>
/// Gets all data of type <typeparamref name="TModel"/> from the storage medium.
/// Gets data of type <typeparamref name="TModel"/> from the storage medium.
/// </summary>
/// <typeparam name="TFilter">The type of the filter carrying the criteria used to filter the results.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching data is returned.</param>
/// <param name="sortBy">The name of the field by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <typeparamref name="TModel"/>, or an error.</returns>
Task<Result<IEnumerable<TModel>>> GetAllAsync(CancellationToken cancellationToken);
/// <returns>An <see cref="Result{TValue}"/> containing either a paginated result of type <typeparamref name="TModel"/>, or an error.</returns>
Task<Result<PaginatedResultDto<TModel>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto;
}
@@ -8,7 +8,7 @@ using System.Threading.Tasks;
namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
/// <summary>
/// Interface defining the "get by id" action for interacting with a generic persistance medium.
/// Interface defining the "get by id" action for interacting with a generic persistence medium.
/// </summary>
/// <typeparam name="TModel">The type used as a result for the "get by id" action. It should implement <see cref="IStorageEntity"/>.</typeparam>
/// <typeparam name="TId">The type used for the identifier of the respository. It should not be <see langword="null"/>.</typeparam>
@@ -19,7 +19,9 @@ public interface IGetByIdRepositoryAction<TModel, TId> where TModel : IStorageEn
/// Gets an element of type <typeparamref name="TModel"/> identified by <paramref name="id"/> from the storage medium.
/// </summary>
/// <param name="id">The id of the element to get.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entity should be loaded together with the entity itself. Pass <see langword="false"/> to retrieve only the data stored directly on the entity row.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entity should be tracked by the persistence medium, so that changes to it can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <typeparamref name="TModel"/> identified by <paramref name="id"/>, or an error.</returns>
Task<Result<TModel?>> GetByIdAsync(TId id, CancellationToken cancellationToken);
Task<Result<TModel?>> GetByIdAsync(TId id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default);
}
@@ -2,8 +2,11 @@
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Errors;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
@@ -38,8 +41,8 @@ internal sealed class PermissionRepository : IPermissionRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(PermissionEntity permission, CancellationToken cancellationToken)
{
bool permissionExists = await _luminaDbContext.Permissions.AnyAsync(repositoryPermission => repositoryPermission.Id == permission.Id, cancellationToken).ConfigureAwait(false);
if (permissionExists)
bool doesPermissionExist = await _luminaDbContext.Permissions.AnyAsync(repositoryPermission => repositoryPermission.Id == permission.Id, cancellationToken).ConfigureAwait(false);
if (doesPermissionExist)
return Errors.Authorization.PermissionAlreadyExists;
_luminaDbContext.Permissions.Add(permission);
@@ -47,13 +50,54 @@ internal sealed class PermissionRepository : IPermissionRepository
}
/// <summary>
/// Gets all autorization permissions.
/// Gets all the authorization permissions, or a page of them when the pagination data is provided.
/// </summary>
/// <typeparam name="TFilter">The type of the filter carrying the criteria used to filter the results.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all the matching permissions are returned.</param>
/// <param name="sortBy">The name of the field by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="PermissionEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<PermissionEntity>>> GetAllAsync(CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> containing either a paginated result of <see cref="PermissionEntity"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<PermissionEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
return await _luminaDbContext.Permissions.ToListAsync(cancellationToken).ConfigureAwait(false);
IQueryable<PermissionEntity> query = _luminaDbContext.Permissions;
if (!shouldTrackEntities)
query = query.AsNoTracking();
// If no pagination was requested, return all the permissions.
if (paginationData is null)
{
IReadOnlyList<PermissionEntity> allPermissions = await query.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<PermissionEntity>
{
Data = allPermissions,
CurrentPage = 1,
PerPage = allPermissions.Count,
Count = allPermissions.Count,
NumberOfPages = 1
};
}
int count = await query.Select(permission => permission.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
IReadOnlyList<PermissionEntity> paginatedResult = await query
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<PermissionEntity>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
@@ -2,11 +2,15 @@
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Errors;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -37,8 +41,8 @@ internal sealed class RoleRepository : IRoleRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(RoleEntity role, CancellationToken cancellationToken)
{
bool roleExists = await _luminaDbContext.Roles.AnyAsync(repositoryRole => repositoryRole.Id == role.Id || repositoryRole.RoleName == role.RoleName, cancellationToken).ConfigureAwait(false);
if (roleExists)
bool doesRoleExist = await _luminaDbContext.Roles.AnyAsync(repositoryRole => repositoryRole.Id == role.Id || repositoryRole.RoleName == role.RoleName, cancellationToken).ConfigureAwait(false);
if (doesRoleExist)
return Errors.Authorization.RoleAlreadyExists;
_luminaDbContext.Roles.Add(role);
@@ -46,13 +50,57 @@ internal sealed class RoleRepository : IRoleRepository
}
/// <summary>
/// Gets all autorization roles.
/// Gets all the authorization roles, or a page of them when the pagination data is provided.
/// </summary>
/// <typeparam name="TFilter">The type of the filter carrying the criteria used to filter the results.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all the matching roles are returned.</param>
/// <param name="sortBy">The name of the field by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="RoleEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<RoleEntity>>> GetAllAsync(CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> containing either a paginated result of <see cref="RoleEntity"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<RoleEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
return await _luminaDbContext.Roles.ToListAsync(cancellationToken).ConfigureAwait(false);
IQueryable<RoleEntity> query = _luminaDbContext.Roles;
// Apply no-tracking when the caller only reads, so the entities are not tracked by the context.
if (!shouldTrackEntities)
query = query.AsNoTracking();
// If no pagination was requested, return all the roles.
if (paginationData is null)
{
IReadOnlyList<RoleEntity> allRoles = await query.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<RoleEntity>
{
Data = allRoles,
CurrentPage = 1,
PerPage = allRoles.Count,
Count = allRoles.Count,
NumberOfPages = 1
};
}
// Count the matching roles first, so the requested page can be clamped to the number of available pages.
int count = await query.Select(role => role.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
// Fetch only the requested page of roles.
IReadOnlyList<RoleEntity> paginatedResult = await query
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<RoleEntity>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
@@ -76,13 +124,19 @@ internal sealed class RoleRepository : IRoleRepository
/// <param name="id">The id of the authorization role to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="RoleEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<RoleEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
public async Task<Result<RoleEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
return await _luminaDbContext.Roles
.Include(role => role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission)
.FirstOrDefaultAsync(role => role.Id == id, cancellationToken)
.ConfigureAwait(false);
IQueryable<RoleEntity> query = _luminaDbContext.Roles;
// Apply no-tracking when the caller only reads, so the entities are not tracked by the context.
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(role => role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission);
}
return await query.FirstOrDefaultAsync(role => role.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -93,16 +147,18 @@ internal sealed class RoleRepository : IRoleRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> UpdateAsync(RoleEntity data, CancellationToken cancellationToken)
{
// check if a role with the requested Id exists, and retrieve it
// Check if a role with the requested Id exists, and retrieve it.
RoleEntity? foundRole = await _luminaDbContext.Roles
.Include(role => role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission)
.FirstOrDefaultAsync(role => role.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundRole is null)
return Errors.Authorization.RoleNotFound;
// update scalar properties
// Update the scalar properties.
_luminaDbContext.Entry(foundRole).CurrentValues.SetValues(data);
// update owned entities (their changes are not automatically tracked by EF)
// Update the owned entities, whose changes are not tracked by EF automatically.
foundRole.RolePermissions.Clear();
foreach (RolePermissionEntity rolePermission in data.RolePermissions)
foundRole.RolePermissions.Add(rolePermission);
@@ -117,12 +173,13 @@ internal sealed class RoleRepository : IRoleRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
// check if a role with the requested Id exists, and retrieve it
// Check if a role with the requested Id exists, and retrieve it.
RoleEntity? foundRole = await _luminaDbContext.Roles
.FirstOrDefaultAsync(role => role.Id == id, cancellationToken).ConfigureAwait(false);
if (foundRole is null)
return Errors.Authorization.RoleNotFound;
// then, remove it
// Remove the role.
_luminaDbContext.Remove(foundRole);
return Result.Deleted;
}
@@ -2,8 +2,12 @@
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
@@ -38,8 +42,8 @@ internal sealed class LibraryRepository : ILibraryRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(LibraryEntity library, CancellationToken cancellationToken)
{
bool libraryExists = await _luminaDbContext.Libraries.AnyAsync(repositoryLibrary => repositoryLibrary.Id == library.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (libraryExists)
bool doesLibraryExist = await _luminaDbContext.Libraries.AnyAsync(repositoryLibrary => repositoryLibrary.Id == library.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (doesLibraryExist)
return Errors.Library.LibraryAlreadyExists;
_luminaDbContext.Libraries.Add(library);
@@ -52,11 +56,17 @@ internal sealed class LibraryRepository : ILibraryRepository
/// <param name="id">The Id of the library to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="LibraryEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<LibraryEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
public async Task<Result<LibraryEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
return await _luminaDbContext.Libraries
.Include(library => library.ContentLocations)
.FirstOrDefaultAsync(library => library.Id == id, cancellationToken).ConfigureAwait(false);
IQueryable<LibraryEntity> query = _luminaDbContext.Libraries;
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(library => library.ContentLocations);
}
return await query.FirstOrDefaultAsync(library => library.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -86,21 +96,65 @@ internal sealed class LibraryRepository : ILibraryRepository
}
/// <summary>
/// Gets all media libraries.
/// Gets all the media libraries, or a page of them when the pagination data is provided.
/// </summary>
/// <typeparam name="TFilter">The type of the filter carrying the criteria used to filter the results.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all the matching media libraries are returned.</param>
/// <param name="sortBy">The name of the field by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<LibraryEntity>>> GetAllAsync(CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> containing either a paginated result of <see cref="LibraryEntity"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<LibraryEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
return await _luminaDbContext.Libraries
.Include(library => library.ContentLocations)
IQueryable<LibraryEntity> query = _luminaDbContext.Libraries;
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(library => library.ContentLocations);
}
// If no pagination was requested, return all the media libraries.
if (paginationData is null)
{
IReadOnlyList<LibraryEntity> allLibraries = await query.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<LibraryEntity>
{
Data = allLibraries,
CurrentPage = 1,
PerPage = allLibraries.Count,
Count = allLibraries.Count,
NumberOfPages = 1
};
}
int count = await query.Select(library => library.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
IReadOnlyList<LibraryEntity> paginatedResult = await query
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<LibraryEntity>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Updates a media library.
/// Updates a media library, replacing only the editable data that actually changed, while preserving its identity, its audit columns, and the identity of its content locations.
/// </summary>
/// <param name="data">The media library to update.</param>
/// <param name="data">The media library whose editable data is applied to the stored library.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> UpdateAsync(LibraryEntity data, CancellationToken cancellationToken)
@@ -110,12 +164,20 @@ internal sealed class LibraryRepository : ILibraryRepository
.FirstOrDefaultAsync(library => library.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundLibrary is null)
return Errors.Library.LibraryNotFound;
// update scalar properties
_luminaDbContext.Entry(foundLibrary).CurrentValues.SetValues(data);
// update owned entities (their changes are not automatically tracked by EF)
foundLibrary.ContentLocations.Clear();
foreach (LibraryContentLocationEntity contentLocation in data.ContentLocations)
foundLibrary.ContentLocations.Add(contentLocation);
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundLibrary, data);
// A content location is matched by its path. Matched locations keep their identity and the locations that did not change are left exactly as they are stored,
// so that editing a library never deletes and re-inserts all of its content locations.
CollectionReconciler.Reconcile(
foundLibrary.ContentLocations,
data.ContentLocations,
existingContentLocation => existingContentLocation.Path,
incomingContentLocation => incomingContentLocation.Path,
shouldReplace: (existingContentLocation, incomingContentLocation) => false,
createNew: incomingContentLocation => incomingContentLocation);
return Result.Updated;
}
@@ -39,9 +39,9 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(LibraryScanEntity libraryScan, CancellationToken cancellationToken)
{
bool libraryScanExists = await _luminaDbContext.LibraryScans.AnyAsync(
bool doesLibraryScanExist = await _luminaDbContext.LibraryScans.AnyAsync(
repositoryScanLibrary => repositoryScanLibrary.Id == libraryScan.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (libraryScanExists)
if (doesLibraryScanExist)
return Errors.LibraryScanning.LibraryScanAlreadyExists;
_luminaDbContext.LibraryScans.Add(libraryScan);
@@ -54,12 +54,18 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository
/// <param name="id">The id of the library scan to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="LibraryScanEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<LibraryScanEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
public async Task<Result<LibraryScanEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
return await _luminaDbContext.LibraryScans
.Include(libraryScan => libraryScan.Library)
.Include(libraryScan => libraryScan.User)
.FirstOrDefaultAsync(libraryScan => libraryScan.Id == id, cancellationToken).ConfigureAwait(false);
IQueryable<LibraryScanEntity> query = _luminaDbContext.LibraryScans;
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(libraryScan => libraryScan.Library)
.Include(libraryScan => libraryScan.User);
}
return await query.FirstOrDefaultAsync(libraryScan => libraryScan.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -101,7 +107,7 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository
.FirstOrDefaultAsync(libraryScan => libraryScan.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundLibraryScan is null)
return Errors.LibraryScanning.LibraryScanNotFound;
// update scalar properties
// Update scalar properties.
_luminaDbContext.Entry(foundLibraryScan).CurrentValues.SetValues(data);
return Result.Updated;
}
@@ -2,11 +2,15 @@
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -35,21 +39,63 @@ internal sealed class PluginRepository : IPluginRepository
/// <param name="id">The Id of the plugin to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PluginEntity"/>, or an error.</returns>
public async Task<Result<PluginEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
public async Task<Result<PluginEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
return await _luminaDbContext.Plugins
.FirstOrDefaultAsync(plugin => plugin.Id == id, cancellationToken).ConfigureAwait(false);
IQueryable<PluginEntity> query = _luminaDbContext.Plugins;
if (!shouldTrackEntities)
query = query.AsNoTracking();
return await query.FirstOrDefaultAsync(plugin => plugin.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all the detected plugins.
/// Gets all the detected plugins, or a page of them when the pagination data is provided.
/// </summary>
/// <typeparam name="TFilter">The type of the filter carrying the criteria used to filter the results.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all the matching plugins are returned.</param>
/// <param name="sortBy">The name of the field by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="PluginEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<PluginEntity>>> GetAllAsync(CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> containing either a paginated result of <see cref="PluginEntity"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<PluginEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
return await _luminaDbContext.Plugins
IQueryable<PluginEntity> query = _luminaDbContext.Plugins;
if (!shouldTrackEntities)
query = query.AsNoTracking();
// If no pagination was requested, return all the plugins.
if (paginationData is null)
{
IReadOnlyList<PluginEntity> allPlugins = await query.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<PluginEntity>
{
Data = allPlugins,
CurrentPage = 1,
PerPage = allPlugins.Count,
Count = allPlugins.Count,
NumberOfPages = 1
};
}
int count = await query.Select(plugin => plugin.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
IReadOnlyList<PluginEntity> paginatedResult = await query
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<PluginEntity>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
@@ -66,7 +112,7 @@ internal sealed class PluginRepository : IPluginRepository
_luminaDbContext.Plugins.Add(plugin);
else
{
// update only the detection fields, preserving the stored settings and creation date
// Update only the detection fields, preserving the stored settings and creation date.
existingPlugin.Name = plugin.Name;
existingPlugin.Author = plugin.Author;
existingPlugin.Version = plugin.Version;
@@ -36,11 +36,14 @@ internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRe
/// <param name="id">The id of the execution to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobExecutionEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<ScheduledJobExecutionEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
public async Task<Result<ScheduledJobExecutionEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
// FindAsync returns an entity that was already loaded in the current unit of work from the change tracker, and only
// reads it from the storage medium when it is not tracked, so an entity loaded earlier is not read again.
return await _luminaDbContext.ScheduledJobExecutions.FindAsync([id], cancellationToken).ConfigureAwait(false);
// The execution is read with a query instead of FindAsync so that it can be retrieved without tracking when requested.
// When the entity is tracked, the change tracker still returns the already loaded instance instead of a new one.
IQueryable<ScheduledJobExecutionEntity> query = _luminaDbContext.ScheduledJobExecutions;
if (!shouldTrackEntities)
query = query.AsNoTracking();
return await query.FirstOrDefaultAsync(execution => execution.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -1,9 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Microsoft.EntityFrameworkCore;
using System;
@@ -37,11 +40,14 @@ internal sealed class ScheduledJobRepository : IScheduledJobRepository
/// <param name="id">The id of the scheduled job to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<ScheduledJobEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
public async Task<Result<ScheduledJobEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
// FindAsync returns an entity that was already loaded in the current unit of work from the change tracker, and only
// reads it from the storage medium when it is not tracked, so an entity loaded earlier is not read again.
return await _luminaDbContext.ScheduledJobs.FindAsync([id], cancellationToken).ConfigureAwait(false);
// The scheduled job is read with a query instead of FindAsync so that it can be retrieved without tracking when requested.
// When the entity is tracked, the change tracker still returns the already loaded instance instead of a new one.
IQueryable<ScheduledJobEntity> query = _luminaDbContext.ScheduledJobs;
if (!shouldTrackEntities)
query = query.AsNoTracking();
return await query.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -59,14 +65,54 @@ internal sealed class ScheduledJobRepository : IScheduledJobRepository
}
/// <summary>
/// Gets all scheduled jobs from the storage medium.
/// Gets all the scheduled jobs from the storage medium, or a page of them when the pagination data is provided.
/// </summary>
/// <typeparam name="TFilter">The type of the filter carrying the criteria used to filter the results.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all the matching scheduled jobs are returned.</param>
/// <param name="sortBy">The name of the field by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="ScheduledJobEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<ScheduledJobEntity>>> GetAllAsync(CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> containing either a paginated result of <see cref="ScheduledJobEntity"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<ScheduledJobEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
return await _luminaDbContext.ScheduledJobs
IQueryable<ScheduledJobEntity> query = _luminaDbContext.ScheduledJobs;
if (!shouldTrackEntities)
query = query.AsNoTracking();
// If no pagination was requested, return all the scheduled jobs.
if (paginationData is null)
{
IReadOnlyList<ScheduledJobEntity> allScheduledJobs = await query.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<ScheduledJobEntity>
{
Data = allScheduledJobs,
CurrentPage = 1,
PerPage = allScheduledJobs.Count,
Count = allScheduledJobs.Count,
NumberOfPages = 1
};
}
int count = await query.Select(scheduledJob => scheduledJob.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
IReadOnlyList<ScheduledJobEntity> paginatedResult = await query
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<ScheduledJobEntity>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
@@ -2,8 +2,11 @@
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
@@ -38,8 +41,8 @@ internal sealed class ThemeRepository : IThemeRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(ThemeEntity theme, CancellationToken cancellationToken)
{
bool themeExists = await _luminaDbContext.Themes.AnyAsync(repositoryTheme => repositoryTheme.Id == theme.Id, cancellationToken).ConfigureAwait(false);
if (themeExists)
bool doesThemeExist = await _luminaDbContext.Themes.AnyAsync(repositoryTheme => repositoryTheme.Id == theme.Id, cancellationToken).ConfigureAwait(false);
if (doesThemeExist)
return Errors.Themes.ThemeNotFound;
_luminaDbContext.Themes.Add(theme);
@@ -64,13 +67,54 @@ internal sealed class ThemeRepository : IThemeRepository
}
/// <summary>
/// Gets all themes from the storage medium.
/// Gets all the themes from the storage medium, or a page of them when the pagination data is provided.
/// </summary>
/// <typeparam name="TFilter">The type of the filter carrying the criteria used to filter the results.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all the matching themes are returned.</param>
/// <param name="sortBy">The name of the field by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="ThemeEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<ThemeEntity>>> GetAllAsync(CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> containing either a paginated result of <see cref="ThemeEntity"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<ThemeEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
return await _luminaDbContext.Themes.ToListAsync(cancellationToken).ConfigureAwait(false);
IQueryable<ThemeEntity> query = _luminaDbContext.Themes;
if (!shouldTrackEntities)
query = query.AsNoTracking();
// If no pagination was requested, return all the themes.
if (paginationData is null)
{
IReadOnlyList<ThemeEntity> allThemes = await query.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<ThemeEntity>
{
Data = allThemes,
CurrentPage = 1,
PerPage = allThemes.Count,
Count = allThemes.Count,
NumberOfPages = 1
};
}
int count = await query.Select(theme => theme.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
IReadOnlyList<ThemeEntity> paginatedResult = await query
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<ThemeEntity>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
@@ -3,11 +3,15 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -38,8 +42,8 @@ internal sealed class UserRepository : IUserRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(UserEntity user, CancellationToken cancellationToken)
{
bool userExists = await _luminaDbContext.Users.AnyAsync(repositoryUser => repositoryUser.Id == user.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (userExists)
bool doesUserExist = await _luminaDbContext.Users.AnyAsync(repositoryUser => repositoryUser.Id == user.Id, cancellationToken: cancellationToken).ConfigureAwait(false);
if (doesUserExist)
return Errors.Users.UserAlreadyExists;
_luminaDbContext.Users.Add(user);
@@ -47,13 +51,54 @@ internal sealed class UserRepository : IUserRepository
}
/// <summary>
/// Gets all users.
/// Gets all the users, or a page of them when the pagination data is provided.
/// </summary>
/// <typeparam name="TFilter">The type of the filter carrying the criteria used to filter the results.</typeparam>
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all the matching users are returned.</param>
/// <param name="sortBy">The name of the field by which to sort the results.</param>
/// <param name="sortOrder">The direction in which to sort the results.</param>
/// <param name="filterModel">The model containing the parameters used to filter the results.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass <see langword="false"/> to retrieve only the data stored directly on the entity rows.</param>
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="UserEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<UserEntity>>> GetAllAsync(CancellationToken cancellationToken)
/// <returns>An <see cref="Result{TValue}"/> containing either a paginated result of <see cref="UserEntity"/>, or an error.</returns>
public async Task<Result<PaginatedResultDto<UserEntity>>> GetAllAsync<TFilter>(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto
{
return await _luminaDbContext.Users.ToListAsync(cancellationToken).ConfigureAwait(false);
IQueryable<UserEntity> query = _luminaDbContext.Users;
if (!shouldTrackEntities)
query = query.AsNoTracking();
// If no pagination was requested, return all the users.
if (paginationData is null)
{
IReadOnlyList<UserEntity> allUsers = await query.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<UserEntity>
{
Data = allUsers,
CurrentPage = 1,
PerPage = allUsers.Count,
Count = allUsers.Count,
NumberOfPages = 1
};
}
int count = await query.Select(user => user.Id).CountAsync(cancellationToken).ConfigureAwait(false);
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
IReadOnlyList<UserEntity> paginatedResult = await query
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return new PaginatedResultDto<UserEntity>
{
Data = paginatedResult,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
@@ -95,10 +140,10 @@ internal sealed class UserRepository : IUserRepository
if (foundUser is null)
return Errors.Users.UserDoesNotExist;
// update scalar properties
// Update scalar properties.
_luminaDbContext.Entry(foundUser).CurrentValues.SetValues(data);
// update user permissions
// Update user permissions.
List<UserPermissionEntity> existingPermissions = [.. foundUser.UserPermissions];
foreach (UserPermissionEntity permission in existingPermissions)
_luminaDbContext.UserPermissions.Remove(permission);
@@ -114,7 +159,7 @@ internal sealed class UserRepository : IUserRepository
});
}
// update user role
// Update user role.
if (foundUser.UserRole != null)
_luminaDbContext.UserRoles.Remove(foundUser.UserRole);
if (data.UserRole is not null)
@@ -136,16 +181,22 @@ internal sealed class UserRepository : IUserRepository
/// <param name="id">The id of the user to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="UserEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<UserEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
public async Task<Result<UserEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
return await _luminaDbContext.Users
.Include(user => user.Libraries)
.ThenInclude(library => library.ContentLocations)
.Include(user => user.UserPermissions)
.ThenInclude(userPermission => userPermission.Permission)
.Include(user => user.UserRole!.Role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission)
.FirstOrDefaultAsync(user => user.Id == id, cancellationToken)
IQueryable<UserEntity> query = _luminaDbContext.Users;
if (!shouldTrackEntities)
query = query.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(user => user.Libraries)
.ThenInclude(library => library.ContentLocations)
.Include(user => user.UserPermissions)
.ThenInclude(userPermission => userPermission.Permission)
.Include(user => user.UserRole!.Role.RolePermissions)
.ThenInclude(rolePermission => rolePermission.Permission);
}
return await query.FirstOrDefaultAsync(user => user.Id == id, cancellationToken)
.ConfigureAwait(false);
}
}
@@ -6,6 +6,7 @@ using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -36,8 +37,8 @@ internal sealed class UserSettingsRepository : IUserSettingsRepository
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(UserSettingsEntity data, CancellationToken cancellationToken)
{
bool settingsExists = await _luminaDbContext.UserSettings.AnyAsync(settings => settings.UserId == data.UserId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (settingsExists)
bool doesSettingsExist = await _luminaDbContext.UserSettings.AnyAsync(settings => settings.UserId == data.UserId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (doesSettingsExist)
return Errors.UserSettings.UserSettingsAlreadyExists;
_luminaDbContext.UserSettings.Add(data);
@@ -50,10 +51,12 @@ internal sealed class UserSettingsRepository : IUserSettingsRepository
/// <param name="id">The Id of the user settings to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the <see cref="UserSettingsEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<UserSettingsEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
public async Task<Result<UserSettingsEntity?>> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
{
return await _luminaDbContext.UserSettings
.FirstOrDefaultAsync(settings => settings.Id == id, cancellationToken)
IQueryable<UserSettingsEntity> query = _luminaDbContext.UserSettings;
if (!shouldTrackEntities)
query = query.AsNoTracking();
return await query.FirstOrDefaultAsync(settings => settings.Id == id, cancellationToken)
.ConfigureAwait(false);
}
@@ -37,15 +37,15 @@ internal class DirectoryProviderService : IDirectoryProviderService
/// 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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of directory paths or an error.</returns>
public Result<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements)
public Result<IEnumerable<FileSystemPathId>> GetSubdirectoryPaths(FileSystemPathId path, bool shouldIncludeHiddenElements)
{
// check if the user has access permissions to the provided path
// Check if the user has access permissions to the provided path.
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory, false))
return Errors.Permission.UnauthorizedAccess;
return Result.From(_fileSystem.Directory.GetDirectories(path.Path)
.Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden)
.Where(path => shouldIncludeHiddenElements || (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))
@@ -63,7 +63,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
{
try
{
// File.GetAttributes is used for both directories and files
// File.GetAttributes is used for both directories and files.
return _fileSystem.File.GetAttributes(path);
}
catch
@@ -101,7 +101,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
/// <returns>An <see cref="Result{TValue}"/> containing either the optional last write time of <paramref name="path"/> if available, or an error.</returns>
public Result<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided 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));
@@ -114,7 +114,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
/// <returns>An <see cref="Result{TValue}"/> containing the optional creation time of <paramref name="path"/> if available, or an error.</returns>
public Result<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided 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));
@@ -128,10 +128,10 @@ internal class DirectoryProviderService : IDirectoryProviderService
/// <returns>An <see cref="Result{TValue}"/> containing either the path of a created directory, or an error.</returns>
public Result<FileSystemPathId> CreateDirectory(FileSystemPathId path, string name)
{
// to create a directory, its parent directory must be writable
// 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
// Create the directory and return its absolute path.
string directoryPath = _fileSystem.Directory.CreateDirectory(_fileSystem.Path.Combine(path.Path, name)).FullName;
return FileSystemPathId.Create(directoryPath);
}
@@ -141,28 +141,28 @@ internal class DirectoryProviderService : IDirectoryProviderService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the copied directory, or an error.</returns>
public Result<FileSystemPathId> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
public Result<FileSystemPathId> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting)
{
// check if the source directory exists
// 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
// Create the new directory.
IDirectoryInfo destDirInfo = _fileSystem.DirectoryInfo.New(_fileSystem.Directory.CreateDirectory(destPath).FullName);
// get the information of the source directory
// Get the information of the source directory.
IDirectoryInfo sourceDirInfo = _fileSystem.DirectoryInfo.New(sourcePath.Path);
// copy all files
// 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
fileInfo.CopyTo(targetFilePath, shouldOverrideExisting);
_fileSystem.File.SetAttributes(targetFilePath, fileInfo.Attributes); // Preserve file attributes.
}
// copy all subdirectories
// Copy all subdirectories.
foreach (IDirectoryInfo subDirInfo in sourceDirInfo.GetDirectories())
{
Result<FileSystemPathId> newSourcePathResult = FileSystemPathId.Create(subDirInfo.FullName);
@@ -171,8 +171,8 @@ internal class DirectoryProviderService : IDirectoryProviderService
Result<FileSystemPathId> newDestinationPathResult = FileSystemPathId.Create(_fileSystem.Path.Combine(destPath, subDirInfo.Name));
if (newDestinationPathResult.IsFailure)
return newDestinationPathResult.Errors;
// recursive call
Result<FileSystemPathId> copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, overrideExisting);
// Recursive call.
Result<FileSystemPathId> copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, shouldOverrideExisting);
if (copySubDirResult.IsFailure)
return copySubDirResult.Errors;
}
@@ -193,7 +193,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
{
string destPath = destinationPath;
int copyNumber = 1;
// check if the destination directory exists and create a unique directory name
// 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;
@@ -204,20 +204,20 @@ internal class DirectoryProviderService : IDirectoryProviderService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a moved directory, or an error.</returns>
public Result<FileSystemPathId> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
public Result<FileSystemPathId> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting)
{
// check if the source directory exists
// 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 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
MergeDirectories(sourcePath.Path, destinationPath.Path, shouldOverrideExisting); // If the destination directory exists, perform a merge based on the overwrite policy.
return FileSystemPathId.Create(destinationPath.Path);
}
catch
@@ -231,39 +231,39 @@ internal class DirectoryProviderService : IDirectoryProviderService
/// </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)
/// <param name="shouldOverwrite">Whether to override existing files.</param>
private void MergeDirectories(string sourceDir, string destDir, bool shouldOverwrite)
{
// merge files from source directory to destination directory
// 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 a file with the same name exists in the destination.
if (_fileSystem.File.Exists(destFilePath))
{
if (overwrite)
if (shouldOverwrite)
{
// overwrite the file in the destination directory
// 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
_fileSystem.File.Move(sourceFilePath, destFilePath); // Move the file if it does not exist in the destination directory.
}
// recursively merge subdirectories
// 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 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
MergeDirectories(sourceSubDirPath, destSubDirPath, shouldOverwrite); // If the subdirectory exists, recursively merge its contents.
}
// after merging the contents, delete the source directory if it's now empty
// After merging the contents, delete the source directory if it's now empty.
if (!_fileSystem.Directory.EnumerateFileSystemEntries(sourceDir).Any())
_fileSystem.Directory.Delete(sourceDir);
}
@@ -276,22 +276,22 @@ internal class DirectoryProviderService : IDirectoryProviderService
/// <returns>An <see cref="Result{TValue}"/> containing either the absolute path of the renamed directory, or an error.</returns>
public Result<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))
// To rename a directory, its parent directory must be writable.
Optional<string> parentDirectory = Optional<string>.FromNullable(_fileSystem.Directory.GetParent(path.Path)?.FullName);
if (parentDirectory.HasValue && !string.IsNullOrEmpty(parentDirectory.Value))
{
Result<FileSystemPathId> parendDirectoryResult = FileSystemPathId.Create(parentDirectory);
Result<FileSystemPathId> parendDirectoryResult = FileSystemPathId.Create(parentDirectory.Value);
if (parendDirectoryResult.IsFailure)
return parendDirectoryResult.Errors;
string? newDirectory = _fileSystem.Path.Combine(parentDirectory, name);
if (!string.IsNullOrEmpty(newDirectory))
Optional<string> newDirectory = Optional<string>.FromNullable(_fileSystem.Path.Combine(parentDirectory.Value, name));
if (newDirectory.HasValue && !string.IsNullOrEmpty(newDirectory.Value))
{
Result<FileSystemPathId> newDirectoryPathResult = FileSystemPathId.Create(newDirectory);
Result<FileSystemPathId> newDirectoryPathResult = FileSystemPathId.Create(newDirectory.Value);
if (newDirectoryPathResult.IsFailure)
return newDirectoryPathResult.Errors;
if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write, false))
return Errors.Permission.UnauthorizedAccess;
// to rename a directory, it must be executable
// 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);
@@ -311,7 +311,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
/// <returns>An <see cref="Result{TValue}"/> containing either the result of deleting a directory, or an error.</returns>
public Result<Deleted> DeleteDirectory(FileSystemPathId path)
{
// check if the user has access permissions to the provided 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);
@@ -36,48 +36,48 @@ public class DirectoryService : IDirectoryService
/// 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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
public Result<IEnumerable<Directory>> GetSubdirectories(string path, bool includeHiddenElements)
public Result<IEnumerable<Directory>> GetSubdirectories(string path, bool shouldIncludeHiddenElements)
{
Result<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsFailure)
return fileSystemPathIdResult.Errors;
return GetSubdirectories(fileSystemPathIdResult.Value, includeHiddenElements);
return GetSubdirectories(fileSystemPathIdResult.Value, shouldIncludeHiddenElements);
}
/// <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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
public Result<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool includeHiddenElements)
public Result<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool shouldIncludeHiddenElements)
{
return GetSubdirectories(directory.Id, includeHiddenElements);
return GetSubdirectories(directory.Id, shouldIncludeHiddenElements);
}
/// <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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
public Result<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements)
public Result<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool shouldIncludeHiddenElements)
{
// retrieve the list of subdirectories
Result<IEnumerable<FileSystemPathId>> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, includeHiddenElements);
// Retrieve the list of subdirectories.
Result<IEnumerable<FileSystemPathId>> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, shouldIncludeHiddenElements);
if (subdirectoryPathsResult.IsFailure)
return subdirectoryPathsResult.Errors;
List<Directory> result = [];
foreach (FileSystemPathId subPath in subdirectoryPathsResult.Value)
{
// extract directory details
// Extract directory details.
Result<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(subPath);
Result<Optional<DateTime>> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(subPath);
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(subPath);
// if any error occurred, mark directory as Inaccessible
// If any error occurred, mark the directory as inaccessible.
if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure)
{
Result<Directory> errorDirResult = Directory.Create(subPath, !dirNameResult.IsFailure ? dirNameResult.Value : null!,
@@ -123,7 +123,7 @@ public class DirectoryService : IDirectoryService
/// <returns>An <see cref="Result{TValue}"/> containing either the result of creating a directory, or an error.</returns>
public Result<Directory> CreateDirectory(FileSystemPathId path, string name)
{
// first, check if the directory about to be created does not already exist
// First, check that the target directory does not already exist.
Result<FileSystemPathId> combinedPath = _platformContext.PathStrategy.CombinePath(path, name);
if (combinedPath.IsFailure)
return combinedPath.Errors;
@@ -134,14 +134,14 @@ public class DirectoryService : IDirectoryService
return Errors.FileSystemManagement.DirectoryAlreadyExists;
else
{
// create the new directory
// Create the new directory.
Result<FileSystemPathId> newDirectoryPathResult = _environmentContext.DirectoryProviderService.CreateDirectory(path, name);
if (newDirectoryPathResult.IsFailure)
return newDirectoryPathResult.Errors;
Result<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value);
Result<Optional<DateTime>> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value);
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value);
// if any error occurred, mark directory as Inaccessible
// If any error occurred, mark the directory as inaccessible.
if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure)
{
Result<Directory> errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsFailure ? dirNameResult.Value : null!,
@@ -164,11 +164,11 @@ public class DirectoryService : IDirectoryService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a copied directory, or an error.</returns>
public Result<Directory> CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting)
public Result<Directory> CopyDirectory(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting)
{
// make sure the paths are in the expected format
// 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))
@@ -179,7 +179,7 @@ public class DirectoryService : IDirectoryService
Result<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
if (fileSystemDestinationPathIdResult.IsFailure)
return fileSystemDestinationPathIdResult.Errors;
return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value);
}
/// <summary>
@@ -187,9 +187,9 @@ public class DirectoryService : IDirectoryService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the copied directory, or an error.</returns>
public Result<Directory> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
public Result<Directory> CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting)
{
Result<bool> directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath);
if (directoryExists.IsFailure)
@@ -198,8 +198,8 @@ public class DirectoryService : IDirectoryService
return Errors.FileSystemManagement.DirectoryNotFound;
else
{
// copy the directory
Result<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, overrideExisting);
// Copy the directory.
Result<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, shouldOverrideExisting);
throw new NotImplementedException();
}
@@ -210,11 +210,11 @@ public class DirectoryService : IDirectoryService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a moved directory, or an error.</returns>
public Result<Directory> MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting)
public Result<Directory> MoveDirectory(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting)
{
// make sure the paths are in the expected format
// 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))
@@ -225,7 +225,7 @@ public class DirectoryService : IDirectoryService
Result<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath);
if (fileSystemDestinationPathIdResult.IsFailure)
return fileSystemDestinationPathIdResult.Errors;
return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value);
}
/// <summary>
@@ -233,9 +233,9 @@ public class DirectoryService : IDirectoryService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the moved directory, or an error.</returns>
public Result<Directory> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting)
public Result<Directory> MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting)
{
Result<bool> directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath);
if (directoryExists.IsFailure)
@@ -244,8 +244,8 @@ public class DirectoryService : IDirectoryService
return Errors.FileSystemManagement.DirectoryNotFound;
else
{
// move the directory
Result<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, overrideExisting);
// Move the directory.
Result<FileSystemPathId> newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, shouldOverrideExisting);
throw new NotImplementedException();
}
@@ -273,7 +273,7 @@ public class DirectoryService : IDirectoryService
/// <returns>An <see cref="Result{TValue}"/> containing either the renamed directory, or an error.</returns>
public Result<Directory> RenameDirectory(FileSystemPathId path, string name)
{
// first, check if the directory about to be created does not already exist
// First, check that the target directory does not already exist.
Result<FileSystemPathId> combinedPath = _platformContext.PathStrategy.CombinePath(path, name);
if (combinedPath.IsFailure)
return combinedPath.Errors;
@@ -284,14 +284,14 @@ public class DirectoryService : IDirectoryService
return Errors.FileSystemManagement.DirectoryAlreadyExists;
else
{
// rename the directory
// Rename the directory.
Result<FileSystemPathId> newDirectoryPathResult = _environmentContext.DirectoryProviderService.RenameDirectory(path, name);
if (newDirectoryPathResult.IsFailure)
return newDirectoryPathResult.Errors;
Result<string> dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value);
Result<Optional<DateTime>> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value);
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value);
// if any error occurred, mark directory as Inaccessible
// If any error occurred, mark the directory as inaccessible.
if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure)
{
Result<Directory> errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsFailure ? dirNameResult.Value : null!,
@@ -36,15 +36,15 @@ internal class FileProviderService : IFileProviderService
/// 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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of file paths or an error.</returns>
public Result<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path, bool includeHiddenElements)
public Result<IEnumerable<FileSystemPathId>> GetFilePaths(FileSystemPathId path, bool shouldIncludeHiddenElements)
{
// check if the user has access permissions to the provided path
// Check if the user has access permissions to the provided path.
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory))
return Errors.Permission.UnauthorizedAccess;
return Result.From(_fileSystem.Directory.GetFiles(path.Path)
.Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden)
.Where(path => shouldIncludeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden)
.OrderBy(path => path)
.Select(path => FileSystemPathId.Create(path))
.Where(pathIdResult => !pathIdResult.IsFailure)
@@ -61,7 +61,7 @@ internal class FileProviderService : IFileProviderService
{
try
{
// File.GetAttributes is used for both directories and files
// File.GetAttributes is used for both directories and files.
return _fileSystem.File.GetAttributes(path);
}
catch
@@ -97,7 +97,7 @@ internal class FileProviderService : IFileProviderService
/// <returns>An <see cref="Result{TValue}"/> containing either the contents of a file at the specified path, or an error.</returns>
public Result<byte[]> GetFileAsync(FileSystemPathId path)
{
// check if the user has access permissions to the provided path
// Check if the user has access permissions to the provided path.
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents))
return Errors.Permission.UnauthorizedAccess;
return _fileSystem.File.ReadAllBytes(path.Path);
@@ -110,7 +110,7 @@ internal class FileProviderService : IFileProviderService
/// <returns>An <see cref="Result{TValue}"/> containing either the optional last write time of <paramref name="path"/> if available, or an error.</returns>
public Result<Optional<DateTime>> GetLastWriteTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided 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));
@@ -123,7 +123,7 @@ internal class FileProviderService : IFileProviderService
/// <returns>An <see cref="Result{TValue}"/> containing either the optional creation time of <paramref name="path"/> if available, or an error.</returns>
public Result<Optional<DateTime>> GetCreationTime(FileSystemPathId path)
{
// check if the user has access permissions to the provided 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));
@@ -136,7 +136,7 @@ internal class FileProviderService : IFileProviderService
/// <returns>An <see cref="Result{TValue}"/> containing either the size of <paramref name="path"/> or an error.</returns>
public Result<long?> GetSize(FileSystemPathId path)
{
// check if the user has access permissions to the provided 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;
@@ -147,27 +147,27 @@ internal class FileProviderService : IFileProviderService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the copied file, or an error.</returns>
public Result<FileSystemPathId> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
public Result<FileSystemPathId> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting)
{
// check if the source file exists
// 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
// 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
// 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)
if (!shouldOverrideExisting)
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
_fileSystem.File.Copy(sourceFilePath.Path, destinationFilePath, shouldOverrideExisting); // Copy the file.
_fileSystem.File.SetAttributes(destinationFilePath, _fileSystem.File.GetAttributes(sourceFilePath.Path)); // Preserve file attributes.
return FileSystemPathId.Create(destinationFilePath);
}
catch
@@ -177,21 +177,23 @@ internal class FileProviderService : IFileProviderService
}
/// <summary>
/// Creates a file path that is unique
/// 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);
Optional<string> directory = Optional<string>.FromNullable(_fileSystem.Path.GetDirectoryName(destinationFilePath));
Optional<string> filename = Optional<string>.FromNullable(_fileSystem.Path.GetFileNameWithoutExtension(destinationFilePath));
Optional<string> extension = Optional<string>.FromNullable(_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))
// Check if the destination file exists and create a unique file name.
if (directory.HasValue && !string.IsNullOrEmpty(directory.Value)
&& filename.HasValue && !string.IsNullOrEmpty(filename.Value)
&& extension.HasValue && !string.IsNullOrEmpty(extension.Value))
while (_fileSystem.File.Exists(destFilePath))
destFilePath = _fileSystem.Path.Combine(directory, $"{filename} - Copy ({copyNumber++}){extension}");
destFilePath = _fileSystem.Path.Combine(directory.Value, $"{filename.Value} - Copy ({copyNumber++}){extension.Value}");
return destFilePath;
}
@@ -200,23 +202,23 @@ internal class FileProviderService : IFileProviderService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a moved file, or an error.</returns>
public Result<FileSystemPathId> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
public Result<FileSystemPathId> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting)
{
// check if the source file exists
// 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 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);
if (shouldOverrideExisting)
_fileSystem.File.Move(sourceFilePath.Path, destinationFilePath, shouldOverrideExisting);
else
return Errors.FileSystemManagement.FileAlreadyExists;
return FileSystemPathId.Create(destinationFilePath);
@@ -235,19 +237,19 @@ internal class FileProviderService : IFileProviderService
/// <returns>An <see cref="Result{TValue}"/> containing either the absolute path of the renamed file, or an error.</returns>
public Result<FileSystemPathId> RenameFile(FileSystemPathId path, string name)
{
string? parentDirectory = _fileSystem.FileInfo.New(path.Path)?.DirectoryName;
if (!string.IsNullOrEmpty(parentDirectory))
Optional<string> parentDirectory = Optional<string>.FromNullable(_fileSystem.FileInfo.New(path.Path)?.DirectoryName);
if (parentDirectory.HasValue && !string.IsNullOrEmpty(parentDirectory.Value))
{
Result<FileSystemPathId> parendDirectoryResult = FileSystemPathId.Create(parentDirectory);
Result<FileSystemPathId> parendDirectoryResult = FileSystemPathId.Create(parentDirectory.Value);
if (parendDirectoryResult.IsFailure)
return parendDirectoryResult.Errors;
string? newFile = _fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name);
if (!string.IsNullOrEmpty(newFile))
Optional<string> newFile = Optional<string>.FromNullable(_fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name));
if (newFile.HasValue && !string.IsNullOrEmpty(newFile.Value))
{
Result<FileSystemPathId> newFilePathResult = FileSystemPathId.Create(newFile);
Result<FileSystemPathId> newFilePathResult = FileSystemPathId.Create(newFile.Value);
if (newFilePathResult.IsFailure)
return newFilePathResult.Errors;
// renaming a file only requires write access to its parent directory, never execute access to the file itself
// Renaming a file only requires write access to its parent directory, never execute access to the file itself.
if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write))
return Errors.Permission.UnauthorizedAccess;
_fileSystem.File.Move(path.Path, newFilePathResult.Value.Path);
@@ -267,7 +269,7 @@ internal class FileProviderService : IFileProviderService
/// <returns>An <see cref="Result{TValue}"/> containing either the result of deleting a file, or an error.</returns>
public Result<Deleted> DeleteFile(FileSystemPathId path)
{
// check if the user has access permissions to the provided 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);
@@ -35,50 +35,50 @@ public class FileService : IFileService
/// 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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
public Result<IEnumerable<File>> GetFiles(string path, bool includeHiddenElements)
public Result<IEnumerable<File>> GetFiles(string path, bool shouldIncludeHiddenElements)
{
Result<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsFailure)
return fileSystemPathIdResult.Errors;
return GetFiles(fileSystemPathIdResult.Value, includeHiddenElements);
return GetFiles(fileSystemPathIdResult.Value, shouldIncludeHiddenElements);
}
/// <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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
public Result<IEnumerable<File>> GetFiles(File file, bool includeHiddenElements)
public Result<IEnumerable<File>> GetFiles(File file, bool shouldIncludeHiddenElements)
{
return GetFiles(file.Id, includeHiddenElements);
return GetFiles(file.Id, shouldIncludeHiddenElements);
}
/// <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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
public Result<IEnumerable<File>> GetFiles(FileSystemPathId path, bool includeHiddenElements)
public Result<IEnumerable<File>> GetFiles(FileSystemPathId path, bool shouldIncludeHiddenElements)
{
// retrieve the list of files
Result<IEnumerable<FileSystemPathId>> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, includeHiddenElements);
// Retrieve the list of files.
Result<IEnumerable<FileSystemPathId>> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, shouldIncludeHiddenElements);
if (filePathsResult.IsFailure)
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
// Extract file details and add them to the result list.
Result<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(filePath);
Result<Optional<DateTime>> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(filePath);
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(filePath);
Result<long?> sizeResult = _environmentContext.FileProviderService.GetSize(filePath);
long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0;
// if any of the details returned an error, set inaccessible status
// If any of the details returned an error, set the inaccessible status.
if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure)
{
Result<File> errorFileResult = File.Create(filePath, !fileNameResult.IsFailure ? fileNameResult.Value : null!,
@@ -107,13 +107,13 @@ public class FileService : IFileService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a copied file, or an error.</returns>
public Result<File> CopyFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting)
public Result<File> CopyFile(string sourceFilePath, string destinationDirectoryPath, Optional<bool> shouldOverrideExisting)
{
if (string.IsNullOrWhiteSpace(destinationDirectoryPath))
return Errors.FileSystemManagement.InvalidPath;
// make sure the paths are in the expected format
// Make sure the paths are in the expected format.
if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator;
Result<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
@@ -122,7 +122,7 @@ public class FileService : IFileService
Result<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
if (fileSystemDestinationPathIdResult.IsFailure)
return fileSystemDestinationPathIdResult.Errors;
return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value);
}
/// <summary>
@@ -130,9 +130,9 @@ public class FileService : IFileService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the copied file, or an error.</returns>
public Result<File> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
public Result<File> CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting)
{
Result<bool> fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
if (fileExists.IsFailure)
@@ -141,8 +141,8 @@ public class FileService : IFileService
return Errors.FileSystemManagement.FileNotFound;
else
{
// copy the file
Result<FileSystemPathId> copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, overrideExisting);
// Copy the file.
Result<FileSystemPathId> copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, shouldOverrideExisting);
if (copyFileResult.IsFailure)
return copyFileResult.Errors;
Result<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(copyFileResult.Value);
@@ -150,7 +150,7 @@ public class FileService : IFileService
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(copyFileResult.Value);
Result<long?> sizeResult = _environmentContext.FileProviderService.GetSize(copyFileResult.Value);
long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0;
// if any of the details returned an error, set inaccessible status
// If any of the details returned an error, set the inaccessible status.
if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure)
{
Result<File> errorFileResult = File.Create(copyFileResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!,
@@ -173,13 +173,13 @@ public class FileService : IFileService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a moved file, or an error.</returns>
public Result<File> MoveFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting)
public Result<File> MoveFile(string sourceFilePath, string destinationDirectoryPath, Optional<bool> shouldOverrideExisting)
{
if (string.IsNullOrWhiteSpace(destinationDirectoryPath))
return Errors.FileSystemManagement.InvalidPath;
// make sure the paths are in the expected format
// Make sure the paths are in the expected format.
if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator))
destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator;
Result<FileSystemPathId> fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath);
@@ -188,7 +188,7 @@ public class FileService : IFileService
Result<FileSystemPathId> fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath);
if (fileSystemDestinationPathIdResult.IsFailure)
return fileSystemDestinationPathIdResult.Errors;
return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false);
return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value);
}
/// <summary>
@@ -196,9 +196,9 @@ public class FileService : IFileService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the moved file, or an error.</returns>
public Result<File> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting)
public Result<File> MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting)
{
Result<bool> fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath);
if (fileExists.IsFailure)
@@ -207,8 +207,8 @@ public class FileService : IFileService
return Errors.FileSystemManagement.FileNotFound;
else
{
// move the file
Result<FileSystemPathId> moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, overrideExisting);
// Move the file.
Result<FileSystemPathId> moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, shouldOverrideExisting);
if (moveFileResult.IsFailure)
return moveFileResult.Errors;
Result<string> fileNameResult = _environmentContext.FileProviderService.GetFileName(moveFileResult.Value);
@@ -216,7 +216,7 @@ public class FileService : IFileService
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(moveFileResult.Value);
Result<long?> sizeResult = _environmentContext.FileProviderService.GetSize(moveFileResult.Value);
long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0;
// if any of the details returned an error, set inaccessible status
// If any of the details returned an error, set the inaccessible status.
if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure)
{
Result<File> errorFileResult = File.Create(moveFileResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!,
@@ -256,7 +256,7 @@ public class FileService : IFileService
/// <returns>An <see cref="Result{TValue}"/> containing either the renamed file, or an error.</returns>
public Result<File> RenameFile(FileSystemPathId path, string name)
{
// first, check if the directory about to be created does not already exist
// First, check that the target file does not already exist.
Result<FileSystemPathId> combinedPath = _platformContext.PathStrategy.CombinePath(path, name);
if (combinedPath.IsFailure)
return combinedPath.Errors;
@@ -267,7 +267,7 @@ public class FileService : IFileService
return Errors.FileSystemManagement.FileAlreadyExists;
else
{
// rename the file
// Rename the file.
Result<FileSystemPathId> newFilePathResult = _environmentContext.FileProviderService.RenameFile(path, name);
if (newFilePathResult.IsFailure)
return newFilePathResult.Errors;
@@ -276,7 +276,7 @@ public class FileService : IFileService
Result<Optional<DateTime>> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(newFilePathResult.Value);
Result<long?> sizeResult = _environmentContext.FileProviderService.GetSize(newFilePathResult.Value);
long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0;
// if any of the details returned an error, set inaccessible status
// If any of the details returned an error, set the inaccessible status.
if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure)
{
Result<File> errorFileResult = File.Create(newFilePathResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!,
@@ -16,25 +16,25 @@ public interface IDirectoryService
/// 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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
Result<IEnumerable<Directory>> GetSubdirectories(string path, bool includeHiddenElements);
Result<IEnumerable<Directory>> GetSubdirectories(string path, bool shouldIncludeHiddenElements);
/// <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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
Result<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool includeHiddenElements);
Result<IEnumerable<Directory>> GetSubdirectories(Directory directory, bool shouldIncludeHiddenElements);
/// <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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden subdirectories or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of subdirectories or an error.</returns>
Result<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements);
Result<IEnumerable<Directory>> GetSubdirectories(FileSystemPathId path, bool shouldIncludeHiddenElements);
/// <summary>
/// Creates a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
@@ -49,18 +49,18 @@ public interface IDirectoryService
/// </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>
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a copied directory, or an error.</returns>
Result<Directory> CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting);
Result<Directory> CopyDirectory(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting);
/// <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>
/// <param name="shouldOverrideExisting">Whether to override existing directories, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a moved directory, or an error.</returns>
Result<Directory> MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting);
Result<Directory> MoveDirectory(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting);
/// <summary>
/// Renames a directory with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
@@ -16,43 +16,43 @@ public interface IFileService
/// 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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
Result<IEnumerable<File>> GetFiles(string path, bool includeHiddenElements);
Result<IEnumerable<File>> GetFiles(string path, bool shouldIncludeHiddenElements);
/// <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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
Result<IEnumerable<File>> GetFiles(File file, bool includeHiddenElements);
Result<IEnumerable<File>> GetFiles(File file, bool shouldIncludeHiddenElements);
/// <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>
/// <param name="shouldIncludeHiddenElements">Whether to include hidden files or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of files or an error.</returns>
Result<IEnumerable<File>> GetFiles(FileSystemPathId path, bool includeHiddenElements);
Result<IEnumerable<File>> GetFiles(FileSystemPathId path, bool shouldIncludeHiddenElements);
/// <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>
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a copied file, or an error.</returns>
Result<File> CopyFile(string sourcePath, string destinationPath, bool? overrideExisting);
Result<File> CopyFile(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting);
/// <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>
/// <param name="shouldOverrideExisting">Whether to override existing files, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a moved file, or an error.</returns>
Result<File> MoveFile(string sourcePath, string destinationPath, bool? overrideExisting);
Result<File> MoveFile(string sourcePath, string destinationPath, Optional<bool> shouldOverrideExisting);
/// <summary>
/// Renames a file with the specified <paramref name="name"/>, at the specified <paramref name="path"/>.
@@ -27,9 +27,9 @@ public interface IPathService
/// 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>
/// <param name="shouldIncludeHiddenElements">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);
bool Exists(string path, bool shouldIncludeHiddenElements = true);
/// <summary>
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
@@ -72,4 +72,12 @@ public interface IPathService
/// <param name="path">The path for which to get the root.</param>
/// <returns>An <see cref="Result{TValue}"/> containing the root of <paramref name="path"/>, or an error.</returns>
Result<PathSegment> GetPathRoot(string path);
/// <summary>
/// Checks whether <paramref name="path"/> is located inside <paramref name="parentPath"/>.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="parentPath">The path that must contain the checked path.</param>
/// <returns><see langword="true"/> if the path is inside the parent path, <see langword="false"/> otherwise.</returns>
bool IsPathWithin(string path, string parentPath);
}
@@ -50,21 +50,21 @@ public class PathService : IPathService
/// 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>
/// <param name="shouldIncludeHiddenElements">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)
public bool Exists(string path, bool shouldIncludeHiddenElements = true)
{
Result<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsFailure)
return false;
return _platformContext.PathStrategy.Exists(newPathResult.Value, includeHiddenElements);
return _platformContext.PathStrategy.Exists(newPathResult.Value, shouldIncludeHiddenElements);
}
/// <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>
/// <param name="name">The name to be combined with the path.</param>
/// <returns>An <see cref="Result{TValue}"/> containing the combined path, or an error.</returns>
public Result<string> CombinePath(string path, string name)
{
@@ -127,28 +127,28 @@ public class PathService : IPathService
char[] invalidChars = _platformContext.PathStrategy.GetInvalidPathSegmentCharsForPlatform();
char[] sanitizedChars = [.. name.Trim().Select(character => Array.IndexOf(invalidChars, character) >= 0 ? ' ' : character)];
// collapse the consecutive whitespace into a single space, so that the segment does not contain ragged spacing
// Collapse the consecutive whitespace into a single space, so that the segment does not contain ragged spacing.
List<char> collapsedChars = [];
bool previousWasWhitespace = false;
bool wasPreviousWhitespace = false;
foreach (char character in sanitizedChars)
{
if (char.IsWhiteSpace(character))
{
if (!previousWasWhitespace)
if (!wasPreviousWhitespace)
collapsedChars.Add(' ');
previousWasWhitespace = true;
wasPreviousWhitespace = true;
}
else
{
collapsedChars.Add(character);
previousWasWhitespace = false;
wasPreviousWhitespace = false;
}
}
string sanitized = new string([.. collapsedChars]).Trim();
if (string.Equals(sanitized, ".", StringComparison.Ordinal) || string.Equals(sanitized, "..", StringComparison.Ordinal))
return Errors.FileSystemManagement.InvalidPath;
// a segment must never contain a path separator, otherwise the segment could escape its directory or nest additional directories
// A segment must never contain a path separator, otherwise the segment could escape its directory or nest additional directories.
if (sanitized.Contains('/') || sanitized.Contains('\\'))
return Errors.FileSystemManagement.InvalidPath;
if (sanitized.Length > MAX_DIRECTORY_SEGMENT_LENGTH)
@@ -171,4 +171,21 @@ public class PathService : IPathService
return newPathResult.Errors;
return _platformContext.PathStrategy.GetPathRoot(newPathResult.Value);
}
/// <summary>
/// Checks whether <paramref name="path"/> is located inside <paramref name="parentPath"/>.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="parentPath">The path that must contain the checked path.</param>
/// <returns><see langword="true"/> if the path is inside the parent path, <see langword="false"/> otherwise.</returns>
public bool IsPathWithin(string path, string parentPath)
{
Result<FileSystemPathId> newPathResult = FileSystemPathId.Create(path);
if (newPathResult.IsFailure)
return false;
Result<FileSystemPathId> parentPathResult = FileSystemPathId.Create(parentPath);
if (parentPathResult.IsFailure)
return false;
return _platformContext.PathStrategy.IsPathWithin(newPathResult.Value, parentPathResult.Value);
}
}
@@ -24,9 +24,9 @@ public interface IPathStrategy
/// 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>
/// <param name="shouldIncludeHiddenElements">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);
bool Exists(FileSystemPathId path, bool shouldIncludeHiddenElements = true);
/// <summary>
/// Tries to combine <paramref name="path"/> with <paramref name="name"/>.
@@ -68,4 +68,12 @@ public interface IPathStrategy
/// <param name="path">The path for which to get the root.</param>
/// <returns>An <see cref="Result{TValue}"/> containing the root of <paramref name="path"/>, or an error.</returns>
Result<PathSegment> GetPathRoot(FileSystemPathId path);
/// <summary>
/// Checks whether <paramref name="path"/> is located inside <paramref name="parentPath"/>.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="parentPath">The path that must contain the checked path.</param>
/// <returns><see langword="true"/> if the path is inside the parent path, <see langword="false"/> otherwise.</returns>
bool IsPathWithin(FileSystemPathId path, FileSystemPathId parentPath);
}
@@ -37,11 +37,11 @@ public class UnixPathStrategy : IUnixPathStrategy
/// <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
// Check for invalid path characters.
char[] invalidChars = GetInvalidPathCharsForPlatform();
if (path.Path.IndexOfAny(invalidChars) >= 0)
return false;
// check for relative paths
// Check for relative paths.
if (path.Path.StartsWith("./") || path.Path.StartsWith("../"))
return false;
const string PATH_PATTERN = @"^\/([\w\-\.\~!$&'()*+,;=:@\[\] ]+(\/[\w\-\.\~!$&'()*+,;=:@\[\] ]+)*)?\/?$";
@@ -52,9 +52,9 @@ public class UnixPathStrategy : IUnixPathStrategy
/// 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>
/// <param name="shouldIncludeHiddenElements">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)
public bool Exists(FileSystemPathId path, bool shouldIncludeHiddenElements = true)
{
if (!_fileSystem.Path.Exists(path.Path))
return false;
@@ -69,9 +69,9 @@ public class UnixPathStrategy : IUnixPathStrategy
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)
else // The path exists but is neither a file nor a directory (drive, etc.).
return true;
return includeHiddenElements || !isHidden;
return shouldIncludeHiddenElements || !isHidden;
}
/// <summary>
@@ -84,11 +84,11 @@ public class UnixPathStrategy : IUnixPathStrategy
{
if (string.IsNullOrWhiteSpace(name))
return Errors.FileSystemManagement.NameCannotBeEmpty;
// trim any directory separator characters from the end of the path
// 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
// If the name begins with a directory separator, remove it.
name = name.TrimStart(PathSeparator);
// combine the two parts with the Unix directory separator character
// Combine the two parts with the Unix directory separator character.
return FileSystemPathId.Create(subpath + PathSeparator + name + PathSeparator);
}
@@ -99,20 +99,20 @@ public class UnixPathStrategy : IUnixPathStrategy
/// <returns>An <see cref="Result{TValue}"/> containing the path segments, or an error.</returns>
public Result<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path)
{
// if path starts with anything other than '/', it's considered relative and invalid for this parser
// If the path starts with anything other than '/', it is considered relative and invalid for this parser.
if (!path.Path.StartsWith(PathSeparator))
return Errors.FileSystemManagement.InvalidPath;
// get the path segments
// Get the path segments.
List<string> splitSegments = [.. path.Path.Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries)];
IEnumerable<Result<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 '/'
isDirectory = index != splitSegments.Count - 1 || path.Path.EndsWith(PathSeparator); // Check if it is 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"
}).Prepend(PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true)); // UNIX paths have '/' as their "root drive".
foreach (Result<PathSegment> segment in segmentsResults)
if (segment.IsFailure)
return segment.Errors;
@@ -126,19 +126,19 @@ public class UnixPathStrategy : IUnixPathStrategy
/// <returns>An <see cref="Result{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
public Result<IEnumerable<PathSegment>> GoUpOneLevel(FileSystemPathId path)
{
// validation: ensure the path is not null or empty
// Validation: ensure the path is not null or empty.
if (!IsValidPath(path))
return Errors.FileSystemManagement.InvalidPath;
// trim trailing slash for consistent processing
// Trim the trailing slash for consistent processing.
string tempPath = path.Path;
if (tempPath.EndsWith('/'))
tempPath = tempPath.TrimEnd(PathSeparator);
// find the last occurrence of a slash
// 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 no slash is found (which should not happen after the previous steps), or if we are at the root level after trimming, return an 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
// Return the path up to the last slash, or, if there is only the root slash, return that one instead.
Result<FileSystemPathId> newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]);
if (newPathResult.IsFailure)
return newPathResult.Errors;
@@ -148,7 +148,7 @@ public class UnixPathStrategy : IUnixPathStrategy
/// <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>
/// <returns>A collection of characters that are invalid in the context of paths.</returns>
public char[] GetInvalidPathCharsForPlatform()
{
return ['\0'];
@@ -173,9 +173,52 @@ public class UnixPathStrategy : IUnixPathStrategy
if (!IsValidPath(path))
return Errors.FileSystemManagement.InvalidPath;
// On Unix-like systems, the root is always "/"
// 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;
}
/// <summary>
/// Checks whether <paramref name="path"/> is located inside <paramref name="parentPath"/>. The comparison resolves the "." and ".."
/// segments first, so that a path can never escape its parent through relative segments, and it is case-sensitive, because
/// Unix paths are case-sensitive.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="parentPath">The path that must contain the checked path.</param>
/// <returns><see langword="true"/> if the path is inside the parent path, <see langword="false"/> otherwise.</returns>
public bool IsPathWithin(FileSystemPathId path, FileSystemPathId parentPath)
{
string[] pathSegments = NormalizePathSegments(path.Path);
string[] parentPathSegments = NormalizePathSegments(parentPath.Path);
if (parentPathSegments.Length == 0 || pathSegments.Length <= parentPathSegments.Length)
return false;
for (int index = 0; index < parentPathSegments.Length; index++)
if (!string.Equals(pathSegments[index], parentPathSegments[index], StringComparison.Ordinal))
return false;
return true;
}
/// <summary>
/// Splits <paramref name="path"/> into its segments, resolving the "." (current directory) and ".." (parent directory) segments.
/// </summary>
/// <param name="path">The path to be normalized.</param>
/// <returns>The normalized path segments of the path.</returns>
private string[] NormalizePathSegments(string path)
{
List<string> segments = [];
foreach (string segment in path.Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries))
{
if (segment == ".")
continue;
if (segment == "..")
{
if (segments.Count > 0)
segments.RemoveAt(segments.Count - 1);
continue;
}
segments.Add(segment);
}
return [.. segments];
}
}
@@ -37,12 +37,12 @@ public class WindowsPathStrategy : IWindowsPathStrategy
/// <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
// 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)
// 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);
}
@@ -51,9 +51,9 @@ public class WindowsPathStrategy : IWindowsPathStrategy
/// 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>
/// <param name="shouldIncludeHiddenElements">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)
public bool Exists(FileSystemPathId path, bool shouldIncludeHiddenElements = true)
{
if (!_fileSystem.Path.Exists(path.Path))
return false;
@@ -68,9 +68,9 @@ public class WindowsPathStrategy : IWindowsPathStrategy
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)
else // The path exists but is neither a file nor a directory (drive, etc.).
return true;
return includeHiddenElements || !isHidden;
return shouldIncludeHiddenElements || !isHidden;
}
/// <summary>
@@ -81,13 +81,13 @@ public class WindowsPathStrategy : IWindowsPathStrategy
/// <returns>An <see cref="Result{TValue}"/> containing the combined path, or an error.</returns>
public Result<FileSystemPathId> CombinePath(FileSystemPathId path, string name)
{
if (name == null)
if (string.IsNullOrWhiteSpace(name))
return Errors.FileSystemManagement.NameCannotBeEmpty;
// trim any directory separator characters from the end of the path
// 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
// If the name begins with a directory separator, remove it.
name = name.TrimStart(PathSeparator);
// combine the two parts with the Windows directory separator character
// Combine the two parts with the Windows directory separator character.
return FileSystemPathId.Create(subpath + PathSeparator + name + PathSeparator);
}
@@ -98,7 +98,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy
/// <returns>An <see cref="Result{TValue}"/> containing the path segments, or an error.</returns>
public Result<IEnumerable<PathSegment>> ParsePath(FileSystemPathId path)
{
// Windows paths usually start with a drive letter and colon, e.g., "C:", or "\\" (UNC paths)
// Windows paths usually start with a drive letter and colon (e.g., "C:") or with "\\" (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<Result<PathSegment>> getPathSegmentsResults = GetPathSegments();
@@ -110,25 +110,25 @@ public class WindowsPathStrategy : IWindowsPathStrategy
{
if (path.Path.StartsWith(@"\\"))
{
// handle UNC path
// Handle a UNC path.
yield return PathSegment.Create(@"\\", isDirectory: false, isDrive: true);
string[] segments = path.Path[2..].Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < segments.Length; i++)
yield return CreatePathSegment(segments[i], i, segments.Length);
}
else // handle regular Windows path
else // Handle a regular Windows path.
{
// the drive segment
// The drive segment.
yield return PathSegment.Create(path.Path[..2], isDirectory: false, isDrive: true);
// extract the other segments
// Extract the other segments.
string[] segments = path.Path[3..].Split([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
isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // Check if it is the last segment, or if the next segment also contains a path delimiter.
else
isDirectory = true;
yield return PathSegment.Create(segment, isDirectory, isDrive: false);
@@ -151,29 +151,29 @@ public class WindowsPathStrategy : IWindowsPathStrategy
/// <returns>An <see cref="Result{TValue}"/> containing the path segments of the path up one level from <paramref name="path"/>, or an error.</returns>
public Result<IEnumerable<PathSegment>> GoUpOneLevel(FileSystemPathId path)
{
// validation: ensure the path is not null or empty
// Validation: ensure the path is not null or empty.
if (!IsValidPath(path))
return Errors.FileSystemManagement.InvalidPath;
// trim trailing backslash for consistent processing
// Trim the trailing backslash for consistent processing.
string tempPath = path.Path.TrimEnd(PathSeparator);
// check for UNC path
// Check for a 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 it is 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)
} // Check for the drive root, both with and without a 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
// 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 no backslash is found or it is 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
// Return the path up to the last backslash.
Result<FileSystemPathId> newPathResult = FileSystemPathId.Create(tempPath[..lastIndex]);
if (newPathResult.IsFailure)
return newPathResult.Errors;
@@ -184,7 +184,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy
/// <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>
/// <returns>A collection of characters that are invalid in the context of paths.</returns>
public char[] GetInvalidPathCharsForPlatform()
{
return ['<', '>', '"', '/', '|', '?', '*'];
@@ -208,28 +208,71 @@ public class WindowsPathStrategy : IWindowsPathStrategy
{
if (!IsValidPath(path))
return Errors.FileSystemManagement.InvalidPath;
// handle UNC paths (e.g., \\server\share\folder)
// Handle UNC paths (e.g., \\server\share\folder).
if (path.Path.StartsWith(@"\\"))
{
// find the position of the second backslash (after \\server)
// 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)
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\)
thirdBackslash = path.Path.Length; // No third backslash, use the 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
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:).
// The path must be at least 2 characters long.
// The first character must be a letter.
// The second character must 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 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;
}
/// <summary>
/// Checks whether <paramref name="path"/> is located inside <paramref name="parentPath"/>. The comparison resolves the "." and ".."
/// segments first, so that a path can never escape its parent through relative segments, and it is case-insensitive, because
/// Windows paths are case-insensitive.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="parentPath">The path that must contain the checked path.</param>
/// <returns><see langword="true"/> if the path is inside the parent path, <see langword="false"/> otherwise.</returns>
public bool IsPathWithin(FileSystemPathId path, FileSystemPathId parentPath)
{
string[] pathSegments = NormalizePathSegments(path.Path);
string[] parentPathSegments = NormalizePathSegments(parentPath.Path);
if (parentPathSegments.Length == 0 || pathSegments.Length <= parentPathSegments.Length)
return false;
for (int index = 0; index < parentPathSegments.Length; index++)
if (!string.Equals(pathSegments[index], parentPathSegments[index], StringComparison.OrdinalIgnoreCase))
return false;
return true;
}
/// <summary>
/// Splits <paramref name="path"/> into its segments, resolving the "." (current directory) and ".." (parent directory) segments.
/// </summary>
/// <param name="path">The path to be normalized.</param>
/// <returns>The normalized path segments of the path.</returns>
private string[] NormalizePathSegments(string path)
{
List<string> segments = [];
foreach (string segment in path.Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries))
{
if (segment == ".")
continue;
if (segment == "..")
{
if (segments.Count > 0)
segments.RemoveAt(segments.Count - 1);
continue;
}
segments.Add(segment);
}
return [.. segments];
}
}
@@ -29,7 +29,6 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
private readonly FileSystemStructureFixture _fileSystemStructureFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
@@ -54,18 +53,18 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
}
[SkipWhenHiddenAttributeNotSupportedFact]
public async Task GetDirectories_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoDirectories()
public async Task GetDirectories_WhenCalledWithValidPathAndHiddenChildrenAndNotShouldIncludeHiddenElements_ShouldReturnNoDirectories()
{
// Arrange
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = false;
bool shouldIncludeHiddenElements = false;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
string content = await response.Content.ReadAsStringAsync();
@@ -84,18 +83,18 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
}
[Fact]
public async Task GetDirectories_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnDirectoriesWithHiddenElements()
public async Task GetDirectories_WhenCalledWithValidPathAndWithShouldIncludeHiddenElements_ShouldReturnDirectoriesWithHiddenElements()
{
// Arrange
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
@@ -127,10 +126,10 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
@@ -153,10 +152,10 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
// Arrange
string emptyPath = "";
string encodedPath = Uri.EscapeDataString(emptyPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
@@ -184,12 +183,12 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token)
await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token)
);
Assert.Null(exception);
}
@@ -200,14 +199,14 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
using CancellationTokenSource cts = new();
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
{
cts.Cancel();
await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token);
});
}
@@ -29,7 +29,6 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
private readonly FileSystemStructureFixture _fileSystemStructureFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
@@ -54,16 +53,16 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
}
[SkipWhenHiddenAttributeNotSupportedFact]
public async Task GetFiles_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnFilesWithoutHiddenElements()
public async Task GetFiles_WhenCalledWithValidPathAndNotShouldIncludeHiddenElements_ShouldReturnFilesWithoutHiddenElements()
{
// Arrange
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
bool includeHiddenElements = false;
bool shouldIncludeHiddenElements = false;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
@@ -90,17 +89,17 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
}
[SkipWhenHiddenAttributeNotSupportedFact]
public async Task GetFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoFiles()
public async Task GetFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotShouldIncludeHiddenElements_ShouldReturnNoFiles()
{
// Arrange
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
bool includeHiddenElements = false;
bool shouldIncludeHiddenElements = false;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
@@ -121,17 +120,17 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
}
[Fact]
public async Task GetFiles_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnFilesWithHiddenElements()
public async Task GetFiles_WhenCalledWithValidPathAndWithShouldIncludeHiddenElements_ShouldReturnFilesWithHiddenElements()
{
// Arrange
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
@@ -166,10 +165,10 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
@@ -192,10 +191,10 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Arrange
string emptyPath = "";
string encodedPath = Uri.EscapeDataString(emptyPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
@@ -223,12 +222,12 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token)
await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token)
);
Assert.Null(exception);
}
@@ -239,14 +238,14 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
using CancellationTokenSource cts = new();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token);
});
Assert.IsType<TaskCanceledException>(exception);
}
@@ -29,7 +29,6 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
private readonly FileSystemStructureFixture _fileSystemStructureFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
@@ -54,16 +53,16 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
}
[SkipWhenHiddenAttributeNotSupportedFact]
public async Task GetTreeFiles_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnTreeFilesWithoutHiddenElements()
public async Task GetTreeFiles_WhenCalledWithValidPathAndNotShouldIncludeHiddenElements_ShouldReturnTreeFilesWithoutHiddenElements()
{
// Arrange
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
bool includeHiddenElements = false;
bool shouldIncludeHiddenElements = false;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
@@ -90,17 +89,17 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
}
[SkipWhenHiddenAttributeNotSupportedFact]
public async Task GetTreeFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoTreeFiles()
public async Task GetTreeFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotShouldIncludeHiddenElements_ShouldReturnNoTreeFiles()
{
// Arrange
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
bool includeHiddenElements = false;
bool shouldIncludeHiddenElements = false;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
@@ -122,17 +121,17 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
}
[Fact]
public async Task GetTreeFiles_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnTreeFilesWithHiddenElements()
public async Task GetTreeFiles_WhenCalledWithValidPathAndWithShouldIncludeHiddenElements_ShouldReturnTreeFilesWithHiddenElements()
{
// Arrange
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={Uri.EscapeDataString(testPath)}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
@@ -166,10 +165,10 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
@@ -192,10 +191,10 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
// Arrange
string emptyPath = "";
string encodedPath = Uri.EscapeDataString(emptyPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
@@ -223,12 +222,12 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token)
await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token)
);
Assert.Null(exception);
}
@@ -239,14 +238,14 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
bool shouldIncludeHiddenElements = true;
using CancellationTokenSource cts = new();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&shouldIncludeHiddenElements={shouldIncludeHiddenElements}", cts.Token);
});
Assert.IsType<TaskCanceledException>(exception);
}
@@ -25,7 +25,6 @@ public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApi
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
@@ -55,7 +54,7 @@ public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApi
string tempPath = System.IO.Path.GetTempPath();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(tempPath)}&includeHiddenElements=false");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(tempPath)}&shouldIncludeHiddenElements=false");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@@ -72,7 +71,7 @@ public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApi
string nonExistingPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(nonExistingPath)}&includeHiddenElements=false");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(nonExistingPath)}&shouldIncludeHiddenElements=false");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@@ -89,7 +88,7 @@ public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApi
string path = "";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=false");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=false");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
@@ -117,7 +116,7 @@ public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApi
string invalidPath = "invalid:path";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(invalidPath)}&includeHiddenElements=false");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(invalidPath)}&shouldIncludeHiddenElements=false");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@@ -139,7 +138,7 @@ public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApi
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.GetAsync($"/api/v1/path/check-path-exists?path={encodedPath}&includeHiddenElements=false", cts.Token);
await _client.GetAsync($"/api/v1/path/check-path-exists?path={encodedPath}&shouldIncludeHiddenElements=false", cts.Token);
});
Assert.IsType<TaskCanceledException>(exception);
}
@@ -76,11 +76,11 @@ public class GetDirectoriesQueryValidatorTests
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
public void Validate_WhenShouldIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
query = query with { IncludeHiddenElements = true };
query = query with { ShouldIncludeHiddenElements = true };
// Act
List<Error> result = _validator.TestValidate(query);
@@ -90,11 +90,11 @@ public class GetDirectoriesQueryValidatorTests
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
public void Validate_WhenShouldIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
query = query with { IncludeHiddenElements = false };
query = query with { ShouldIncludeHiddenElements = false };
// Act
List<Error> result = _validator.TestValidate(query);
@@ -76,11 +76,11 @@ public class GetFilesQueryValidatorTests
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
public void Validate_WhenShouldIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetFilesQuery query = _getFilesQueryFixture.Create();
query = query with { IncludeHiddenElements = true };
query = query with { ShouldIncludeHiddenElements = true };
// Act
List<Error> result = _validator.TestValidate(query);
@@ -90,11 +90,11 @@ public class GetFilesQueryValidatorTests
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
public void Validate_WhenShouldIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetFilesQuery query = _getFilesQueryFixture.Create();
query = query with { IncludeHiddenElements = false };
query = query with { ShouldIncludeHiddenElements = false };
// Act
List<Error> result = _validator.TestValidate(query);
@@ -76,11 +76,11 @@ public class GetTreeFilesQueryValidatorTests
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
public void Validate_WhenShouldIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
query = query with { IncludeHiddenElements = true };
query = query with { ShouldIncludeHiddenElements = true };
// Act
List<Error> result = _validator.TestValidate(query);
@@ -90,11 +90,11 @@ public class GetTreeFilesQueryValidatorTests
}
[Fact]
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
public void Validate_WhenShouldIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
query = query with { IncludeHiddenElements = false };
query = query with { ShouldIncludeHiddenElements = false };
// Act
List<Error> result = _validator.TestValidate(query);
@@ -52,10 +52,10 @@ public class CheckPathExistsQueryHandlerTests
}
[Fact]
public async Task HandleAsync_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrueResponse()
public async Task HandleAsync_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsTrue_ShouldReturnTrueResponse()
{
// Arrange
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(includeHiddenElements: true);
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(shouldIncludeHiddenElements: true);
_mockPathService.Exists(query.Path!).Returns(true);
// Act
@@ -68,10 +68,10 @@ public class CheckPathExistsQueryHandlerTests
}
[Fact]
public async Task HandleAsync_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalseResponse()
public async Task HandleAsync_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsFalse_ShouldReturnFalseResponse()
{
// Arrange
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(includeHiddenElements: false);
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(shouldIncludeHiddenElements: false);
_mockPathService.Exists(query.Path!, false).Returns(false);
// Act
@@ -105,7 +105,7 @@ public class DirectoryProviderServiceTests
}
[Fact]
public void GetSubdirectoryPaths_WhenIncludeHiddenElementsIsFalse_ShouldExcludeHiddenDirectories()
public void GetSubdirectoryPaths_WhenShouldIncludeHiddenElementsIsFalse_ShouldExcludeHiddenDirectories()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.Create();
@@ -126,7 +126,7 @@ public class DirectoryProviderServiceTests
}
[Fact]
public void GetSubdirectoryPaths_WhenIncludeHiddenElementsIsTrue_ShouldIncludeHiddenDirectories()
public void GetSubdirectoryPaths_WhenShouldIncludeHiddenElementsIsTrue_ShouldIncludeHiddenDirectories()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.Create();
@@ -89,7 +89,7 @@ public class FileProviderServiceTests
}
[Fact]
public void GetFilePaths_WhenIncludeHiddenElementsIsFalse_ShouldExcludeHiddenFiles()
public void GetFilePaths_WhenShouldIncludeHiddenElementsIsFalse_ShouldExcludeHiddenFiles()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.Create();
@@ -109,7 +109,7 @@ public class FileProviderServiceTests
}
[Fact]
public void GetFilePaths_WhenIncludeHiddenElementsIsTrue_ShouldIncludeHiddenFiles()
public void GetFilePaths_WhenShouldIncludeHiddenElementsIsTrue_ShouldIncludeHiddenFiles()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.Create();
@@ -131,7 +131,7 @@ public class PathServiceTests
}
[Fact]
public void Exists_WhenPathIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrue()
public void Exists_WhenPathIsHiddenAndShouldIncludeHiddenElementsIsTrue_ShouldReturnTrue()
{
// Arrange
string existingPath = @"C:\ExistingPath";
@@ -147,7 +147,7 @@ public class PathServiceTests
}
[Fact]
public void Exists_WhenPathIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalse()
public void Exists_WhenPathIsHiddenAndShouldIncludeHiddenElementsIsFalse_ShouldReturnFalse()
{
// Arrange
string existingPath = @"C:\ExistingPath";
@@ -771,4 +771,50 @@ public class PathServiceTests
Assert.False(result.IsFailure);
Assert.Equal(100, result.Value.Name.Length);
}
[Fact]
public void IsPathWithin_WhenBothPathsAreValid_ShouldCreatePathIdsAndDelegateToTheStrategy()
{
// Arrange
string path = @"C:\Media\Books\book.epub";
string parentPath = @"C:\Media\Books";
_mockPathStrategy.IsPathWithin(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>()).Returns(true);
// Act
bool result = _sut.IsPathWithin(path, parentPath);
// Assert
Assert.True(result);
_mockPathStrategy.Received(1).IsPathWithin(
Arg.Is<FileSystemPathId>(pathId => pathId.Path == path),
Arg.Is<FileSystemPathId>(pathId => pathId.Path == parentPath));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void IsPathWithin_WhenPathIsNotValid_ShouldReturnFalseWithoutCallingTheStrategy(string? invalidPath)
{
// Act
bool result = _sut.IsPathWithin(invalidPath!, @"C:\Media");
// Assert
Assert.False(result);
_mockPathStrategy.DidNotReceive().IsPathWithin(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>());
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void IsPathWithin_WhenParentPathIsNotValid_ShouldReturnFalseWithoutCallingTheStrategy(string? invalidParentPath)
{
// Act
bool result = _sut.IsPathWithin(@"C:\Media\Books\book.epub", invalidParentPath!);
// Assert
Assert.False(result);
_mockPathStrategy.DidNotReceive().IsPathWithin(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>());
}
}
@@ -120,7 +120,7 @@ public class UnixPathStrategyTests
}
[Fact]
public void Exists_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrue()
public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsTrue_ShouldReturnTrue()
{
// Arrange
string existingPath = "/home/user/existing_file.txt";
@@ -138,7 +138,7 @@ public class UnixPathStrategyTests
}
[Fact]
public void Exists_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalse()
public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsFalse_ShouldReturnFalse()
{
// Arrange
string existingPath = "/home/user/existing_file.txt";
@@ -596,4 +596,42 @@ public class UnixPathStrategyTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
}
[Theory]
[InlineData("/media/books", "/media/books/book.epub")] // direct child
[InlineData("/media", "/media/books/book.epub")] // nested descendant
[InlineData("/media/books/", "/media/books/book.epub")] // trailing separator on the parent
[InlineData("/media/books", "/media/books/sub/../book.epub")] // relative segments that stay inside
public void IsPathWithin_WithContainedPaths_ShouldReturnTrue(string parentPath, string path)
{
// Arrange
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath);
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
// Act
bool result = _sut.IsPathWithin(pathId, parentPathId);
// Assert
Assert.True(result);
}
[Theory]
[InlineData("/media/books", "/media/book.epub")] // sibling directory
[InlineData("/media/books", "/Media/Books/book.epub")] // Unix paths are case-sensitive
[InlineData("/media/books", "/media/other/book.epub")] // sibling directory
[InlineData("/media/books", "/media/books/../other/book.epub")] // relative segment that escapes the parent
[InlineData("/media/books", "/etc/passwd")] // unrelated location
[InlineData("/media", "/media")] // the parent itself is not inside itself
public void IsPathWithin_WithPathsOutsideTheParent_ShouldReturnFalse(string parentPath, string path)
{
// Arrange
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath);
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
// Act
bool result = _sut.IsPathWithin(pathId, parentPathId);
// Assert
Assert.False(result);
}
}
@@ -148,7 +148,7 @@ public class WindowsPathStrategyTests
}
[Fact]
public void Exists_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrue()
public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsTrue_ShouldReturnTrue()
{
// Arrange
string existingPath = @"C:\Users\User\existing_file.txt";
@@ -165,7 +165,7 @@ public class WindowsPathStrategyTests
}
[Fact]
public void Exists_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalse()
public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsFalse_ShouldReturnFalse()
{
// Arrange
string existingPath = @"C:\Users\User\existing_file.txt";
@@ -811,4 +811,44 @@ public class WindowsPathStrategyTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
}
[Theory]
[InlineData(@"C:\Media\Books", @"C:\Media\Books\book.epub")] // direct child
[InlineData(@"C:\Media", @"C:\Media\Books\book.epub")] // nested descendant
[InlineData(@"C:\Media\Books\", @"C:\Media\Books\book.epub")] // trailing separator on the parent
[InlineData(@"C:\Media\Books", @"c:\media\books\book.epub")] // Windows paths are case-insensitive
[InlineData(@"C:\Media\Books", @"C:\Media\Books\Sub\..\book.epub")] // relative segments that stay inside
public void IsPathWithin_WithContainedPaths_ShouldReturnTrue(string parentPath, string path)
{
// Arrange
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath);
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
// Act
bool result = _sut.IsPathWithin(pathId, parentPathId);
// Assert
Assert.True(result);
}
[Theory]
[InlineData(@"C:\Media\Books", @"C:\Media\book.epub")] // sibling directory
[InlineData(@"C:\Media\Books", @"D:\Media\Books\book.epub")] // different drive
[InlineData(@"C:\Media\Books", @"C:\Media\BookShelf\book.epub")] // a sibling whose name shares the prefix
[InlineData(@"C:\Media\Books", @"C:\Media\Other\book.epub")] // sibling directory
[InlineData(@"C:\Media\Books", @"C:\Media\Books\..\Other\book.epub")] // relative segment that escapes the parent
[InlineData(@"C:\Media\Books", @"C:\Windows\System32\config\SAM")] // unrelated location
[InlineData(@"C:\Media", @"C:\Media")] // the parent itself is not inside itself
public void IsPathWithin_WithPathsOutsideTheParent_ShouldReturnFalse(string parentPath, string path)
{
// Arrange
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath);
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
// Act
bool result = _sut.IsPathWithin(pathId, parentPathId);
// Assert
Assert.False(result);
}
}
@@ -60,7 +60,7 @@ public class GetDirectoriesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create();
@@ -86,7 +86,7 @@ public class GetDirectoriesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create();
@@ -112,7 +112,7 @@ public class GetDirectoriesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoriesQueryToHandler()
public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoriesQueryToSender()
{
// Arrange
GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create();
@@ -125,7 +125,7 @@ public class GetDirectoriesEndpointTests
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetDirectoriesQuery>(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements),
Arg.Is<GetDirectoriesQuery>(q => q.Path == request.Path && q.ShouldIncludeHiddenElements == request.ShouldIncludeHiddenElements),
Arg.Is(cancellationToken));
}
@@ -60,7 +60,7 @@ public class GetFilesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
GetFilesRequest request = _getFilesRequestFixture.Create();
@@ -86,7 +86,7 @@ public class GetFilesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
GetFilesRequest request = _getFilesRequestFixture.Create();
@@ -126,7 +126,7 @@ public class GetFilesEndpointTests
// Assert
await _mockHandler.Received(1).HandleAsync(Arg.Is<GetFilesQuery>(q =>
q.Path == request.Path &&
q.IncludeHiddenElements == request.IncludeHiddenElements),
q.ShouldIncludeHiddenElements == request.ShouldIncludeHiddenElements),
Arg.Is(cancellationToken));
}
@@ -60,7 +60,7 @@ public class GetTreeFilesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
GetTreeFilesRequest request = _getTreeFilesRequestFixture.Create();
@@ -86,7 +86,7 @@ public class GetTreeFilesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
GetTreeFilesRequest request = _getTreeFilesRequestFixture.Create();
@@ -126,7 +126,7 @@ public class GetTreeFilesEndpointTests
// Assert
await _mockHandler.Received(1).HandleAsync(Arg.Is<GetTreeFilesQuery>(q =>
q.Path == request.Path &&
q.IncludeHiddenElements == request.IncludeHiddenElements),
q.ShouldIncludeHiddenElements == request.ShouldIncludeHiddenElements),
Arg.Is(cancellationToken));
}
@@ -43,7 +43,7 @@ public class CheckPathExistsEndpointTests
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathExistsResponse()
{
// Arrange
CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true);
CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", shouldIncludeHiddenElements: true);
CancellationToken cancellationToken = CancellationToken.None;
PathExistsResponse expectedResponse = _pathExistsResponseFixture.Create(exists: true);
_mockHandler.HandleAsync(Arg.Any<CheckPathExistsQuery>(), Arg.Any<CancellationToken>())
@@ -58,10 +58,10 @@ public class CheckPathExistsEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendCheckPathExistsQueryToHandler()
public async Task ExecuteAsync_WhenCalled_ShouldSendCheckPathExistsQueryToSender()
{
// Arrange
CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true);
CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", shouldIncludeHiddenElements: true);
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<CheckPathExistsQuery>(), Arg.Any<CancellationToken>())
.Returns(_pathExistsResponseFixture.Create(exists: true));
@@ -71,7 +71,7 @@ public class CheckPathExistsEndpointTests
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<CheckPathExistsQuery>(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements),
Arg.Is<CheckPathExistsQuery>(q => q.Path == request.Path && q.ShouldIncludeHiddenElements == request.ShouldIncludeHiddenElements),
Arg.Is(cancellationToken));
}
@@ -79,7 +79,7 @@ public class CheckPathExistsEndpointTests
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true);
CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", shouldIncludeHiddenElements: true);
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();