subx-cli 1.7.4

AI subtitle processing CLI tool, which automatically matches, renames, and converts subtitle files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Media file discovery utilities.
//!
//! This module provides `FileDiscovery` to scan directories,
//! classify media files (video and subtitle), and collect metadata needed for matching.
//!
//! # Examples
//!
//! ```rust,ignore
//! use subx_cli::core::matcher::discovery::FileDiscovery;
//! let disco = FileDiscovery::new();
//! let files = disco.scan_directory("./path".as_ref(), true).unwrap();
//! ```

use std::path::{Path, PathBuf};
use walkdir::WalkDir;

use crate::Result;
use crate::core::uuidv7::Uuidv7Generator;

/// Media file record representing a discovered file.
///
/// Contains metadata about a media file discovered during the scanning process,
/// including its path, type classification, and basic file properties.
#[derive(Debug, Clone)]
pub struct MediaFile {
    /// Unique identifier for this media file (`file_<uuid-v7-hyphenated>`)
    pub id: String,
    /// Full path to the media file
    pub path: PathBuf,
    /// Classification of the file (Video or Subtitle)
    pub file_type: MediaFileType,
    /// File size in bytes
    pub size: u64,
    /// Complete filename with extension (e.g., "movie.mkv")
    pub name: String,
    /// File extension (without the dot)
    pub extension: String,
    /// Relative path from scan root for recursive matching
    pub relative_path: String,
}
/// Generate a unique UUIDv7-based identifier for a discovered media file.
///
/// The returned string has the form `file_<uuid-v7-hyphenated>` (length 41)
/// and embeds a `unix_time_ts` strictly greater than that of every previous
/// ID produced by the same generator instance. Callers that need monotonic
/// ordering across an entire scan SHALL share a single
/// [`Uuidv7Generator`] across all calls in the scan.
pub fn generate_file_id(generator: &mut Uuidv7Generator) -> String {
    format!("file_{}", generator.next_id().hyphenated())
}

// Unit tests: FileDiscovery file matching logic
#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_files(dir: &std::path::Path) {
        let _ = fs::write(dir.join("video1.mp4"), b"");
        let _ = fs::write(dir.join("video2.mkv"), b"");
        let _ = fs::write(dir.join("subtitle1.srt"), b"");
        let sub = dir.join("season1");
        fs::create_dir_all(&sub).unwrap();
        let _ = fs::write(sub.join("episode1.mp4"), b"");
        let _ = fs::write(sub.join("episode1.srt"), b"");
        let _ = fs::write(dir.join("note.txt"), b"");
    }

    #[test]
    fn test_file_discovery_non_recursive() {
        let temp = TempDir::new().unwrap();
        create_test_files(temp.path());
        let disco = FileDiscovery::new();
        let files = disco.scan_directory(temp.path(), false).unwrap();
        let vids = files
            .iter()
            .filter(|f| matches!(f.file_type, MediaFileType::Video))
            .count();
        let subs = files
            .iter()
            .filter(|f| matches!(f.file_type, MediaFileType::Subtitle))
            .count();
        assert_eq!(vids, 2);
        assert_eq!(subs, 1);
        assert!(!files.iter().any(|f| f.relative_path.contains("episode1")));
    }

    #[test]
    fn test_file_discovery_recursive() {
        let temp = TempDir::new().unwrap();
        create_test_files(temp.path());
        let disco = FileDiscovery::new();
        let files = disco.scan_directory(temp.path(), true).unwrap();
        let vids = files
            .iter()
            .filter(|f| matches!(f.file_type, MediaFileType::Video))
            .count();
        let subs = files
            .iter()
            .filter(|f| matches!(f.file_type, MediaFileType::Subtitle))
            .count();
        assert_eq!(vids, 3);
        assert_eq!(subs, 2);
        assert!(files.iter().any(|f| f.relative_path.contains("episode1")));
    }

    #[test]
    fn test_file_classification_and_extensions() {
        let temp = TempDir::new().unwrap();
        let v = temp.path().join("t.mp4");
        fs::write(&v, b"").unwrap();
        let s = temp.path().join("t.srt");
        fs::write(&s, b"").unwrap();
        let x = temp.path().join("t.txt");
        fs::write(&x, b"").unwrap();
        let disco = FileDiscovery::new();
        let vf = disco
            .classify_file(&v, temp.path(), &mut Uuidv7Generator::new())
            .unwrap()
            .unwrap();
        assert!(matches!(vf.file_type, MediaFileType::Video));
        assert_eq!(vf.name, "t.mp4");
        let sf = disco
            .classify_file(&s, temp.path(), &mut Uuidv7Generator::new())
            .unwrap()
            .unwrap();
        assert!(matches!(sf.file_type, MediaFileType::Subtitle));
        assert_eq!(sf.name, "t.srt");
        let none = disco
            .classify_file(&x, temp.path(), &mut Uuidv7Generator::new())
            .unwrap();
        assert!(none.is_none());
        assert!(disco.video_extensions.contains(&"mp4".to_string()));
        assert!(disco.subtitle_extensions.contains(&"srt".to_string()));
    }

    #[test]
    fn test_empty_and_nonexistent_directory() {
        let temp = TempDir::new().unwrap();
        let disco = FileDiscovery::new();
        let files = disco.scan_directory(temp.path(), false).unwrap();
        assert!(files.is_empty());
        let res = disco.scan_directory(&std::path::Path::new("/nonexistent/path"), false);
        assert!(res.is_err());
    }
}

