parsers/parse_file.go

57 lines
1.2 KiB
Go
Raw Normal View History

2022-12-07 20:25:13 +01:00
package parsers
import (
"path/filepath"
"regexp"
"git.milar.in/nyaanime/model"
)
// FileParseOptions holds the subgroup index in which information can be found in a given regex
type FileParseOptions struct {
Name int
Episode int
}
func RegexFileParser(regex string, options FileParseOptions) model.FileParserFunc {
pattern := regexp.MustCompile(regex)
// handle faulty regexes
if options.Name == 0 || options.Episode == 0 {
panic(ErrTorrentParserInsufficientData.New(regex))
}
// handle faulty group references
for _, g := range []int{options.Name, options.Episode} {
if g > pattern.NumSubexp() {
panic(ErrTorrentParserInvalidGroupReference.New(g, pattern.NumSubexp()))
}
}
return func(parser *model.Parser, path string) (file *model.ParsedFile, ok bool) {
filename := filepath.Base(path)
matches := pattern.FindStringSubmatch(filename)
if matches == nil {
return nil, false
}
episode, ok := atoi(matches[options.Episode])
if !ok {
return nil, false
}
parsedFile, err := AnalyzeFile(path)
if err != nil {
return nil, false
}
parsedFile.OriginalAnimeTitle = matches[options.Name]
parsedFile.Episode = episode
parsedFile.Parser = parser
2023-01-15 14:52:25 +01:00
parsedFile.File = path
2022-12-07 20:25:13 +01:00
return parsedFile, true
}
}