parsers/parse_file.go

58 lines
1.3 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 {
// regex group references
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-13 11:19:42 +01:00
parsedFile.File = filename
2022-12-07 20:25:13 +01:00
return parsedFile, true
}
}