download_test.go
⎇
Raw
1package service
2
3import (
4 "database/sql"
5 "os"
6 "path/filepath"
7 "strings"
8 "testing"
9
10 "vidarchive/internal/config"
11 "vidarchive/internal/models"
12)
13
14func TestSanitizeDirName(t *testing.T) {
15 tests := []struct{ in, want string }{
16 {"normal title", "normal title"},
17 {"a/b:c*d?e\"f<g>h|i", "a-b-c-d-e-f-g-h-i"},
18 {" trimmed ", "trimmed"},
19 {"", "untitled"},
20 {"///", "---"},
21 }
22 for _, tc := range tests {
23 if got := sanitizeDirName(tc.in); got != tc.want {
24 t.Errorf("sanitizeDirName(%q) = %q, want %q", tc.in, got, tc.want)
25 }
26 }
27}
28
29func TestUniqueDir(t *testing.T) {
30 base := t.TempDir()
31 svc := &DownloadService{}
32
33 first := svc.uniqueDir(base, "item")
34 if filepath.Base(first) != "item" {
35 t.Errorf("first uniqueDir = %q, want .../item", first)
36 }
37 if err := os.MkdirAll(first, 0755); err != nil {
38 t.Fatal(err)
39 }
40 second := svc.uniqueDir(base, "item")
41 if filepath.Base(second) != "item-1" {
42 t.Errorf("second uniqueDir = %q, want .../item-1", second)
43 }
44 if err := os.MkdirAll(second, 0755); err != nil {
45 t.Fatal(err)
46 }
47 third := svc.uniqueDir(base, "item")
48 if filepath.Base(third) != "item-2" {
49 t.Errorf("third uniqueDir = %q, want .../item-2", third)
50 }
51}
52
53func TestDeriveItemName(t *testing.T) {
54 svc := &DownloadService{}
55 itemDir := t.TempDir()
56
57 // info.json title wins and is sanitized.
58 infoPath := filepath.Join(itemDir, "info.json")
59 if err := os.WriteFile(infoPath, []byte(`{"title":"Cool: Video"}`), 0644); err != nil {
60 t.Fatal(err)
61 }
62 bigName := "big.mp4"
63 if err := os.WriteFile(filepath.Join(itemDir, bigName), []byte("xxxxxxxxxx"), 0644); err != nil {
64 t.Fatal(err)
65 }
66 media := []os.DirEntry{dirEntry(t, itemDir, bigName)}
67 if got := svc.deriveItemName(itemDir, infoPath, media); got != "Cool- Video" {
68 t.Errorf("deriveItemName with info.json = %q, want %q", got, "Cool- Video")
69 }
70
71 // Without info.json, falls back to the largest media file's stem.
72 small := "small.mp4"
73 if err := os.WriteFile(filepath.Join(itemDir, small), []byte("x"), 0644); err != nil {
74 t.Fatal(err)
75 }
76 media = []os.DirEntry{dirEntry(t, itemDir, small), dirEntry(t, itemDir, bigName)}
77 if got := svc.deriveItemName(itemDir, "", media); got != "big" {
78 t.Errorf("deriveItemName fallback = %q, want %q (largest file stem)", got, "big")
79 }
80}
81
82func dirEntry(t *testing.T, dir, name string) os.DirEntry {
83 t.Helper()
84 entries, err := os.ReadDir(dir)
85 if err != nil {
86 t.Fatal(err)
87 }
88 for _, e := range entries {
89 if e.Name() == name {
90 return e
91 }
92 }
93 t.Fatalf("dir entry %q not found", name)
94 return nil
95}
96
97func TestParseFormatList(t *testing.T) {
98 output := `[info] Available formats:
99ID EXT RESOLUTION FPS
10018 mp4 640x360 30
101137 mp4 1920x1080 60
102233 m4a audio_only_xtra 128k
103`
104 formats := parseFormatList(output)
105 if len(formats) != 3 {
106 t.Fatalf("expected 3 formats, got %d: %+v", len(formats), formats)
107 }
108 if formats[0].ID != "18" || formats[0].Ext != "mp4" {
109 t.Errorf("format[0] = %+v", formats[0])
110 }
111 if formats[1].Resolution != "1920x1080" {
112 t.Errorf("format[1] resolution = %q, want 1920x1080", formats[1].Resolution)
113 }
114 // A non-resolution token containing the letter 'x' must NOT be parsed as a
115 // resolution (the old "contains x" heuristic misclassified it).
116 if formats[2].Resolution != "" {
117 t.Errorf("format[2] resolution = %q, want empty (token has 'x' but isn't WxH)", formats[2].Resolution)
118 }
119}
120
121// TestImportItemDir exercises the full import: media + info.json + subtitles get
122// sorted into a named item directory with a marker. Uses ffmpeg to produce real
123// media so the mimetype-based classification in importItemDir matches.
124func TestImportItemDir(t *testing.T) {
125 requireFFmpeg(t)
126
127 libDir := t.TempDir()
128 svc := &DownloadService{cfg: &config.Config{LibraryDir: libDir}}
129
130 src := t.TempDir()
131 makeTestVideo(t, filepath.Join(src, "raw.mp4"))
132 if err := os.WriteFile(filepath.Join(src, "info.json"), []byte(`{"title":"My Clip"}`), 0644); err != nil {
133 t.Fatal(err)
134 }
135 if err := os.WriteFile(filepath.Join(src, "raw.en.srt"), []byte("1\n00:00:00,000 --> 00:00:01,000\nhi\n"), 0644); err != nil {
136 t.Fatal(err)
137 }
138
139 if err := svc.importItemDir("https://example.com/v", src, libDir, "", "-f bestvideo+bestaudio"); err != nil {
140 t.Fatalf("importItemDir: %v", err)
141 }
142
143 targetDir := filepath.Join(libDir, "My Clip")
144 if _, err := os.Stat(filepath.Join(targetDir, itemMarkerName)); err != nil {
145 t.Errorf("marker not created: %v", err)
146 }
147 if _, err := os.Stat(filepath.Join(targetDir, "info.json")); err != nil {
148 t.Errorf("info.json not moved: %v", err)
149 }
150 if _, err := os.Stat(filepath.Join(targetDir, "raw.mp4")); err != nil {
151 t.Errorf("media not moved: %v", err)
152 }
153 if _, err := os.Stat(filepath.Join(targetDir, subtitlesDirName, "raw.en.srt")); err != nil {
154 t.Errorf("subtitle not moved into subtitles dir: %v", err)
155 }
156
157 // The marker should record the source URL and a probed per-file duration
158 // (the test video is 3s), so the library never has to probe at serve time.
159 markerData, _ := os.ReadFile(filepath.Join(targetDir, itemMarkerName))
160 if want := "https://example.com/v"; !strings.Contains(string(markerData), want) {
161 t.Errorf("marker missing source url %q: %s", want, markerData)
162 }
163 if !strings.Contains(string(markerData), "file_durations") || !strings.Contains(string(markerData), "raw.mp4") {
164 t.Errorf("marker missing probed per-file duration: %s", markerData)
165 }
166 if want := "-f bestvideo+bestaudio"; !strings.Contains(string(markerData), want) {
167 t.Errorf("marker missing yt-dlp flags %q: %s", want, markerData)
168 }
169}
170
171func TestCheckReservedFlags(t *testing.T) {
172 cases := []struct {
173 name string
174 flags string
175 subscription bool
176 wantErr bool
177 }{
178 {"empty", "", false, false},
179 {"harmless", "--no-playlist --write-thumbnail", false, false},
180 {"output short", "-o foo.mp4", false, true},
181 {"output long", "--output foo.mp4", false, true},
182 {"output equals form", "--output=foo.mp4", false, true},
183 {"paths short", "-P /tmp", false, true},
184 {"cookies", "--cookies x.txt", false, true},
185 {"cookies inverse", "--no-cookies", false, true},
186 // Subscription-only reserved flags pass for normal downloads...
187 {"skip-download non-sub", "--skip-download", false, false},
188 {"write-info-json non-sub", "--write-info-json", false, false},
189 // ...but are rejected for subscription runs (and their inverses).
190 {"skip-download sub", "--skip-download", true, true},
191 {"no-skip-download sub", "--no-skip-download", true, true},
192 {"write-info-json sub", "--write-info-json", true, true},
193 {"no-write-info-json sub", "--no-write-info-json", true, true},
194 {"download-archive sub", "--download-archive a.txt", true, true},
195 // Base reserved flags still apply to subscriptions.
196 {"output sub", "-o x", true, true},
197 }
198 for _, tc := range cases {
199 t.Run(tc.name, func(t *testing.T) {
200 err := checkReservedFlags(tc.flags, tc.subscription)
201 if tc.wantErr != (err != nil) {
202 t.Errorf("checkReservedFlags(%q, %v) error = %v, wantErr %v", tc.flags, tc.subscription, err, tc.wantErr)
203 }
204 })
205 }
206}
207
208func TestImportDownloadedItemsRejectsOutputTraversal(t *testing.T) {
209 libDir := t.TempDir()
210 svc := &DownloadService{cfg: &config.Config{LibraryDir: libDir}}
211
212 // A temp download dir with one item subdir.
213 tempDir := t.TempDir()
214 itemDir := filepath.Join(tempDir, "item-00001")
215 if err := os.MkdirAll(itemDir, 0755); err != nil {
216 t.Fatal(err)
217 }
218
219 d := &models.Download{
220 URL: "u",
221 OutputDir: sql.NullString{String: "../escape", Valid: true},
222 }
223 if err := svc.importDownloadedItems(d, tempDir, "", ""); err == nil {
224 t.Error("expected path-traversal output dir to be rejected")
225 }
226}
227