58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
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
|
|
parsedFile.File = path
|
|
|
|
return parsedFile, true
|
|
}
|
|
}
|