downloader/file_properties.go
2022-08-26 18:24:52 +02:00

86 lines
1.9 KiB
Go

package main
import (
"context"
"os"
"git.milar.in/nyaanime/model"
"git.milar.in/nyaanime/parsers"
ffprobe "gopkg.in/vansante/go-ffprobe.v2"
)
type FileProperties struct {
Filepath string
Languages []string
Subtitles []string
Resolution model.Resolution
}
var _ model.PropertyHolder = &FileProperties{}
var filePropCache = map[string]*FileProperties{}
func AnalyzeFile(path string) (props *FileProperties, err error) {
// caching
if cacheEntry, ok := filePropCache[path]; ok {
return cacheEntry, nil
}
defer func() {
if err == nil {
filePropCache[path] = props
}
}()
props = &FileProperties{Filepath: path}
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
data, err := ffprobe.ProbeReader(context.Background(), file)
if err != nil {
return nil, err
}
defaultVideoLang := ""
for _, s := range data.StreamType(ffprobe.StreamVideo) {
if s.Disposition.Default > 0 {
props.Resolution = model.Resolution(s.Height)
defaultVideoLang = parsers.ParseLanguage(s.Tags.Language)
break
}
}
for _, s := range data.StreamType(ffprobe.StreamAudio) {
if s.Tags.Language != "" {
props.Languages = append(props.Languages, parsers.ParseLanguage(s.Tags.Language))
} else if s.Disposition.Default > 0 {
props.Languages = append(props.Languages, defaultVideoLang)
}
}
for _, s := range data.StreamType(ffprobe.StreamSubtitle) {
if s.Tags.Language != "" {
props.Subtitles = append(props.Subtitles, parsers.ParseLanguage(s.Tags.Language))
} else if s.Disposition.Default > 0 {
props.Subtitles = append(props.Subtitles, defaultVideoLang)
}
}
return props, nil
}
func (fp *FileProperties) GetLanguages() []string {
return fp.Languages
}
func (fp *FileProperties) GetSubtitles() []string {
return fp.Subtitles
}
func (fp *FileProperties) GetResolution() model.Resolution {
return fp.Resolution
}