package converter import ( "errors" "fmt" "path/filepath" "strings" "sub-cli/internal/format/ass" "sub-cli/internal/format/lrc" "sub-cli/internal/format/srt" "sub-cli/internal/format/txt" "sub-cli/internal/format/vtt" "sub-cli/internal/model" ) // ErrUnsupportedFormat is returned when trying to convert to/from an unsupported format var ErrUnsupportedFormat = errors.New("unsupported format") // Convert converts a file from one format to another func Convert(sourceFile, targetFile string) error { sourceFmt := strings.TrimPrefix(filepath.Ext(sourceFile), ".") targetFmt := strings.TrimPrefix(filepath.Ext(targetFile), ".") // TXT only supports being a target format if sourceFmt == "txt" { return fmt.Errorf("%w: txt is only supported as a target format", ErrUnsupportedFormat) } // Convert source to intermediate representation subtitle, err := convertToIntermediate(sourceFile, sourceFmt) if err != nil { return err } // Convert from intermediate representation to target format return convertFromIntermediate(subtitle, targetFile, targetFmt) } // convertToIntermediate converts a source file to our intermediate Subtitle representation func convertToIntermediate(sourceFile, sourceFormat string) (model.Subtitle, error) { switch sourceFormat { case "lrc": return lrc.ConvertToSubtitle(sourceFile) case "srt": return srt.ConvertToSubtitle(sourceFile) case "vtt": return vtt.ConvertToSubtitle(sourceFile) case "ass": return ass.ConvertToSubtitle(sourceFile) default: return model.Subtitle{}, fmt.Errorf("%w: %s", ErrUnsupportedFormat, sourceFormat) } } // convertFromIntermediate converts our intermediate Subtitle representation to a target format func convertFromIntermediate(subtitle model.Subtitle, targetFile, targetFormat string) error { switch targetFormat { case "lrc": return lrc.ConvertFromSubtitle(subtitle, targetFile) case "srt": return srt.ConvertFromSubtitle(subtitle, targetFile) case "vtt": return vtt.ConvertFromSubtitle(subtitle, targetFile) case "ass": return ass.ConvertFromSubtitle(subtitle, targetFile) case "txt": return txt.GenerateFromSubtitle(subtitle, targetFile) default: return fmt.Errorf("%w: %s", ErrUnsupportedFormat, targetFormat) } }