diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs index 58f34768..5421e458 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs @@ -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; /// -/// 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. /// /// The type used as a result for the "get all" action. It should implement . public interface IGetAllRepositoryAction where TModel : IStorageEntity { /// - /// Gets all data of type from the storage medium. + /// Gets data of type from the storage medium. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching data is returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - Task>> GetAllAsync(CancellationToken cancellationToken); + /// An containing either a paginated result of type , or an error. + Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto; } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs index 69d82b5b..2a749c52 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; /// -/// 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. /// /// The type used as a result for the "get by id" action. It should implement . /// The type used for the identifier of the respository. It should not be . @@ -19,7 +19,9 @@ public interface IGetByIdRepositoryAction where TModel : IStorageEn /// Gets an element of type identified by from the storage medium. /// /// The id of the element to get. + /// Whether the navigation properties of the entity should be loaded together with the entity itself. Pass to retrieve only the data stored directly on the entity row. + /// Whether the retrieved entity should be tracked by the persistence medium, so that changes to it can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - Task> GetByIdAsync(TId id, CancellationToken cancellationToken); + Task> GetByIdAsync(TId id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default); } diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs index 26a77760..72d5d6ab 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs @@ -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 /// An representing either a successful operation, or an error. public async Task> 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 } /// - /// Gets all autorization permissions. + /// Gets all the authorization permissions, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching permissions are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(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 query = _luminaDbContext.Permissions; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + + // If no pagination was requested, return all the permissions. + if (paginationData is null) + { + IReadOnlyList allPermissions = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + 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 paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs index cbf17889..5cf0856d 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs @@ -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 /// An representing either a successful operation, or an error. public async Task> 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 } /// - /// Gets all autorization roles. + /// Gets all the authorization roles, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching roles are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(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 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 allRoles = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + 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 paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// @@ -76,13 +124,19 @@ internal sealed class RoleRepository : IRoleRepository /// The id of the authorization role to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> 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 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); } /// @@ -93,16 +147,18 @@ internal sealed class RoleRepository : IRoleRepository /// An representing either a successful operation, or an error. public async Task> 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 /// An representing either a successful operation, or an error. public async Task> 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; } diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs index 43b63d9e..f41c8eaf 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs @@ -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 /// An representing either a successful operation, or an error. public async Task> 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 /// The Id of the library to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> 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 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); } /// @@ -86,21 +96,65 @@ internal sealed class LibraryRepository : ILibraryRepository } /// - /// Gets all media libraries. + /// Gets all the media libraries, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching media libraries are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(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 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 allLibraries = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + 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 paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// - /// 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. /// - /// The media library to update. + /// The media library whose editable data is applied to the stored library. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. public async Task> 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; } diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs index 6e072148..093c8cee 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs @@ -39,9 +39,9 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository /// An representing either a successful operation, or an error. public async Task> 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 /// The id of the library scan to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> 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 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); } /// @@ -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; } diff --git a/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs index c71d54fd..7d3d7b4c 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs @@ -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 /// The Id of the plugin to get. /// Cancellation token that can be used to stop the execution. /// An containing either a , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> 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 query = _luminaDbContext.Plugins; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + return await query.FirstOrDefaultAsync(plugin => plugin.Id == id, cancellationToken).ConfigureAwait(false); } /// - /// Gets all the detected plugins. + /// Gets all the detected plugins, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching plugins are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(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 query = _luminaDbContext.Plugins; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + + // If no pagination was requested, return all the plugins. + if (paginationData is null) + { + IReadOnlyList allPlugins = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + 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 paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// @@ -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; diff --git a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs index 32f4fa45..db0c5fab 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs @@ -36,11 +36,14 @@ internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRe /// The id of the execution to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> 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 query = _luminaDbContext.ScheduledJobExecutions; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + return await query.FirstOrDefaultAsync(execution => execution.Id == id, cancellationToken).ConfigureAwait(false); } /// diff --git a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs index 899b05fb..c8139a84 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs @@ -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 /// The id of the scheduled job to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> 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 query = _luminaDbContext.ScheduledJobs; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + return await query.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == id, cancellationToken).ConfigureAwait(false); } /// @@ -59,14 +65,54 @@ internal sealed class ScheduledJobRepository : IScheduledJobRepository } /// - /// 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. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching scheduled jobs are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(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 query = _luminaDbContext.ScheduledJobs; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + + // If no pagination was requested, return all the scheduled jobs. + if (paginationData is null) + { + IReadOnlyList allScheduledJobs = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + 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 paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// diff --git a/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs index 330b06ce..bdbe711f 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs @@ -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 /// An representing either a successful operation, or an error. public async Task> 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 } /// - /// 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. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching themes are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(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 query = _luminaDbContext.Themes; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + + // If no pagination was requested, return all the themes. + if (paginationData is null) + { + IReadOnlyList allThemes = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + 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 paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs index 0414b5a9..2417fe17 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs @@ -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 /// An representing either a successful operation, or an error. public async Task> 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 } /// - /// Gets all users. + /// Gets all the users, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching users are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(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 query = _luminaDbContext.Users; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + + // If no pagination was requested, return all the users. + if (paginationData is null) + { + IReadOnlyList allUsers = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + 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 paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// @@ -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 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 /// The id of the user to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> 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 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); } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs index 03094365..cdd3fea1 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs @@ -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 /// An representing either a successful operation, or an error. public async Task> 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 /// The Id of the user settings to get. /// Cancellation token that can be used to stop the execution. /// An containing either the identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - return await _luminaDbContext.UserSettings - .FirstOrDefaultAsync(settings => settings.Id == id, cancellationToken) + IQueryable query = _luminaDbContext.UserSettings; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + return await query.FirstOrDefaultAsync(settings => settings.Id == id, cancellationToken) .ConfigureAwait(false); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs index bad71749..89190f99 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs @@ -37,15 +37,15 @@ internal class DirectoryProviderService : IDirectoryProviderService /// Retrieves a list of subdirectory paths from the specified path. /// /// The path from which to retrieve the subdirectory paths. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of directory paths or an error. - public Result> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements) + public Result> 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 /// An containing either the optional last write time of if available, or an error. public Result> 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.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path)); @@ -114,7 +114,7 @@ internal class DirectoryProviderService : IDirectoryProviderService /// An containing the optional creation time of if available, or an error. public Result> 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.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path)); @@ -128,10 +128,10 @@ internal class DirectoryProviderService : IDirectoryProviderService /// An containing either the path of a created directory, or an error. public Result 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 /// /// Identifier for the path where the directory to be copied is located. /// Identifier for the path where the directory will be copied. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either the copied directory, or an error. - public Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + public Result 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 newSourcePathResult = FileSystemPathId.Create(subDirInfo.FullName); @@ -171,8 +171,8 @@ internal class DirectoryProviderService : IDirectoryProviderService Result newDestinationPathResult = FileSystemPathId.Create(_fileSystem.Path.Combine(destPath, subDirInfo.Name)); if (newDestinationPathResult.IsFailure) return newDestinationPathResult.Errors; - // recursive call - Result copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, overrideExisting); + // Recursive call. + Result 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 /// /// Identifier for the path where the directory to be moved is located. /// Identifier for the path where the directory will be moved. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either a moved directory, or an error. - public Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + public Result 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 /// /// The source directory to be merged. /// The destination directory to be merged. - /// Whether to override existing files. - private void MergeDirectories(string sourceDir, string destDir, bool overwrite) + /// Whether to override existing files. + 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 /// An containing either the absolute path of the renamed directory, or an error. public Result 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 parentDirectory = Optional.FromNullable(_fileSystem.Directory.GetParent(path.Path)?.FullName); + if (parentDirectory.HasValue && !string.IsNullOrEmpty(parentDirectory.Value)) { - Result parendDirectoryResult = FileSystemPathId.Create(parentDirectory); + Result parendDirectoryResult = FileSystemPathId.Create(parentDirectory.Value); if (parendDirectoryResult.IsFailure) return parendDirectoryResult.Errors; - string? newDirectory = _fileSystem.Path.Combine(parentDirectory, name); - if (!string.IsNullOrEmpty(newDirectory)) + Optional newDirectory = Optional.FromNullable(_fileSystem.Path.Combine(parentDirectory.Value, name)); + if (newDirectory.HasValue && !string.IsNullOrEmpty(newDirectory.Value)) { - Result newDirectoryPathResult = FileSystemPathId.Create(newDirectory); + Result 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 /// An containing either the result of deleting a directory, or an error. public Result 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); diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs index f404edc1..54c925c4 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs @@ -36,48 +36,48 @@ public class DirectoryService : IDirectoryService /// Retrieves subdirectories for the specified string path. /// /// String representation of the file path. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - public Result> GetSubdirectories(string path, bool includeHiddenElements) + public Result> GetSubdirectories(string path, bool shouldIncludeHiddenElements) { Result fileSystemPathIdResult = FileSystemPathId.Create(path); if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; - return GetSubdirectories(fileSystemPathIdResult.Value, includeHiddenElements); + return GetSubdirectories(fileSystemPathIdResult.Value, shouldIncludeHiddenElements); } /// /// Retrieves subdirectories for the given directory. /// /// Directory object to retrieve subdirectories for. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - public Result> GetSubdirectories(Directory directory, bool includeHiddenElements) + public Result> GetSubdirectories(Directory directory, bool shouldIncludeHiddenElements) { - return GetSubdirectories(directory.Id, includeHiddenElements); + return GetSubdirectories(directory.Id, shouldIncludeHiddenElements); } /// /// Retrieves subdirectories for the specified file system path. /// /// Identifier for the file path. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - public Result> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements) + public Result> GetSubdirectories(FileSystemPathId path, bool shouldIncludeHiddenElements) { - // retrieve the list of subdirectories - Result> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, includeHiddenElements); + // Retrieve the list of subdirectories. + Result> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, shouldIncludeHiddenElements); if (subdirectoryPathsResult.IsFailure) return subdirectoryPathsResult.Errors; List result = []; foreach (FileSystemPathId subPath in subdirectoryPathsResult.Value) { - // extract directory details + // Extract directory details. Result dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(subPath); Result> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(subPath); Result> 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 errorDirResult = Directory.Create(subPath, !dirNameResult.IsFailure ? dirNameResult.Value : null!, @@ -123,7 +123,7 @@ public class DirectoryService : IDirectoryService /// An containing either the result of creating a directory, or an error. public Result 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 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 newDirectoryPathResult = _environmentContext.DirectoryProviderService.CreateDirectory(path, name); if (newDirectoryPathResult.IsFailure) return newDirectoryPathResult.Errors; Result dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value); Result> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value); Result> 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 errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsFailure ? dirNameResult.Value : null!, @@ -164,11 +164,11 @@ public class DirectoryService : IDirectoryService /// /// String representation of the path where the directory to be copied is located. /// String representation of the path where the directory will be copied. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either a copied directory, or an error. - public Result CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting) + public Result CopyDirectory(string sourcePath, string destinationPath, Optional 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 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); } /// @@ -187,9 +187,9 @@ public class DirectoryService : IDirectoryService /// /// Identifier for the path where the directory to be copied is located. /// Identifier for the path where the directory will be copied. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either the copied directory, or an error. - public Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + public Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting) { Result 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 newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, overrideExisting); + // Copy the directory. + Result newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, shouldOverrideExisting); throw new NotImplementedException(); } @@ -210,11 +210,11 @@ public class DirectoryService : IDirectoryService /// /// String representation of the path where the directory to be moved is located. /// String representation of the path where the directory will be moved. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either a moved directory, or an error. - public Result MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting) + public Result MoveDirectory(string sourcePath, string destinationPath, Optional 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 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); } /// @@ -233,9 +233,9 @@ public class DirectoryService : IDirectoryService /// /// Identifier for the path where the directory to be moved is located. /// Identifier for the path where the directory will be moved. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either the moved directory, or an error. - public Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + public Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting) { Result 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 newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, overrideExisting); + // Move the directory. + Result newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, shouldOverrideExisting); throw new NotImplementedException(); } @@ -273,7 +273,7 @@ public class DirectoryService : IDirectoryService /// An containing either the renamed directory, or an error. public Result 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 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 newDirectoryPathResult = _environmentContext.DirectoryProviderService.RenameDirectory(path, name); if (newDirectoryPathResult.IsFailure) return newDirectoryPathResult.Errors; Result dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value); Result> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value); Result> 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 errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsFailure ? dirNameResult.Value : null!, diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs index 452e3667..e52a47ca 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs @@ -36,15 +36,15 @@ internal class FileProviderService : IFileProviderService /// Retrieves a list of file paths at the specified path. /// /// The path for which to retrieve the list of files. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of file paths or an error. - public Result> GetFilePaths(FileSystemPathId path, bool includeHiddenElements) + public Result> 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 /// An containing either the contents of a file at the specified path, or an error. public Result 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 /// An containing either the optional last write time of if available, or an error. public Result> 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.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path)); @@ -123,7 +123,7 @@ internal class FileProviderService : IFileProviderService /// An containing either the optional creation time of if available, or an error. public Result> 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.FromNullable(_fileSystem.File.GetCreationTime(path.Path)); @@ -136,7 +136,7 @@ internal class FileProviderService : IFileProviderService /// An containing either the size of or an error. public Result 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 /// /// Identifier for the path where the file to be copied is located. /// Identifier for the path of the directory where the file will be copied. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either the copied file, or an error. - public Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + public Result 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 } /// - /// Creates a file path that is unique + /// Creates a file path that is unique. /// /// The path from which to generate the unique file path. /// A unique directory path. private string CreateUniqueFilePath(string destinationFilePath) { - string? directory = _fileSystem.Path.GetDirectoryName(destinationFilePath); - string? filename = _fileSystem.Path.GetFileNameWithoutExtension(destinationFilePath); - string? extension = _fileSystem.Path.GetExtension(destinationFilePath); + Optional directory = Optional.FromNullable(_fileSystem.Path.GetDirectoryName(destinationFilePath)); + Optional filename = Optional.FromNullable(_fileSystem.Path.GetFileNameWithoutExtension(destinationFilePath)); + Optional extension = Optional.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 /// /// Identifier for the path where the file to be moved is located. /// Identifier for the path of the directory where the file will be moved. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either a moved file, or an error. - public Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + public Result 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 /// An containing either the absolute path of the renamed file, or an error. public Result RenameFile(FileSystemPathId path, string name) { - string? parentDirectory = _fileSystem.FileInfo.New(path.Path)?.DirectoryName; - if (!string.IsNullOrEmpty(parentDirectory)) + Optional parentDirectory = Optional.FromNullable(_fileSystem.FileInfo.New(path.Path)?.DirectoryName); + if (parentDirectory.HasValue && !string.IsNullOrEmpty(parentDirectory.Value)) { - Result parendDirectoryResult = FileSystemPathId.Create(parentDirectory); + Result 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 newFile = Optional.FromNullable(_fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name)); + if (newFile.HasValue && !string.IsNullOrEmpty(newFile.Value)) { - Result newFilePathResult = FileSystemPathId.Create(newFile); + Result 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 /// An containing either the result of deleting a file, or an error. public Result 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); diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs index dc5de274..b4404c1c 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs @@ -35,50 +35,50 @@ public class FileService : IFileService /// Retrieves files for the specified string path. /// /// String representation of the file path. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - public Result> GetFiles(string path, bool includeHiddenElements) + public Result> GetFiles(string path, bool shouldIncludeHiddenElements) { Result fileSystemPathIdResult = FileSystemPathId.Create(path); if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; - return GetFiles(fileSystemPathIdResult.Value, includeHiddenElements); + return GetFiles(fileSystemPathIdResult.Value, shouldIncludeHiddenElements); } /// /// Retrieves files associated with a given file. /// /// The file object. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - public Result> GetFiles(File file, bool includeHiddenElements) + public Result> GetFiles(File file, bool shouldIncludeHiddenElements) { - return GetFiles(file.Id, includeHiddenElements); + return GetFiles(file.Id, shouldIncludeHiddenElements); } /// /// Retrieves files for a specified file path Id. /// /// Identifier for the file path. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - public Result> GetFiles(FileSystemPathId path, bool includeHiddenElements) + public Result> GetFiles(FileSystemPathId path, bool shouldIncludeHiddenElements) { - // retrieve the list of files - Result> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, includeHiddenElements); + // Retrieve the list of files. + Result> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, shouldIncludeHiddenElements); if (filePathsResult.IsFailure) return filePathsResult.Errors; List result = []; IEnumerable 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 fileNameResult = _environmentContext.FileProviderService.GetFileName(filePath); Result> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(filePath); Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(filePath); Result 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 errorFileResult = File.Create(filePath, !fileNameResult.IsFailure ? fileNameResult.Value : null!, @@ -107,13 +107,13 @@ public class FileService : IFileService /// /// String representation of the path where the file to be copied is located. /// String representation of the path of the directory where the file will be copied. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either a copied file, or an error. - public Result CopyFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) + public Result CopyFile(string sourceFilePath, string destinationDirectoryPath, Optional 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 fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); @@ -122,7 +122,7 @@ public class FileService : IFileService Result 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); } /// @@ -130,9 +130,9 @@ public class FileService : IFileService /// /// Identifier for the path where the file to be copied is located. /// Identifier for the path of the directory where the file will be copied. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either the copied file, or an error. - public Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + public Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting) { Result 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 copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, overrideExisting); + // Copy the file. + Result copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, shouldOverrideExisting); if (copyFileResult.IsFailure) return copyFileResult.Errors; Result fileNameResult = _environmentContext.FileProviderService.GetFileName(copyFileResult.Value); @@ -150,7 +150,7 @@ public class FileService : IFileService Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(copyFileResult.Value); Result 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 errorFileResult = File.Create(copyFileResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!, @@ -173,13 +173,13 @@ public class FileService : IFileService /// /// String representation of the path where the file to be moved is located. /// String representation of the path of the directory where the file will be moved. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either a moved file, or an error. - public Result MoveFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) + public Result MoveFile(string sourceFilePath, string destinationDirectoryPath, Optional 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 fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); @@ -188,7 +188,7 @@ public class FileService : IFileService Result 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); } /// @@ -196,9 +196,9 @@ public class FileService : IFileService /// /// Identifier for the path where the file to be moved is located. /// Identifier for the path of the directory where the file will be moved. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either the moved file, or an error. - public Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + public Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting) { Result 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 moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, overrideExisting); + // Move the file. + Result moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, shouldOverrideExisting); if (moveFileResult.IsFailure) return moveFileResult.Errors; Result fileNameResult = _environmentContext.FileProviderService.GetFileName(moveFileResult.Value); @@ -216,7 +216,7 @@ public class FileService : IFileService Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(moveFileResult.Value); Result 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 errorFileResult = File.Create(moveFileResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!, @@ -256,7 +256,7 @@ public class FileService : IFileService /// An containing either the renamed file, or an error. public Result 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 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 newFilePathResult = _environmentContext.FileProviderService.RenameFile(path, name); if (newFilePathResult.IsFailure) return newFilePathResult.Errors; @@ -276,7 +276,7 @@ public class FileService : IFileService Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(newFilePathResult.Value); Result 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 errorFileResult = File.Create(newFilePathResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!, diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs index 96afe5aa..f5ee7823 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs @@ -16,25 +16,25 @@ public interface IDirectoryService /// Retrieves subdirectories for the specified string path. /// /// String representation of the file path. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - Result> GetSubdirectories(string path, bool includeHiddenElements); + Result> GetSubdirectories(string path, bool shouldIncludeHiddenElements); /// /// Retrieves subdirectories for the given directory. /// /// Directory object to retrieve subdirectories for. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - Result> GetSubdirectories(Directory directory, bool includeHiddenElements); + Result> GetSubdirectories(Directory directory, bool shouldIncludeHiddenElements); /// /// Retrieves subdirectories for the specified file system path. /// /// Identifier for the file path. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - Result> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements); + Result> GetSubdirectories(FileSystemPathId path, bool shouldIncludeHiddenElements); /// /// Creates a directory with the specified , at the specified . @@ -49,18 +49,18 @@ public interface IDirectoryService /// /// String representation of the path where the directory to be copied is located. /// String representation of the path where the directory will be copied. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either a copied directory, or an error. - Result CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting); + Result CopyDirectory(string sourcePath, string destinationPath, Optional shouldOverrideExisting); /// /// Moves a directory located at to . /// /// String representation of the path where the directory to be moved is located. /// String representation of the path where the directory will be moved. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either a moved directory, or an error. - Result MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting); + Result MoveDirectory(string sourcePath, string destinationPath, Optional shouldOverrideExisting); /// /// Renames a directory with the specified , at the specified . diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs index ece87ff5..4cb7b412 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs @@ -16,43 +16,43 @@ public interface IFileService /// Retrieves files for the specified string path. /// /// String representation of the file path. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - Result> GetFiles(string path, bool includeHiddenElements); + Result> GetFiles(string path, bool shouldIncludeHiddenElements); /// /// Retrieves files associated with a given file. /// /// The file object. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - Result> GetFiles(File file, bool includeHiddenElements); + Result> GetFiles(File file, bool shouldIncludeHiddenElements); /// /// Retrieves files for a specified file path ID. /// /// Identifier for the file path. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - Result> GetFiles(FileSystemPathId path, bool includeHiddenElements); + Result> GetFiles(FileSystemPathId path, bool shouldIncludeHiddenElements); /// /// Copies a file located at to . /// /// String representation of the path where the file to be copied is located. /// String representation of the path where the file will be copied. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either a copied file, or an error. - Result CopyFile(string sourcePath, string destinationPath, bool? overrideExisting); + Result CopyFile(string sourcePath, string destinationPath, Optional shouldOverrideExisting); /// /// Moves a file located at to . /// /// String representation of the path where the file to be moved is located. /// String representation of the path where the file will be moved. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either a moved file, or an error. - Result MoveFile(string sourcePath, string destinationPath, bool? overrideExisting); + Result MoveFile(string sourcePath, string destinationPath, Optional shouldOverrideExisting); /// /// Renames a file with the specified , at the specified . diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs index 34a03dab..598e44de 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs @@ -27,9 +27,9 @@ public interface IPathService /// Checks if exists. /// /// The path to be checked. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// if exists, otherwise. - bool Exists(string path, bool includeHiddenElements = true); + bool Exists(string path, bool shouldIncludeHiddenElements = true); /// /// Tries to combine with . @@ -72,4 +72,12 @@ public interface IPathService /// The path for which to get the root. /// An containing the root of , or an error. Result GetPathRoot(string path); + + /// + /// Checks whether is located inside . + /// + /// The path to be checked. + /// The path that must contain the checked path. + /// if the path is inside the parent path, otherwise. + bool IsPathWithin(string path, string parentPath); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs index 02dadc41..18f0d79b 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs @@ -50,21 +50,21 @@ public class PathService : IPathService /// Checks if exists. /// /// The path to be checked. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// if exists, otherwise. - public bool Exists(string path, bool includeHiddenElements = true) + public bool Exists(string path, bool shouldIncludeHiddenElements = true) { Result newPathResult = FileSystemPathId.Create(path); if (newPathResult.IsFailure) return false; - return _platformContext.PathStrategy.Exists(newPathResult.Value, includeHiddenElements); + return _platformContext.PathStrategy.Exists(newPathResult.Value, shouldIncludeHiddenElements); } /// /// Tries to combine with . /// /// The path to be combined. - /// The name to be combined with the path. + /// The name to be combined with the path. /// An containing the combined path, or an error. public Result 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 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); } + + /// + /// Checks whether is located inside . + /// + /// The path to be checked. + /// The path that must contain the checked path. + /// if the path is inside the parent path, otherwise. + public bool IsPathWithin(string path, string parentPath) + { + Result newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsFailure) + return false; + Result parentPathResult = FileSystemPathId.Create(parentPath); + if (parentPathResult.IsFailure) + return false; + return _platformContext.PathStrategy.IsPathWithin(newPathResult.Value, parentPathResult.Value); + } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs index 2d36653b..ecc0e00a 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs @@ -24,9 +24,9 @@ public interface IPathStrategy /// Checks if exists. /// /// The path to be checked. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// if exists, otherwise. - bool Exists(FileSystemPathId path, bool includeHiddenElements = true); + bool Exists(FileSystemPathId path, bool shouldIncludeHiddenElements = true); /// /// Tries to combine with . @@ -68,4 +68,12 @@ public interface IPathStrategy /// The path for which to get the root. /// An containing the root of , or an error. Result GetPathRoot(FileSystemPathId path); + + /// + /// Checks whether is located inside . + /// + /// The path to be checked. + /// The path that must contain the checked path. + /// if the path is inside the parent path, otherwise. + bool IsPathWithin(FileSystemPathId path, FileSystemPathId parentPath); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs index 2b6039e5..0f2f6010 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs @@ -37,11 +37,11 @@ public class UnixPathStrategy : IUnixPathStrategy /// if is a valid path, otherwise. 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 exists. /// /// The path to be checked. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// if exists, otherwise. - 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; } /// @@ -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 /// An containing the path segments, or an error. public Result> 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 splitSegments = [.. path.Path.Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries)]; IEnumerable> 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 segment in segmentsResults) if (segment.IsFailure) return segment.Errors; @@ -126,19 +126,19 @@ public class UnixPathStrategy : IUnixPathStrategy /// An containing the path segments of the path up one level from , or an error. public Result> 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 newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]); if (newPathResult.IsFailure) return newPathResult.Errors; @@ -148,7 +148,7 @@ public class UnixPathStrategy : IUnixPathStrategy /// /// Returns a collection of characters that are invalid for paths. /// - /// A collection of characters that are invalid in the context of paths + /// A collection of characters that are invalid in the context of paths. 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; } + + /// + /// Checks whether is located inside . 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. + /// + /// The path to be checked. + /// The path that must contain the checked path. + /// if the path is inside the parent path, otherwise. + 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; + } + + /// + /// Splits into its segments, resolving the "." (current directory) and ".." (parent directory) segments. + /// + /// The path to be normalized. + /// The normalized path segments of the path. + private string[] NormalizePathSegments(string path) + { + List 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]; + } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index 396dee6f..efb203ca 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -37,12 +37,12 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// if is a valid path, otherwise. 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 exists. /// /// The path to be checked. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// if exists, otherwise. - 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; } /// @@ -81,13 +81,13 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// An containing the combined path, or an error. public Result 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 /// An containing the path segments, or an error. public Result> 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> 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 /// An containing the path segments of the path up one level from , or an error. public Result> 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 newPathResult = FileSystemPathId.Create(tempPath[..lastIndex]); if (newPathResult.IsFailure) return newPathResult.Errors; @@ -184,7 +184,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// /// Returns a collection of characters that are invalid for paths. /// - /// A collection of characters that are invalid in the context of paths + /// A collection of characters that are invalid in the context of paths. 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; } + + /// + /// Checks whether is located inside . 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. + /// + /// The path to be checked. + /// The path that must contain the checked path. + /// if the path is inside the parent path, otherwise. + 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; + } + + /// + /// Splits into its segments, resolving the "." (current directory) and ".." (parent directory) segments. + /// + /// The path to be normalized. + /// The normalized path segments of the path. + private string[] NormalizePathSegments(string path) + { + List 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]; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs index e37ab2d7..bccba4c3 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs @@ -29,7 +29,6 @@ public class GetDirectoriesEndpointTests : IClassFixture