-
-
Notifications
You must be signed in to change notification settings - Fork 37
Fix/602: root folder deletion #607
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
T4g1
wants to merge
7
commits into
Listenarrs:canary
Choose a base branch
from
T4g1:fix/602-root-folder-deletion
base: canary
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b097470
[fix] Remove root folder contained within another one
T4g1 72afc45
[fix] Adapt tests to run with full context
T4g1 6e0c43d
[fix] Code review
T4g1 1411735
[fix] Tests
T4g1 f45e026
[fix] Pernicious error due to infrastructure layer tracking leaking i…
T4g1 d6683ce
[fix] Github wont succeed
T4g1 28306e5
[fix] Uniform trailing separator for root folders and audiobooks folders
T4g1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,208 @@ | ||
| /* | ||
| * Listenarr - Audiobook Management System | ||
| * Copyright (C) 2024-2026 Listenarr Contributors | ||
| * | ||
| * This program is free software: you can redistribute it and/or modify | ||
| * it under the terms of the GNU Affero General Public License as published | ||
| * by the Free Software Foundation, either version 3 of the License, or | ||
| * (at your option) any later version. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| * GNU Affero General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Affero General Public License | ||
| * along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
| */ | ||
| using Listenarr.Application.Interfaces; | ||
| using Listenarr.Application.Interfaces.Repositories; | ||
| using Listenarr.Domain.Models; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Listenarr.Application.Audiobooks | ||
| { | ||
| public class RootFolderService( | ||
| IRootFolderRepository rootFolderRepository, | ||
| IAudiobookRepository audiobookRepository, | ||
| ILogger<RootFolderService> logger, | ||
| IMoveQueueService moveQueueService) : IRootFolderService | ||
| { | ||
| public async Task<RootFolder?> GetDefaultAsync() | ||
| { | ||
| return await rootFolderRepository.GetDefaultAsync(); | ||
| } | ||
|
|
||
| private async Task<bool> HasDuplicate(RootFolder root) | ||
| { | ||
| var rootFolders = await rootFolderRepository.GetAllAsync(); | ||
| return rootFolders.Any(r => r.Path == root.Path && r.Id != root.Id); | ||
| } | ||
|
|
||
| public async Task<RootFolder> CreateAsync(RootFolder root) | ||
| { | ||
| root.Path ??= string.Empty; | ||
| root.Name = root.Name?.Trim() ?? string.Empty; | ||
|
|
||
| if (string.IsNullOrWhiteSpace(root.Path)) throw new ArgumentException("Path is required"); | ||
| if (string.IsNullOrWhiteSpace(root.Name)) throw new ArgumentException("Name is required"); | ||
|
|
||
| if (await HasDuplicate(root)) throw new InvalidOperationException("A root folder with that path already exists."); | ||
|
|
||
| if (root.IsDefault) | ||
| { | ||
| await rootFolderRepository.ClearDefaultExceptAsync(excludeId: null); | ||
| } | ||
|
|
||
| await rootFolderRepository.AddAsync(root); | ||
| return root; | ||
| } | ||
|
|
||
| public async Task DeleteAsync(int id, int? reassignRootId = null) | ||
| { | ||
| var rootFolders = await rootFolderRepository.GetAllAsync(); | ||
| var rootFolder = rootFolders.FirstOrDefault(r => r.Id == id); | ||
| if (rootFolder == null) | ||
| { | ||
| logger.LogWarning($"Root folder with id {id} cannot be found, assuming it's deleted"); | ||
| return; | ||
| } | ||
|
|
||
| var rootFoldersAfterDelete = rootFolders | ||
| .Where(r => r.Id != id) | ||
| .ToList(); | ||
|
|
||
| if (reassignRootId != null) | ||
| { | ||
| var newRoot = await rootFolderRepository.GetByIdAsync(reassignRootId!.Value) ?? throw new KeyNotFoundException("Reassign root not found"); | ||
| await MigrateAudiobookPathsAsync(rootFolder.Path, newRoot.Path); | ||
| } | ||
|
|
||
| var audiobooks = await audiobookRepository.GetAllAsync(); | ||
|
|
||
| // Audiobooks are considered orphaned if base path is empty or no root folder can be linked to it | ||
| var orphanedAudiobooks = audiobooks | ||
| .Where(a => string.IsNullOrEmpty(a.BasePath) || !rootFolders.Any(r => a.BasePath!.StartsWith(r.Path))); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The trailing separator fix helps, but I’d still avoid raw |
||
|
|
||
| if (orphanedAudiobooks.Any()) | ||
| { | ||
| var formattedList = string.Join(", ", orphanedAudiobooks.Select(a => a.Title)); | ||
|
|
||
| logger.LogWarning($"The following audiobooks are orphaned: {formattedList}"); | ||
| } | ||
|
|
||
| var rootedAudiobooks = audiobooks | ||
| .Where(a => !orphanedAudiobooks.Any(o => o.Id == a.Id)) // Check only audiobooks that are not orphaned | ||
| .Where(a => !rootFoldersAfterDelete.Any(r => a.BasePath!.StartsWith(r.Path))); | ||
| if (rootedAudiobooks.Any()) | ||
| { | ||
| throw new InvalidOperationException($"Root folder is in use by {rootedAudiobooks.Count()} audiobooks, we cannot remove it"); | ||
| } | ||
|
|
||
| await rootFolderRepository.RemoveAsync(id); | ||
| } | ||
|
|
||
| public async Task<List<RootFolder>> GetAllAsync() => await rootFolderRepository.GetAllAsync(); | ||
|
|
||
| public async Task<RootFolder?> GetByIdAsync(int id) => await rootFolderRepository.GetByIdAsync(id); | ||
|
|
||
| public async Task<RootFolder> UpdateAsync(RootFolder root, bool moveFiles = false, bool deleteEmptySource = true) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(root); | ||
|
|
||
| root.Path ??= string.Empty; | ||
| root.Name = root.Name?.Trim() ?? string.Empty; | ||
|
|
||
| var existing = await rootFolderRepository.GetByIdAsync(root.Id) ?? throw new KeyNotFoundException("Root folder not found"); | ||
|
|
||
| if (await HasDuplicate(root)) throw new InvalidOperationException("A root folder with that path already exists."); | ||
|
|
||
| if (root.IsDefault) | ||
| { | ||
| await rootFolderRepository.ClearDefaultExceptAsync(excludeId: root.Id); | ||
| } | ||
|
|
||
| var oldPath = existing.Path; | ||
| var newPath = root.Path; | ||
|
|
||
| List<(int audiobookId, string original, string target)> moves = []; | ||
| if (!string.Equals(oldPath, newPath, StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| moves = await MigrateAudiobookPathsAsync(oldPath, newPath); | ||
|
|
||
| try | ||
| { | ||
| logger.LogInformation("Root rename from {OldPath} to {NewPath}: {Count} audiobooks affected", oldPath, newPath, moves.Count); | ||
| foreach (var m in moves) | ||
| { | ||
| logger.LogInformation("Root rename move prep: AudiobookId={AudiobookId} Original={Original} Target={Target}", m.audiobookId, m.original, m.target); | ||
| } | ||
| } | ||
| catch (Exception ex) when (ex is not OperationCanceledException && ex is not OutOfMemoryException && ex is not StackOverflowException) | ||
| { | ||
| logger.LogDebug(ex, "Failed to emit diagnostics for root rename"); | ||
| } | ||
| } | ||
|
|
||
| existing.Name = root.Name; | ||
| existing.Path = root.Path; | ||
| existing.IsDefault = root.IsDefault; | ||
| existing.UpdatedAt = DateTime.UtcNow; | ||
| await rootFolderRepository.UpdateAsync(existing); | ||
|
|
||
| if (moveFiles) | ||
| { | ||
| foreach (var m in moves) | ||
| { | ||
| try | ||
| { | ||
| _ = moveQueueService.EnqueueMoveAsync(m.audiobookId, m.target, m.original); | ||
| } | ||
| catch (Exception ex) when (ex is not OperationCanceledException && ex is not OutOfMemoryException && ex is not StackOverflowException) | ||
| { | ||
| logger.LogWarning(ex, "Failed to enqueue move for audiobook {AudiobookId} during root rename", m.audiobookId); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return existing; | ||
| } | ||
|
|
||
| // FIXME: Should be in audibook service | ||
| // FIXME: Can produce unexpected results (on the user side) when some root folder are contained within each other (/data/media and /data/media/library) and one of them gets moved | ||
| private async Task<List<(int audiobookId, string original, string target)>> MigrateAudiobookPathsAsync(string oldRootPath, string newRootPath, CancellationToken ct = default) | ||
| { | ||
| var all = await audiobookRepository.GetAllAsync(); | ||
| all = [.. all.Where(a => !string.IsNullOrEmpty(a.BasePath))]; | ||
|
|
||
| const char backslash = '\\'; | ||
| const char slash = '/'; | ||
| string NormalizeForCompare(string s) => (s ?? string.Empty).Replace(slash, backslash).TrimEnd(backslash).ToLowerInvariant(); | ||
| var oldNorm = NormalizeForCompare(oldRootPath); | ||
|
|
||
| var affected = all.Where(a => | ||
| { | ||
| var bpNorm = NormalizeForCompare(a.BasePath!); | ||
| return bpNorm == oldNorm || bpNorm.StartsWith(oldNorm + backslash); | ||
| }).ToList(); | ||
|
|
||
| var moves = new List<(int audiobookId, string original, string target)>(); | ||
| foreach (var a in affected) | ||
| { | ||
| var original = a.BasePath!; | ||
| var suffix = original.Length > oldRootPath.Length | ||
| ? original.Substring(oldRootPath.Length).TrimStart(backslash, slash) | ||
| : string.Empty; | ||
| var target = string.IsNullOrEmpty(suffix) | ||
| ? newRootPath | ||
| : Path.Combine(newRootPath, suffix); | ||
| moves.Add((a.Id, original, target)); | ||
| a.BasePath = target; | ||
|
|
||
| await audiobookRepository.UpdateAsync(a); | ||
| } | ||
|
|
||
| return moves; | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.