rustream/squire/
subtitles.rs

1use std::ffi::OsStr;
2use std::fs::File;
3use std::io::{Read, Write};
4use std::path::PathBuf;
5use std::result::Result;
6
7/// Converts an SRT file to VTT format.
8///
9/// # Arguments
10///
11/// * `filename` - The path to the input SRT file.
12///
13/// # Returns
14///
15/// A boolean indicating whether the conversion was successful.
16pub fn srt_to_vtt(filepath: &PathBuf) -> Result<bool, String> {
17    if filepath.extension().and_then(OsStr::to_str) != Some("srt") {
18        return Ok(false);
19    }
20
21    let output_file = filepath.with_extension("vtt");
22    let mut rf = match File::open(filepath) {
23        Ok(file) => file,
24        Err(err) => return Err(format!("Error opening file: {}", err)),
25    };
26
27    let mut srt_content = String::new();
28    if let Err(err) = rf.read_to_string(&mut srt_content) {
29        return Err(format!("Error reading file: {}", err));
30    }
31
32    let srt_content = srt_content.replace(',', ".");
33    let srt_content = srt_content.replace(" --> ", "-->");
34
35    let mut vtt_content = String::from("WEBVTT\n\n");
36    let subtitle_blocks: Vec<&str> = srt_content.trim().split("\n\n").collect();
37
38    for block in subtitle_blocks {
39        let lines: Vec<&str> = block.split('\n').collect();
40        let timecode = lines[1];
41        let text = lines[2..].join("\n");
42        vtt_content.push_str(&format!("{}\n{}\n\n", timecode, text));
43    }
44
45    let mut wf = match File::create(output_file) {
46        Ok(file) => file,
47        Err(err) => return Err(format!("Error creating output file: {}", err)),
48    };
49
50    if let Err(err) = wf.write_all(vtt_content.as_bytes()) {
51        return Err(format!("Error writing to output file: {}", err));
52    }
53
54    if let Err(err) = wf.flush() {
55        return Err(format!("Error flushing output file: {}", err));
56    }
57
58    Ok(true)
59}