// Unit tests for unique ID generation and MediaFile structure
#[cfg(test)]
mod id_tests {
    use super::*;
    use crate::core::uuidv7::unix_time_ms;
    use std::fs;
    use tempfile::TempDir;

    fn parse_file_id(id: &str) -> uuid::Uuid {
        let stripped = id
            .strip_prefix("file_")
            .expect("file id must begin with `file_`");
        uuid::Uuid::parse_str(stripped).expect("file id must contain a valid UUID")
    }

    #[test]
    fn test_media_file_structure_with_unique_id() {
        let temp = TempDir::new().unwrap();
        let video_path = temp.path().join("[Test][01].mkv");
        fs::write(&video_path, b"dummy content").unwrap();

        let disco = FileDiscovery::new();
        let files = disco.scan_directory(temp.path(), false).unwrap();

        let video_file = files
            .iter()
            .find(|f| matches!(f.file_type, MediaFileType::Video))
            .unwrap();

        assert!(!video_file.id.is_empty());
        assert!(video_file.id.starts_with("file_"));
        assert_eq!(video_file.id.len(), 41);
        let parsed = parse_file_id(&video_file.id);
        assert_eq!(parsed.get_version_num(), 7);

        assert_eq!(video_file.name, "[Test][01].mkv");
        assert_eq!(video_file.extension, "mkv");
        assert_eq!(video_file.relative_path, "[Test][01].mkv");
    }

    #[test]
    fn test_uuidv7_id_generation() {
        let mut gen1 = Uuidv7Generator::new();
        let id1 = generate_file_id(&mut gen1);
        assert!(id1.starts_with("file_"));
        assert_eq!(id1.len(), 41);

        let parsed1 = parse_file_id(&id1);
        assert_eq!(parsed1.get_version_num(), 7);

        let id2 = generate_file_id(&mut gen1);
        let parsed2 = parse_file_id(&id2);
        assert_eq!(parsed2.get_version_num(), 7);

        assert!(
            unix_time_ms(&parsed2) > unix_time_ms(&parsed1),
            "second id's unix_time_ts must strictly exceed the first"
        );
    }

    #[test]
    fn test_recursive_mode_with_unique_ids() {
        let temp = TempDir::new().unwrap();
        let sub_dir = temp.path().join("season1");
        fs::create_dir_all(&sub_dir).unwrap();

        let video1 = temp.path().join("movie.mkv");
        let video2 = sub_dir.join("episode1.mkv");
        fs::write(&video1, b"content1").unwrap();
        fs::write(&video2, b"content2").unwrap();

        let disco = FileDiscovery::new();
        let files = disco.scan_directory(temp.path(), true).unwrap();

        let root_video = files.iter().find(|f| f.name == "movie.mkv").unwrap();
        let sub_video = files.iter().find(|f| f.name == "episode1.mkv").unwrap();

        assert_ne!(root_video.id, sub_video.id);
        assert_eq!(root_video.id.len(), 41);
        assert_eq!(sub_video.id.len(), 41);
        assert_eq!(parse_file_id(&root_video.id).get_version_num(), 7);
        assert_eq!(parse_file_id(&sub_video.id).get_version_num(), 7);
        assert_eq!(root_video.relative_path, "movie.mkv");
        assert_eq!(sub_video.relative_path, "season1/episode1.mkv");
    }

    #[test]
    fn test_uuidv7_id_shape_basic() {
        let mut generator = Uuidv7Generator::new();
        let id = generate_file_id(&mut generator);
        assert!(id.starts_with("file_"));
        assert_eq!(id.len(), 41);
        assert_eq!(parse_file_id(&id).get_version_num(), 7);
    }
}

impl Default for FileDiscovery {
    fn default() -> Self {
        Self::new()
    }
}

/// Enumeration of supported media file types.
///
/// Classifies discovered files into their primary categories for
/// processing by the subtitle matching system.
#[derive(Debug, Clone)]
pub enum MediaFileType {
    /// Video file (e.g., .mp4, .mkv, .avi)
    Video,
    /// Subtitle file (e.g., .srt, .ass, .vtt)
    Subtitle,
}

