Smarter AUTO_DETECT grouping for audiobook series folders and multi-part files (#2900)

This commit is contained in:
ACX
2026-02-23 23:34:57 -07:00
committed by GitHub
parent 0867a06cce
commit 5d0d21d9c4
6 changed files with 933 additions and 18 deletions
@@ -109,22 +109,25 @@ public class LibraryFileHelper {
boolean hasNonAudioBooks = dirHasNonAudioBooks.getOrDefault(dir, false);
if (audioFiles != null && audioFiles.size() >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBooks) {
// This is a folder-based audiobook: contains 2+ audio files and no ebook files
// Don't treat library root as audiobook folder
if (!dir.equals(libraryPath)) {
log.info("Detected folder-based audiobook: {} ({} audio files)", dir.getFileName(), audioFiles.size());
if (FileUtils.isSeriesFolder(audioFiles)) {
log.info("Detected series folder: {} ({} audio files with distinct titles)", dir.getFileName(), audioFiles.size());
addIndividualAudioFiles(audioFiles, libraryEntity, pathEntity, libraryFiles);
} else {
log.info("Detected folder-based audiobook: {} ({} audio files)", dir.getFileName(), audioFiles.size());
processedAsFolderAudiobook.add(dir);
processedAsFolderAudiobook.add(dir);
// Add a single LibraryFile representing the folder
libraryFiles.add(LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(pathEntity)
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), dir))
.fileName(dir.getFileName().toString())
.bookFileType(BookFileType.AUDIOBOOK)
.folderBased(true)
.build());
libraryFiles.add(LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(pathEntity)
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), dir))
.fileName(dir.getFileName().toString())
.bookFileType(BookFileType.AUDIOBOOK)
.folderBased(true)
.build());
}
} else {
// Library root - add individual audio files
addIndividualAudioFiles(audioFiles, libraryEntity, pathEntity, libraryFiles);
@@ -18,6 +18,8 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.*;
@@ -252,7 +254,7 @@ public class LibraryFileEventProcessor {
}
private FolderAnalysis analyzeFolderForAudiobook(Path folderPath) {
int audioFileCount = 0;
List<Path> audioFiles = new ArrayList<>();
boolean hasNonAudioBook = false;
try (var stream = Files.walk(folderPath)) {
@@ -263,7 +265,7 @@ public class LibraryFileEventProcessor {
var ext = BookFileExtension.fromFileName(fileName);
if (ext.isPresent()) {
if (ext.get().getType() == BookFileType.AUDIOBOOK) {
audioFileCount++;
audioFiles.add(file);
} else {
hasNonAudioBook = true;
}
@@ -273,12 +275,15 @@ public class LibraryFileEventProcessor {
log.warn("[ERROR] Analyzing folder '{}': {}", folderPath, e.getMessage());
}
return new FolderAnalysis(audioFileCount, hasNonAudioBook);
boolean isSeriesFolder = audioFiles.size() >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK
&& FileUtils.isSeriesFolder(audioFiles);
return new FolderAnalysis(audioFiles.size(), hasNonAudioBook, isSeriesFolder);
}
private record FolderAnalysis(int audioFileCount, boolean hasNonAudioBook) {
private record FolderAnalysis(int audioFileCount, boolean hasNonAudioBook, boolean isSeriesFolder) {
boolean isFolderBasedAudiobook() {
return audioFileCount >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBook;
return audioFileCount >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBook && !isSeriesFolder;
}
}
@@ -44,6 +44,23 @@ public class BookFileGroupingUtils {
"[\\s_-]?(\\d{1,3})\\s*$"
);
// Part/disc indicators: "(part 1)", "[pt 2]", "- disc 1", "cd 3", etc.
// "part" requires brackets or dash prefix to avoid conflict with series labels ("Part 1" = series entry).
// "pt", "disc", "disk", "cd" are unambiguous and can be matched bare.
private static final Pattern PART_INDICATOR_PATTERN = Pattern.compile(
"\\s*(?:" +
"[\\(\\[]\\s*(?:part|pt|dis[ck]|cd)\\s*\\d+\\s*[\\)\\]]" +
"|-\\s*(?:part|pt|dis[ck]|cd)\\s*\\d+" +
"|(?:pt|dis[ck]|cd)\\s*\\d+" +
")\\s*$",
Pattern.CASE_INSENSITIVE
);
// Bare-number prefix: "1. Title", "01 - Title" (NOT "101 Dalmatians" or "1984")
private static final Pattern BARE_NUMBER_PREFIX_PATTERN = Pattern.compile(
"^(\\d{1,3})(?:\\.|\\s*-)\\s+(.+)$"
);
// Edition/version patterns that should NOT prevent grouping
// Includes format indicators (audiobook, ebook) and edition descriptors
private static final Pattern EDITION_PATTERN = Pattern.compile(
@@ -86,6 +103,9 @@ public class BookFileGroupingUtils {
baseName = FORMAT_INDICATOR_PATTERN.matcher(baseName).replaceAll("");
// Strip part/disc indicators (e.g., "(part 1)", "[cd 2]")
baseName = PART_INDICATOR_PATTERN.matcher(baseName).replaceAll("");
// Strip trailing author names (after dash)
baseName = TRAILING_AUTHOR_PATTERN.matcher(baseName).replaceAll("");
@@ -318,6 +338,18 @@ public class BookFileGroupingUtils {
}
}
}
// Fallback: bare-number prefix like "1. title" or "01 - title"
Matcher bareMatcher = BARE_NUMBER_PREFIX_PATTERN.matcher(key);
if (bareMatcher.matches()) {
String number = bareMatcher.group(1);
String baseTitle = bareMatcher.group(2).trim();
baseTitle = WHITESPACE_PATTERN.matcher(baseTitle).replaceAll(" ").trim();
if (baseTitle.length() >= 3) {
return new SeriesInfo(baseTitle, number);
}
}
return null;
}
@@ -12,8 +12,11 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
@UtilityClass
@Slf4j
@@ -147,6 +150,43 @@ public class FileUtils {
}
}
private static final Pattern LEADING_NUMBER_PREFIX = Pattern.compile("^\\d{1,3}(?:\\.|\\s*-)\\s*");
private static final Pattern PART_DISC_INDICATOR = Pattern.compile(
"\\s*[\\(\\[\\-]?\\s*(?:part|pt|dis[ck]|cd)\\s*\\d+\\s*[\\)\\]]?\\s*$",
Pattern.CASE_INSENSITIVE
);
private static final Pattern TRAILING_NUMBERS = Pattern.compile("\\s*\\d+\\s*$");
private static final Set<String> GENERIC_AUDIO_TITLES = Set.of(
"chapter", "track", "part", "disc", "disk", "cd", "side", "intro", "epilogue", "prologue", "outro"
);
/**
* Determines if a list of audio files represents a series folder (each file is a separate book)
* rather than a multi-file audiobook (chapter files for one book).
*
* Extracts a "base title" from each file by stripping numbering, part indicators, and extensions,
* then counts distinct non-generic titles. If more than one distinct title exists, it's a series folder.
*/
public boolean isSeriesFolder(List<Path> audioFiles) {
Set<String> distinctTitles = new HashSet<>();
for (Path file : audioFiles) {
String title = extractBaseTitle(file.getFileName().toString());
if (!title.isEmpty() && !GENERIC_AUDIO_TITLES.contains(title)) {
distinctTitles.add(title);
}
}
return distinctTitles.size() > 1;
}
private String extractBaseTitle(String fileName) {
int lastDot = fileName.lastIndexOf('.');
String baseName = lastDot > 0 ? fileName.substring(0, lastDot) : fileName;
baseName = LEADING_NUMBER_PREFIX.matcher(baseName).replaceFirst("");
baseName = PART_DISC_INDICATOR.matcher(baseName).replaceAll("");
baseName = TRAILING_NUMBERS.matcher(baseName).replaceAll("");
return baseName.toLowerCase().trim();
}
public void deleteDirectoryRecursively(Path path) throws IOException {
if (!Files.exists(path)) return;
@@ -510,6 +510,152 @@ class BookFileGroupingUtilsTest {
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(basic, withAuthor);
}
// ========== Part Indicator Stripping Tests ==========
@Test
void extractGroupingKey_shouldStripPartIndicators() {
assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero (part 1).m4b")).isEqualTo("the lost hero");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero (pt 2).m4b")).isEqualTo("the lost hero");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero (disc 1).m4b")).isEqualTo("the lost hero");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero [cd 3].m4b")).isEqualTo("the lost hero");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Lost Hero - part 1.m4b")).isEqualTo("the lost hero");
}
@Test
void extractGroupingKey_shouldPreserveNonPartParenthetical() {
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (Extended Edition).epub"))
.isEqualTo("the hobbit (extended edition)");
}
@Test
void extractGroupingKey_shouldProduceSameKeyForMultiPartFiles() {
String key1 = BookFileGroupingUtils.extractGroupingKey("1. The Lost Hero (part 1).m4b");
String key2 = BookFileGroupingUtils.extractGroupingKey("1. The Lost Hero (part 2).m4b");
assertThat(key1).isEqualTo(key2);
}
// ========== Bare-Number Series Detection Tests ==========
@Test
void extractGroupingKey_shouldNotStripBarePartAsSeriesLabel() {
// "Part 1" without brackets/dash is a series label, not a multi-file indicator
assertThat(BookFileGroupingUtils.extractGroupingKey("Harry Potter Part 1.epub"))
.isEqualTo("harry potter part 1");
assertThat(BookFileGroupingUtils.extractGroupingKey("Harry Potter Part 2.epub"))
.isEqualTo("harry potter part 2");
}
@Test
void groupByBaseName_shouldKeepBarePartSeriesEntriesSeparate() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile part1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Harry Potter")
.fileName("Harry Potter Part 1.epub")
.bookFileType(BookFileType.EPUB)
.build();
LibraryFile part2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Harry Potter")
.fileName("Harry Potter Part 2.epub")
.bookFileType(BookFileType.EPUB)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(part1, part2));
assertThat(groups).hasSize(2);
}
@Test
void groupByBaseName_shouldSeparateBareNumberedSeriesFiles() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile file1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Percy Jackson")
.fileName("1. The Lightning Thief.m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
LibraryFile file2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Percy Jackson")
.fileName("2. The Sea of Monsters.m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2));
assertThat(groups).hasSize(2);
}
@Test
void groupByBaseName_shouldGroupMultiPartFilesOfSameBook() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile part1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus")
.fileName("1. The Lost Hero (part 1).m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
LibraryFile part2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus")
.fileName("1. The Lost Hero (part 2).m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(part1, part2));
assertThat(groups).hasSize(1);
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(part1, part2);
}
@Test
void groupByBaseName_shouldHandleMixedPartsAndSeparateBooks() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile lostHeroPt1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus")
.fileName("1. The Lost Hero (part 1).m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
LibraryFile lostHeroPt2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus")
.fileName("1. The Lost Hero (part 2).m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
LibraryFile sonOfNeptune = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus")
.fileName("2. The Son of Neptune.m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(lostHeroPt1, lostHeroPt2, sonOfNeptune));
assertThat(groups).hasSize(2);
boolean foundLostHeroGroup = groups.values().stream()
.anyMatch(list -> list.size() == 2 && list.containsAll(List.of(lostHeroPt1, lostHeroPt2)));
assertThat(foundLostHeroGroup).isTrue();
}
@Test
void groupByBaseName_shouldHandleFolderBasedAudiobook() {
// Folder-based audiobook (MP3 folder) with ebook files
@@ -637,6 +783,453 @@ class BookFileGroupingUtilsTest {
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(epub, audiobook1);
}
// ========== Part Indicator Pattern Edge Cases ==========
@Test
void extractGroupingKey_shouldStripBareDiscAndCdAndPt() {
// pt, disc, disk, cd are unambiguous and stripped even without brackets/dash
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit disc 1.m4b")).isEqualTo("the hobbit");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit disk 2.m4b")).isEqualTo("the hobbit");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit cd 3.m4b")).isEqualTo("the hobbit");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit pt 1.m4b")).isEqualTo("the hobbit");
}
@Test
void extractGroupingKey_shouldStripPartInSquareBrackets() {
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [part 1].m4b")).isEqualTo("the hobbit");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [Part 2].m4b")).isEqualTo("the hobbit");
}
@Test
void extractGroupingKey_shouldStripPartCaseInsensitive() {
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (PART 1).m4b")).isEqualTo("the hobbit");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (Part 1).m4b")).isEqualTo("the hobbit");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit - PART 1.m4b")).isEqualTo("the hobbit");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit DISC 1.m4b")).isEqualTo("the hobbit");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit CD 3.m4b")).isEqualTo("the hobbit");
}
@Test
void extractGroupingKey_shouldNotStripPartWithoutNumber() {
// "part" keyword without a trailing number should not be stripped
assertThat(BookFileGroupingUtils.extractGroupingKey("The Best Part.epub")).isEqualTo("the best part");
assertThat(BookFileGroupingUtils.extractGroupingKey("Disc Jockey.m4b")).isEqualTo("disc jockey");
}
@Test
void extractGroupingKey_shouldStripAudioFormatIndicators() {
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (m4b).m4b")).isEqualTo("the hobbit");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (mp3).mp3")).isEqualTo("the hobbit");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit [audiobook].m4b")).isEqualTo("the hobbit");
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (audio).m4b")).isEqualTo("the hobbit");
}
@Test
void extractGroupingKey_shouldStripFormatThenPartIndicator() {
// Both format indicator and part indicator present
assertThat(BookFileGroupingUtils.extractGroupingKey("The Hobbit (mp3) (part 1).mp3")).isEqualTo("the hobbit");
}
// ========== Bare-Number Prefix Edge Cases ==========
@Test
void extractGroupingKey_shouldPreserveBareNumberDotPrefix() {
// "N. Title" prefix is preserved in the grouping key (series detection handles it separately)
assertThat(BookFileGroupingUtils.extractGroupingKey("01. The Lightning Thief.m4b")).isEqualTo("01. the lightning thief");
assertThat(BookFileGroupingUtils.extractGroupingKey("100. War and Peace.epub")).isEqualTo("100. war and peace");
}
@Test
void extractGroupingKey_shouldStripDashPrefixViaAuthorPattern() {
// "01 - The Lightning Thief" looks like "number - Author Name" to the trailing author pattern,
// so the author pattern strips it. This is expected existing behavior.
assertThat(BookFileGroupingUtils.extractGroupingKey("01 - The Lightning Thief.m4b")).isEqualTo("01");
}
@Test
void extractGroupingKey_shouldNotTreatFourDigitNumberAsPrefix() {
// 4-digit numbers should not be treated as series prefixes
assertThat(BookFileGroupingUtils.extractGroupingKey("1984.epub")).isEqualTo("1984");
}
@Test
void extractGroupingKey_shouldNotTreatNumberWithoutSeparatorAsPrefix() {
// "101 Dalmatians" has no dot or dash after the number
assertThat(BookFileGroupingUtils.extractGroupingKey("101 Dalmatians.epub")).isEqualTo("101 dalmatians");
}
@Test
void groupByBaseName_shouldSeparateFiveBookSeriesWithBareNumbers() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
List<LibraryFile> files = new java.util.ArrayList<>();
String[] titles = {
"1. The Lightning Thief.m4b",
"2. The Sea of Monsters.m4b",
"3. The Titans Curse.m4b",
"4. The Battle of the Labyrinth.m4b",
"5. The Last Olympian.m4b"
};
for (String title : titles) {
files.add(LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Percy Jackson")
.fileName(title)
.bookFileType(BookFileType.AUDIOBOOK)
.build());
}
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(files);
assertThat(groups).hasSize(5);
}
@Test
void groupByBaseName_shouldGroupSameBareNumberInMultipleFormats() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile epub = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Percy Jackson")
.fileName("1. The Lightning Thief.epub")
.bookFileType(BookFileType.EPUB)
.build();
LibraryFile m4b = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Percy Jackson")
.fileName("1. The Lightning Thief.m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
LibraryFile epub2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Percy Jackson")
.fileName("2. The Sea of Monsters.epub")
.bookFileType(BookFileType.EPUB)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(epub, m4b, epub2));
// Book 1 in 2 formats = 1 group, Book 2 = 1 group
assertThat(groups).hasSize(2);
boolean foundBook1Group = groups.values().stream()
.anyMatch(list -> list.size() == 2 && list.containsAll(List.of(epub, m4b)));
assertThat(foundBook1Group).isTrue();
}
@Test
void groupByBaseName_shouldSeparateDashPrefixedSeriesFiles() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile file1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Rick Riordan")
.fileName("01 - The Lightning Thief.m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
LibraryFile file2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Rick Riordan")
.fileName("02 - The Sea of Monsters.m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2));
assertThat(groups).hasSize(2);
}
@Test
void groupByBaseName_shouldHandleRootLevelBareNumberedFiles() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile file1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath(null)
.fileName("1. The Lightning Thief.epub")
.bookFileType(BookFileType.EPUB)
.build();
LibraryFile file2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath(null)
.fileName("2. The Sea of Monsters.epub")
.bookFileType(BookFileType.EPUB)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2));
// Root-level uses exact key matching, different keys = separate groups
assertThat(groups).hasSize(2);
}
// ========== Series Detection with Various Keywords ==========
@Test
void groupByBaseName_shouldSeparateEpisodeSeriesEntries() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile ep1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("The Podcast")
.fileName("The Podcast Episode 1.mp3")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
LibraryFile ep2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("The Podcast")
.fileName("The Podcast Episode 2.mp3")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(ep1, ep2));
assertThat(groups).hasSize(2);
}
@Test
void groupByBaseName_shouldSeparateHashNumberedSeries() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile n1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Discworld")
.fileName("Discworld #1.epub")
.bookFileType(BookFileType.EPUB)
.build();
LibraryFile n2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Discworld")
.fileName("Discworld #2.epub")
.bookFileType(BookFileType.EPUB)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(n1, n2));
assertThat(groups).hasSize(2);
}
// ========== Multi-Part Grouping Edge Cases ==========
@Test
void groupByBaseName_shouldGroupBracketedPartsAtRootLevel() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile pt1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath(null)
.fileName("The Lost Hero (part 1).m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
LibraryFile pt2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath(null)
.fileName("The Lost Hero (part 2).m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(pt1, pt2));
// Root-level exact key matching: both produce "the lost hero" → same group
assertThat(groups).hasSize(1);
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(pt1, pt2);
}
@Test
void groupByBaseName_shouldGroupDiscVariantsOfSameBook() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile d1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("War and Peace")
.fileName("War and Peace disc 1.m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
LibraryFile d2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("War and Peace")
.fileName("War and Peace disc 2.m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
LibraryFile d3 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("War and Peace")
.fileName("War and Peace disc 3.m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(d1, d2, d3));
assertThat(groups).hasSize(1);
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(d1, d2, d3);
}
@Test
void groupByBaseName_shouldGroupCdVariantsOfSameBook() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile cd1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Moby Dick")
.fileName("Moby Dick cd 1.m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
LibraryFile cd2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Moby Dick")
.fileName("Moby Dick cd 2.m4b")
.bookFileType(BookFileType.AUDIOBOOK)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(cd1, cd2));
assertThat(groups).hasSize(1);
assertThat(groups.values().iterator().next()).containsExactlyInAnyOrder(cd1, cd2);
}
// ========== Grouping Boundary / Misc Edge Cases ==========
@Test
void groupByBaseName_shouldHandleEmptyList() {
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of());
assertThat(groups).isEmpty();
}
@Test
void groupByBaseName_shouldHandleSingleFileInFolder() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile file = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Some Folder")
.fileName("Lonely Book.epub")
.bookFileType(BookFileType.EPUB)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file));
assertThat(groups).hasSize(1);
assertThat(groups.values().iterator().next()).containsExactly(file);
}
@Test
void groupByBaseName_shouldHandleEmptySubPath() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile file1 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("")
.fileName("Book.epub")
.bookFileType(BookFileType.EPUB)
.build();
LibraryFile file2 = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("")
.fileName("Book.pdf")
.bookFileType(BookFileType.PDF)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(file1, file2));
// Empty subPath treated as root level
assertThat(groups).hasSize(1);
}
@Test
void groupByBaseName_shouldSeparateCompletelyUnrelatedFilesInFolder() {
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile war = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Random")
.fileName("War and Peace.epub")
.bookFileType(BookFileType.EPUB)
.build();
LibraryFile moby = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Random")
.fileName("Moby Dick.epub")
.bookFileType(BookFileType.EPUB)
.build();
LibraryFile pride = LibraryFile.builder()
.libraryPathEntity(pathEntity)
.fileSubPath("Random")
.fileName("Pride and Prejudice.pdf")
.bookFileType(BookFileType.PDF)
.build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(war, moby, pride));
assertThat(groups).hasSize(3);
}
@Test
void groupByBaseName_shouldHandleFullHeroesOfOlympusScenario() {
// Realistic 5-book series with multi-part splits for some books
LibraryPathEntity pathEntity = new LibraryPathEntity();
pathEntity.setId(1L);
pathEntity.setPath("/library");
LibraryFile lh1 = LibraryFile.builder().libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus").fileName("1. The Lost Hero (part 1).m4b").bookFileType(BookFileType.AUDIOBOOK).build();
LibraryFile lh2 = LibraryFile.builder().libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus").fileName("1. The Lost Hero (part 2).m4b").bookFileType(BookFileType.AUDIOBOOK).build();
LibraryFile son = LibraryFile.builder().libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus").fileName("2. The Son of Neptune.m4b").bookFileType(BookFileType.AUDIOBOOK).build();
LibraryFile moa1 = LibraryFile.builder().libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus").fileName("3. The Mark of Athena (part 1).m4b").bookFileType(BookFileType.AUDIOBOOK).build();
LibraryFile moa2 = LibraryFile.builder().libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus").fileName("3. The Mark of Athena (part 2).m4b").bookFileType(BookFileType.AUDIOBOOK).build();
LibraryFile hoh = LibraryFile.builder().libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus").fileName("4. The House of Hades.m4b").bookFileType(BookFileType.AUDIOBOOK).build();
LibraryFile boo = LibraryFile.builder().libraryPathEntity(pathEntity)
.fileSubPath("Heroes of Olympus").fileName("5. The Blood of Olympus.m4b").bookFileType(BookFileType.AUDIOBOOK).build();
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(List.of(lh1, lh2, son, moa1, moa2, hoh, boo));
// 5 books: Lost Hero (2 parts grouped), Son of Neptune, Mark of Athena (2 parts grouped), House of Hades, Blood of Olympus
assertThat(groups).hasSize(5);
boolean lhGrouped = groups.values().stream().anyMatch(l -> l.size() == 2 && l.containsAll(List.of(lh1, lh2)));
boolean moaGrouped = groups.values().stream().anyMatch(l -> l.size() == 2 && l.containsAll(List.of(moa1, moa2)));
assertThat(lhGrouped).isTrue();
assertThat(moaGrouped).isTrue();
}
@Test
void groupByBaseName_shouldGroupFolderWithDotInName() {
// Folder-based audiobook with dot in name like "1. American Gods - Neil Gaiman (2011)"
@@ -189,9 +189,251 @@ class FileUtilsTest {
void testGetFileSizeInKb_validFile_returnsSize() throws IOException {
Path file = tempDir.resolve("test.txt");
Files.write(file, "test".getBytes());
Long size = FileUtils.getFileSizeInKb(file);
assertNotNull(size, "File size should not be null for existing file");
assertTrue(size >= 0, "File size should be non-negative");
}
// ========== isSeriesFolder Tests ==========
@Test
void testIsSeriesFolder_distinctTitles_returnsTrue() {
List<Path> files = List.of(
Path.of("1. The Lightning Thief.m4b"),
Path.of("2. The Sea of Monsters.m4b"),
Path.of("3. The Titans Curse.m4b")
);
assertTrue(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_chapterFiles_returnsFalse() {
List<Path> files = List.of(
Path.of("Chapter 01.mp3"),
Path.of("Chapter 02.mp3"),
Path.of("Chapter 03.mp3")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_bareNumberedTracks_returnsFalse() {
List<Path> files = List.of(
Path.of("01.mp3"),
Path.of("02.mp3"),
Path.of("03.mp3")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_trackFiles_returnsFalse() {
List<Path> files = List.of(
Path.of("Track 01.mp3"),
Path.of("Track 02.mp3"),
Path.of("Track 03.mp3")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_mixedWithParts_returnsTrue() {
List<Path> files = List.of(
Path.of("1. The Lost Hero (part 1).m4b"),
Path.of("1. The Lost Hero (part 2).m4b"),
Path.of("2. The Son of Neptune.m4b")
);
assertTrue(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_singleFile_returnsFalse() {
List<Path> files = List.of(Path.of("The Lightning Thief.m4b"));
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_dashSeparatedNumbers_returnsTrue() {
List<Path> files = List.of(
Path.of("01 - The Lightning Thief.m4b"),
Path.of("02 - The Sea of Monsters.m4b")
);
assertTrue(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_emptyList_returnsFalse() {
assertFalse(FileUtils.isSeriesFolder(List.of()));
}
@Test
void testIsSeriesFolder_allSameTitle_returnsFalse() {
// Same book split across multiple files (no number prefix)
List<Path> files = List.of(
Path.of("The Lightning Thief.m4b"),
Path.of("The Lightning Thief.mp3")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_sameTitleWithParts_returnsFalse() {
// Same book split into parts: after stripping part indicators, all produce same title
List<Path> files = List.of(
Path.of("The Lightning Thief (part 1).m4b"),
Path.of("The Lightning Thief (part 2).m4b"),
Path.of("The Lightning Thief (part 3).m4b")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_genericPartTitles_returnsFalse() {
// "Part" is in the generic list, so "Part 1", "Part 2" → stripped to "part" → generic
List<Path> files = List.of(
Path.of("Part 1.mp3"),
Path.of("Part 2.mp3"),
Path.of("Part 3.mp3")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_genericDiscTitles_returnsFalse() {
List<Path> files = List.of(
Path.of("Disc 1.mp3"),
Path.of("Disc 2.mp3")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_genericSideTitles_returnsFalse() {
List<Path> files = List.of(
Path.of("Side 1.mp3"),
Path.of("Side 2.mp3")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_genericIntroEpilogue_returnsFalse() {
List<Path> files = List.of(
Path.of("Intro.mp3"),
Path.of("Epilogue.mp3")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_genericOutro_returnsFalse() {
List<Path> files = List.of(
Path.of("Intro.mp3"),
Path.of("Outro.mp3")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_mixedGenericAndRealTitles_returnsFalse() {
// Only one non-generic title → not > 1 distinct → not a series
List<Path> files = List.of(
Path.of("Intro.mp3"),
Path.of("Chapter 01.mp3"),
Path.of("The Lightning Thief.m4b")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_mixedCaseFileNames_returnsTrue() {
List<Path> files = List.of(
Path.of("1. THE LIGHTNING THIEF.M4B"),
Path.of("2. the Sea of Monsters.m4b")
);
assertTrue(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_noExtension_returnsTrue() {
// Files without dots in the name (no extension confusion)
List<Path> files = List.of(
Path.of("The Lightning Thief"),
Path.of("The Sea of Monsters")
);
assertTrue(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_zeroPaddedNumbers_returnsTrue() {
List<Path> files = List.of(
Path.of("001. A Game of Thrones.m4b"),
Path.of("002. A Clash of Kings.m4b"),
Path.of("003. A Storm of Swords.m4b")
);
assertTrue(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_numberedPartsOfSameBook_returnsFalse() {
// Same book number but different parts → single distinct title after stripping
List<Path> files = List.of(
Path.of("1. The Lost Hero (part 1).m4b"),
Path.of("1. The Lost Hero (part 2).m4b"),
Path.of("1. The Lost Hero (part 3).m4b")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_twoDistinctAmongManyParts_returnsTrue() {
List<Path> files = List.of(
Path.of("1. The Lost Hero (part 1).m4b"),
Path.of("1. The Lost Hero (part 2).m4b"),
Path.of("1. The Lost Hero (part 3).m4b"),
Path.of("2. The Son of Neptune (part 1).m4b"),
Path.of("2. The Son of Neptune (part 2).m4b")
);
assertTrue(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_titlesWithSpecialCharacters_returnsTrue() {
List<Path> files = List.of(
Path.of("1. The Lion, the Witch & the Wardrobe.m4b"),
Path.of("2. Prince Caspian.m4b")
);
assertTrue(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_prologueAndChapters_returnsFalse() {
// All generic: prologue, chapter, epilogue
List<Path> files = List.of(
Path.of("Prologue.mp3"),
Path.of("Chapter 01.mp3"),
Path.of("Chapter 02.mp3"),
Path.of("Chapter 03.mp3"),
Path.of("Epilogue.mp3")
);
assertFalse(FileUtils.isSeriesFolder(files));
}
@Test
void testIsSeriesFolder_largeSeriesFolder_returnsTrue() {
List<Path> files = List.of(
Path.of("01. The Colour of Magic.m4b"),
Path.of("02. The Light Fantastic.m4b"),
Path.of("03. Equal Rites.m4b"),
Path.of("04. Mort.m4b"),
Path.of("05. Sourcery.m4b"),
Path.of("06. Wyrd Sisters.m4b"),
Path.of("07. Pyramids.m4b"),
Path.of("08. Guards Guards.m4b"),
Path.of("09. Eric.m4b"),
Path.of("10. Moving Pictures.m4b")
);
assertTrue(FileUtils.isSeriesFolder(files));
}
}