parsers/torrent_parsing.go
2022-08-04 18:13:41 +02:00

62 lines
1.5 KiB
Go

package parsers
import (
"regexp"
"git.milar.in/animan/model"
)
// TorrentParseOptions holds the subgroup index in which information can be found in a given regex
// as well as some parser specific functions
type TorrentParseOptions struct {
Name int
Episode int
Languages int
Subtitles int
Resolution int
LanguageParser LanguageParserFunc
}
func regexTorrentParser(regex string, options TorrentParseOptions) model.TorrentParserFunc {
pattern := regexp.MustCompile(regex)
if options.Name == 0 || options.Episode == 0 {
panic(ErrTorrentParserInsufficientData.New(regex))
}
for _, g := range []int{options.Name, options.Episode, options.Languages, options.Subtitles, options.Resolution} {
if g > pattern.NumSubexp() {
panic(ErrTorrentParserInvalidGroupReference.New(g, pattern.NumSubexp()))
}
}
return func(parser *model.Parser, torrent *model.Torrent) (ParsedTorrent *model.ParsedTorrent, ok bool) {
matches := pattern.FindStringSubmatch(torrent.Title)
if matches == nil {
return nil, false
}
episode, ok := atoi(matches[options.Episode])
if !ok {
return nil, false
}
resolution, err := model.ParseResolution(matches[options.Resolution])
if err != nil {
return nil, false
}
return &model.ParsedTorrent{
Title: matches[options.Name],
Episode: episode,
Resolution: resolution,
Parser: parser,
Languages: options.LanguageParser(matches[options.Languages]),
Torrent: torrent,
}, true
}
}