guessit-go/guessit.go

128 lines
2.4 KiB
Go

package guessit
import (
"encoding/json"
"fmt"
"log"
"os/exec"
)
type GuessitConfig struct {
Python string
Git bool
Pip bool
}
type Guessit struct {
GuessitConfig
DefaultOptions []string
}
type Match struct {
// Main
Type string `json:"type,omitempty"`
Title string `json:"title,omitempty"`
ReleaseGroup string `json:"release_group,omitempty"`
StreamingService string `json:"streaming_service,omitempty"`
// Episode
Season int64 `json:"season,omitempty"`
Episode int64 `json:"episode,omitempty"`
Version int64 `json:"version,omitempty"`
// Video
ScreenSize string `json:"screen_size,omitempty"`
Container string `json:"container,omitempty"`
VideoCodec string `json:"video_codec,omitempty"`
// Audio
AudioChannels string `json:"audio_channels,omitempty"`
AudioCodec []string `json:"audio_codec,omitempty"`
// Other
Other []string `json:"other,omitempty"`
}
func (u *Match) UnmarshalJSON(data []byte) error {
type Alias Match
aux := &struct {
AudioCodec interface{} `json:"audio_codec,omitempty"`
Other interface{} `json:"other,omitempty"`
*Alias
}{
Alias: (*Alias)(u),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
switch ac := aux.AudioCodec.(type) {
case string:
u.AudioCodec = append(u.AudioCodec, ac)
case []string:
u.AudioCodec = ac
}
switch oth := aux.Other.(type) {
case string:
u.Other = append(u.Other, oth)
case []string:
u.Other = oth
}
return nil
}
func (g GuessitConfig) PipInstall() (err error) {
args := []string{"-m", "pip", "install", "guessit"}
cmd := exec.Command(g.Python, args...)
cmdout, err := cmd.Output()
if err != nil {
return
}
fmt.Println(string(cmdout))
return nil
}
func New(conf GuessitConfig) (Guessit, error) {
if conf.Python == "" {
conf.Python = "python3"
}
pyPath, err := exec.LookPath(conf.Python)
if err != nil {
log.Fatal(err)
}
conf.Python = pyPath
if conf.Pip {
err = conf.PipInstall()
if err != nil {
return Guessit{}, err
}
}
return Guessit{conf, []string{}}, nil
}
func (g Guessit) Guessit(s string, options ...string) (out Match, err error) {
args := []string{"-m", "guessit", s}
args = append(args, g.DefaultOptions...)
args = append(args, options...)
args = append(args, "--json")
cmd := exec.Command(g.Python, args...)
cmdout, err := cmd.Output()
if err != nil {
return
}
err = json.Unmarshal(cmdout, &out)
return
}