package service import ( "os" "os/exec" "path/filepath" "strings" "testing" "vidarchive/internal/models" ) // --- test helpers --- func newLibrary(t *testing.T) (*LibraryService, string) { t.Helper() dir := t.TempDir() return NewLibraryService(dir, "ffmpeg", "ffprobe"), dir } // writeItem creates an item directory with a marker and the given files // (filename -> contents). A nil/empty marker body still creates a valid item. func writeItem(t *testing.T, libraryDir, relPath, markerBody string, files map[string]string) string { t.Helper() itemDir := filepath.Join(libraryDir, filepath.FromSlash(relPath)) if err := os.MkdirAll(itemDir, 0o755); err != nil { t.Fatalf("mkdir item: %v", err) } if markerBody == "" { markerBody = "duration = -1\n" } if err := os.WriteFile(filepath.Join(itemDir, itemMarkerName), []byte(markerBody), 0o644); err != nil { t.Fatalf("write marker: %v", err) } for name, content := range files { if err := os.WriteFile(filepath.Join(itemDir, name), []byte(content), 0o644); err != nil { t.Fatalf("write file %s: %v", name, err) } } return itemDir } func requireFFmpeg(t *testing.T) { t.Helper() if _, err := exec.LookPath("ffmpeg"); err != nil { t.Skip("ffmpeg not on PATH") } } // makeTestVideo writes a tiny real video file ffmpeg can decode a frame from. func makeTestVideo(t *testing.T, path string) { t.Helper() makeTestVideoSize(t, path, "64x64") } // makeTestVideoSize is makeTestVideo with an explicit WxH size. func makeTestVideoSize(t *testing.T, path, size string) { t.Helper() // 3s so the default 1s thumbnail seek lands on a real frame. cmd := exec.Command("ffmpeg", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=duration=3:size="+size+":rate=5", "-pix_fmt", "yuv420p", path, "-y") if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("make test video: %v\n%s", err, out) } } // --- pure helper tests --- func TestInfoDuration(t *testing.T) { tests := []struct { name string in map[string]interface{} want int ok bool }{ {"float", map[string]interface{}{"duration": 149.4}, 149, true}, {"float rounds up", map[string]interface{}{"duration": 149.6}, 150, true}, {"string", map[string]interface{}{"duration": "12.0"}, 12, true}, {"bad string", map[string]interface{}{"duration": "abc"}, 0, false}, {"missing", map[string]interface{}{}, 0, false}, {"nil", nil, 0, false}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { got, ok := infoDuration(tc.in) if ok != tc.ok || got != tc.want { t.Errorf("infoDuration(%v) = (%d,%v), want (%d,%v)", tc.in, got, ok, tc.want, tc.ok) } }) } } func TestInfoString(t *testing.T) { if _, ok := infoString(nil, "title"); ok { t.Error("nil info should return false") } if _, ok := infoString(map[string]interface{}{}, "title"); ok { t.Error("missing key should return false") } if v, ok := infoString(map[string]interface{}{"title": "hi"}, "title"); !ok || v != "hi" { t.Errorf("string value = (%q,%v), want (hi,true)", v, ok) } if _, ok := infoString(map[string]interface{}{"title": 5}, "title"); ok { t.Error("numeric value should return false, not stringify") } if _, ok := infoString(map[string]interface{}{"title": map[string]interface{}{"a": 1}}, "title"); ok { t.Error("map value should return false, not stringify") } } func TestPrimaryMediaFile(t *testing.T) { dir := t.TempDir() write := func(name string, n int) string { p := filepath.Join(dir, name) if err := os.WriteFile(p, make([]byte, n), 0o644); err != nil { t.Fatal(err) } return p } // Largest video wins over a larger audio file. mixed := &models.LibraryItem{MediaFiles: []models.MediaFile{ {Filename: "small.mp4", Filepath: write("small.mp4", 10)}, {Filename: "big.mp4", Filepath: write("big.mp4", 100)}, {Filename: "huge.mp3", Filepath: write("huge.mp3", 1000), IsAudio: true}, }} if got := primaryMediaFile(mixed); got == nil || got.Filename != "big.mp4" { t.Errorf("expected largest video big.mp4, got %v", got) } // Audio-only item falls back to the largest audio file. audio := &models.LibraryItem{MediaFiles: []models.MediaFile{ {Filename: "a.mp3", Filepath: write("a.mp3", 5), IsAudio: true}, {Filename: "b.mp3", Filepath: write("b.mp3", 50), IsAudio: true}, }} if got := primaryMediaFile(audio); got == nil || got.Filename != "b.mp3" { t.Errorf("expected largest audio b.mp3, got %v", got) } if got := primaryMediaFile(&models.LibraryItem{}); got != nil { t.Errorf("empty item should yield nil, got %v", got) } } // --- listItemFiles / GetAll --- func TestListItemFilesClassification(t *testing.T) { svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "item", "", map[string]string{ "video.mp4": "v", "audio.mp3": "a", "audio.m4a": "a", "cover.jpg": "img", "thumb.webp": "img", "notes.txt": "ignored", "info.json": `{"title":"x"}`, "video.info.json": `{"title":"x"}`, }) media, infoPath, err := svc.listItemFiles(itemDir) if err != nil { t.Fatalf("listItemFiles: %v", err) } if len(media) != 3 { t.Fatalf("expected 3 media files, got %d: %+v", len(media), media) } var sawAudio, sawVideo, sawM4A bool for _, m := range media { switch m.Filename { case "audio.mp3": sawAudio = true if !m.IsAudio { t.Error("audio.mp3 should be IsAudio") } // yt-dlp writes .m4a for extracted audio, so the scanner must list it — // otherwise an imported item never appears in the library. case "audio.m4a": sawM4A = true if !m.IsAudio { t.Error("audio.m4a should be IsAudio") } case "video.mp4": sawVideo = true if m.IsAudio { t.Error("video.mp4 should not be IsAudio") } default: t.Errorf("unexpected media file %q", m.Filename) } } if !sawAudio || !sawVideo || !sawM4A { t.Error("missing expected media files") } if infoPath == "" { t.Error("expected an info.json path") } } func TestListItemFilesSortedAscending(t *testing.T) { svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "item", "", map[string]string{ "03 - c.mp4": "c", "01 - a.mp4": "a", "02 - b.mp4": "b", }) media, _, err := svc.listItemFiles(itemDir) if err != nil { t.Fatalf("listItemFiles: %v", err) } got := make([]string, len(media)) for i, m := range media { got[i] = m.Filename } want := []string{"01 - a.mp4", "02 - b.mp4", "03 - c.mp4"} for i := range want { if got[i] != want[i] { t.Fatalf("media files = %v, want ascending %v", got, want) } } } func TestGetAllSeparatesFoldersAndItems(t *testing.T) { svc, dir := newLibrary(t) // An item (has marker) writeItem(t, dir, "song", "name = \"Song\"\nduration = -1\n", map[string]string{"a.mp4": "v"}) // A plain folder (no marker) containing a nested item writeItem(t, dir, "folder/nested", "name = \"Nested\"\nduration = -1\n", map[string]string{"b.mp4": "v"}) // The reserved subtitles dir at root must be ignored if err := os.MkdirAll(filepath.Join(dir, subtitlesDirName), 0o755); err != nil { t.Fatal(err) } items, folders, err := svc.GetAll("", "title", "") if err != nil { t.Fatalf("GetAll: %v", err) } if len(items) != 1 || items[0].Name != "Song" { t.Errorf("expected 1 item 'Song', got %+v", items) } if len(folders) != 1 || folders[0] != "folder" { t.Errorf("expected folder 'folder', got %v", folders) } for _, f := range folders { if f == subtitlesDirName { t.Error("subtitles dir should not be listed as a folder") } } } func TestGetAllFilter(t *testing.T) { svc, dir := newLibrary(t) writeItem(t, dir, "alpha", "name = \"Alpha\"\nduration = -1\n", map[string]string{"a.mp4": "v"}) writeItem(t, dir, "beta", "name = \"Beta\"\nduration = -1\n", map[string]string{"b.mp4": "v"}) items, _, err := svc.GetAll("", "title", "alph") if err != nil { t.Fatalf("GetAll: %v", err) } if len(items) != 1 || items[0].Name != "Alpha" { t.Errorf("filter 'alph' should match only Alpha, got %+v", items) } } func TestGetAllSortByTitle(t *testing.T) { svc, dir := newLibrary(t) writeItem(t, dir, "c", "name = \"Charlie\"\nduration = -1\n", map[string]string{"c.mp4": "v"}) writeItem(t, dir, "a", "name = \"alpha\"\nduration = -1\n", map[string]string{"a.mp4": "v"}) writeItem(t, dir, "b", "name = \"Bravo\"\nduration = -1\n", map[string]string{"b.mp4": "v"}) items, _, err := svc.GetAll("", "title", "") if err != nil { t.Fatalf("GetAll: %v", err) } got := []string{items[0].Name, items[1].Name, items[2].Name} want := []string{"alpha", "Bravo", "Charlie"} // case-insensitive for i := range want { if got[i] != want[i] { t.Errorf("sort by title = %v, want %v", got, want) break } } } // --- metadata derivation + marker write behavior --- func TestScanItemDerivesMetadataFromInfoJSON(t *testing.T) { svc, dir := newLibrary(t) info := `{"title":"Real Title","webpage_url":"https://example.com/v","description":"hello","duration":149.2}` writeItem(t, dir, "x", "duration = -1\n", map[string]string{ "x.mp4": "v", "info.json": info, }) item, err := svc.GetByRelPath("x") if err != nil { t.Fatalf("GetByRelPath: %v", err) } if item.Name != "Real Title" { t.Errorf("Name = %q, want derived from info.json", item.Name) } if item.SourceURL != "https://example.com/v" { t.Errorf("SourceURL = %q", item.SourceURL) } if item.Description != "hello" { t.Errorf("Description = %q", item.Description) } if item.Duration != 149 { t.Errorf("Duration = %d, want 149", item.Duration) } // Derived metadata should be persisted to the marker. markerData, _ := os.ReadFile(filepath.Join(dir, "x", itemMarkerName)) if !strings.Contains(string(markerData), "Real Title") { t.Errorf("marker not enriched with derived title: %s", markerData) } } func TestScanItemUsesFileDurations(t *testing.T) { svc, dir := newLibrary(t) marker := "name = \"M\"\n\n[file_durations]\n \"a.mp4\" = 30\n \"b.mp4\" = 12\n" writeItem(t, dir, "multi", marker, map[string]string{"a.mp4": "v", "b.mp4": "v"}) item, err := svc.GetByRelPath("multi") if err != nil { t.Fatalf("GetByRelPath: %v", err) } got := map[string]int{} for _, mf := range item.MediaFiles { got[mf.Filename] = mf.Duration } if got["a.mp4"] != 30 || got["b.mp4"] != 12 { t.Errorf("per-file durations = %v, want a=30 b=12", got) } // The item duration is the sum of known per-file durations (used for sorting); // there is no single "overall" duration any more. if item.Duration != 42 { t.Errorf("item Duration = %d, want 42 (sum of file durations)", item.Duration) } } func TestScanItemDoesNotRewriteConvergedMarker(t *testing.T) { svc, dir := newLibrary(t) // Disable the scan cache so every read actually rescans — this exercises // scanItem's own idempotency rather than just a cache hit. svc.scanTTL = 0 marker := "name = \"Done\"\nsource_url = \"u\"\ndescription = \"d\"\n" itemDir := writeItem(t, dir, "y", marker, map[string]string{"y.mp4": "v"}) markerPath := filepath.Join(itemDir, itemMarkerName) // First read may enrich the marker (e.g. cache per-file durations), after // which it has converged. if _, err := svc.GetByRelPath("y"); err != nil { t.Fatalf("warm-up read: %v", err) } before, err := os.Stat(markerPath) if err != nil { t.Fatal(err) } // Subsequent reads must not rewrite a converged marker. for i := 0; i < 3; i++ { if _, err := svc.GetByRelPath("y"); err != nil { t.Fatalf("GetByRelPath: %v", err) } } after, err := os.Stat(markerPath) if err != nil { t.Fatal(err) } if !before.ModTime().Equal(after.ModTime()) { t.Errorf("converged marker was rewritten on read (mtime changed %v -> %v)", before.ModTime(), after.ModTime()) } } // TestScanItemEmptyInfoFieldsDoNotRewriteMarker is a regression test: an // info.json with present-but-empty "description"/"webpage_url" must not flip the // marker dirty on every scan. infoString returns ("", true) for those fields, so // the old code reassigned "" and rewrote the marker forever (e.g. clips whose // text lives only in the title). We detect any rewrite via an unknown TOML key, // which scanItem's re-encode would drop. func TestScanItemEmptyInfoFieldsDoNotRewriteMarker(t *testing.T) { svc, dir := newLibrary(t) svc.scanTTL = 0 // force a real rescan on every read info := `{"title":"#hashtags only","description":"","webpage_url":""}` marker := "name = \"#hashtags only\"\nsentinel = \"keep\"\n" writeItem(t, dir, "z", marker, map[string]string{"z.mp4": "v", "info.json": info}) markerPath := filepath.Join(dir, "z", itemMarkerName) for i := 0; i < 3; i++ { if _, err := svc.GetByRelPath("z"); err != nil { t.Fatalf("GetByRelPath: %v", err) } } data, _ := os.ReadFile(markerPath) if !strings.Contains(string(data), "sentinel") { t.Errorf("marker was rewritten on read (sentinel dropped): %s", data) } } // --- scan cache --- func TestScanCacheReusesWithinTTL(t *testing.T) { svc, dir := newLibrary(t) writeItem(t, dir, "x", "name = \"X\"\nsource_url = \"u\"\n", map[string]string{"x.mp4": "v"}) // Within the TTL, repeated lookups return the same cached scan (no rescan). a, err := svc.GetByRelPath("x") if err != nil { t.Fatalf("first lookup: %v", err) } b, err := svc.GetByRelPath("x") if err != nil { t.Fatalf("second lookup: %v", err) } if a != b { t.Error("expected the cached scan to be reused (same pointer) within the TTL") } // Deleting the item evicts its cached scan immediately. if err := svc.Delete("x"); err != nil { t.Fatalf("Delete: %v", err) } if _, ok := svc.getCachedScan("x"); ok { t.Error("Delete should evict the cached scan") } // With caching disabled, each lookup rescans into a distinct item. svc2, dir2 := newLibrary(t) svc2.scanTTL = 0 writeItem(t, dir2, "y", "name = \"Y\"\n", map[string]string{"y.mp4": "v"}) c, _ := svc2.GetByRelPath("y") d, _ := svc2.GetByRelPath("y") if c == nil || d == nil || c == d { t.Error("with TTL disabled each lookup should rescan, not reuse a pointer") } } // --- path traversal --- func TestResolveItemDirRejectsTraversal(t *testing.T) { svc, dir := newLibrary(t) if _, err := svc.resolveItemDir("../../etc"); err == nil { t.Error("expected error for traversal path") } // A legitimate nested path resolves fine. got, err := svc.resolveItemDir("sub/item") if err != nil { t.Fatalf("unexpected error: %v", err) } if !strings.HasPrefix(got, dir) { t.Errorf("resolved path %q not under library %q", got, dir) } } // --- delete safety --- func TestDeleteRejectsLibraryRoot(t *testing.T) { svc, dir := newLibrary(t) writeItem(t, dir, "keep", "name = \"Keep\"\nduration = -1\n", map[string]string{"k.mp4": "v"}) for _, rel := range []string{"", "/", "//"} { if err := svc.Delete(rel); err == nil { t.Errorf("Delete(%q) should be refused", rel) } } // The guard must not have touched the library or its contents. if _, err := os.Stat(filepath.Join(dir, "keep", "k.mp4")); err != nil { t.Fatalf("library content was deleted by a root-delete attempt: %v", err) } // A real item still deletes. if err := svc.Delete("keep"); err != nil { t.Fatalf("Delete(real item): %v", err) } if _, err := os.Stat(filepath.Join(dir, "keep")); !os.IsNotExist(err) { t.Errorf("expected item dir removed, stat err = %v", err) } } // --- Thumbnail behavior ---