/// File discovery engine for scanning and classifying media files.
pub struct FileDiscovery {
    video_extensions: Vec<String>,
    subtitle_extensions: Vec<String>,
}

impl FileDiscovery {
    /// Creates a new `FileDiscovery` with default video and subtitle extensions.
    pub fn new() -> Self {
        Self {
            video_extensions: vec![
                "mp4".to_string(),
                "mkv".to_string(),
                "avi".to_string(),
                "mov".to_string(),
                "wmv".to_string(),
                "flv".to_string(),
                "m4v".to_string(),
                "webm".to_string(),
            ],
            subtitle_extensions: vec![
                "srt".to_string(),
                "ass".to_string(),
                "vtt".to_string(),
                "sub".to_string(),
                "ssa".to_string(),
                "idx".to_string(),
            ],
        }
    }

    /// Scans the given directory and returns all media files found.
    ///
    /// # Arguments
    ///
    /// * `path` - The root directory to scan.
    /// * `recursive` - Whether to scan subdirectories recursively.
    pub fn scan_directory(&self, root_path: &Path, recursive: bool) -> Result<Vec<MediaFile>> {
        let mut files = Vec::new();
        let mut id_gen = Uuidv7Generator::new();

        let walker = if recursive {
            WalkDir::new(root_path).into_iter()
        } else {
            WalkDir::new(root_path).max_depth(1).into_iter()
        };

        for entry in walker {
            let entry = entry?;
            let path = entry.path();

            let ft = entry.file_type();
            if ft.is_symlink() {
                log::debug!("Skipping symlink: {}", path.display());
                continue;
            }
            if ft.is_file() {
                if let Some(media_file) = self.classify_file(path, root_path, &mut id_gen)? {
                    files.push(media_file);
                }
            }
        }

        Ok(files)
    }

    /// Creates MediaFile objects from a list of file paths.
    ///
    /// This method processes each file path individually, creating MediaFile objects
    /// with consistent IDs that match those generated by scan_directory.
    ///
    /// # Arguments
    ///
    /// * `file_paths` - A slice of file paths to process
    ///
    /// # Returns
    ///
    /// A vector of `MediaFile` objects for valid media files, or an error if file access fails.
    pub fn scan_file_list(&self, file_paths: &[PathBuf]) -> Result<Vec<MediaFile>> {
        let mut media_files = Vec::new();
        let mut id_gen = Uuidv7Generator::new();

        for path in file_paths {
            if !path.exists() {
                continue; // Skip non-existent files
            }

            if !path.is_file() {
                continue; // Skip directories
            }

            if let Some(extension) = path.extension().and_then(|e| e.to_str()) {
                let extension_lower = extension.to_lowercase();

                // Check if it's a video or subtitle file
                let file_type = if self.video_extensions.contains(&extension_lower) {
                    MediaFileType::Video
                } else if self.subtitle_extensions.contains(&extension_lower) {
                    MediaFileType::Subtitle
                } else {
                    continue; // Skip non-media files
                };

                if let Ok(metadata) = path.metadata() {
                    let name = path
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("")
                        .to_string();

                    // For file list scanning, use filename as relative path
                    // This maintains compatibility with existing display logic
                    let relative_path = name.clone();

                    let media_file = MediaFile {
                        id: generate_file_id(&mut id_gen),
                        path: path.clone(),
                        file_type,
                        size: metadata.len(),
                        name,
                        extension: extension_lower,
                        relative_path,
                    };
                    media_files.push(media_file);
                }
            }
        }

        Ok(media_files)
    }

    /// Classifies a file by its extension and gathers its metadata.
    ///
    /// Returns `Some(MediaFile)` if the file is a recognized media type,
    /// or `None` otherwise.
    fn classify_file(
        &self,
        path: &Path,
        scan_root: &Path,
        id_gen: &mut Uuidv7Generator,
    ) -> Result<Option<MediaFile>> {
        let extension = path
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|s| s.to_lowercase())
            .unwrap_or_default();

        let file_type = if self.video_extensions.contains(&extension) {
            MediaFileType::Video
        } else if self.subtitle_extensions.contains(&extension) {
            MediaFileType::Subtitle
        } else {
            return Ok(None);
        };

        let metadata = std::fs::metadata(path)?;
        // Complete filename with extension
        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default()
            .to_string();

        // Compute relative path with normalized separators
        let relative_path = path
            .strip_prefix(scan_root)
            .unwrap_or(path)
            .to_string_lossy()
            .replace('\\', "/"); // Normalize to Unix-style separators for consistency

        // Generate a per-scan unique UUIDv7-based identifier
        let id = generate_file_id(id_gen);

        Ok(Some(MediaFile {
            id,
            path: path.to_path_buf(),
            file_type,
            size: metadata.len(),
            name,
            extension,
            relative_path,
        }))
    }
}