Files
2024-12-10 10:24:31 +08:00

108 lines
2.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package media_store
import (
"encoding/json"
"os"
"path/filepath"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
type Store []VideoInfo
type VideoInfo struct {
Hash string
Name string
Duration int64
}
// Price
func (info VideoInfo) Price() int64 {
min := int64(10)
// if duration is less than 300 seconds, return 10
if info.Duration < 5*60 {
return min * 100
}
// 每多一分钟,价格加 3 如果余数大于 30 秒,按一分钟计算
cells := (info.Duration - 5*30) / 60
if info.Duration%60 > 30 {
cells++
}
return (min + cells*3) * 100
}
func NewStore(path string) (Store, error) {
mapFile := filepath.Join(path, "map.json")
log.Infof("read in from: %s", mapFile)
if _, err := os.Stat(mapFile); err != nil {
if os.IsNotExist(err) {
if err := os.WriteFile(mapFile, []byte("[]"), os.ModePerm); err != nil {
return nil, errors.Wrapf(err, "write file: %s", mapFile)
}
}
}
b, err := os.ReadFile(mapFile)
if err != nil {
return nil, errors.Wrapf(err, "read file: %s", mapFile)
}
var store Store
err = json.Unmarshal(b, &store)
if err != nil {
return nil, errors.Wrapf(err, "unmarshal json: %s", mapFile)
}
return store, nil
}
func (s Store) Save(path string) error {
mapFile := filepath.Join(path, "map.json")
b, err := json.Marshal(s)
if err != nil {
return errors.Wrapf(err, "marshal json: %s", mapFile)
}
if err := os.WriteFile(mapFile, b, os.ModePerm); err != nil {
return errors.Wrapf(err, "write file: %s", mapFile)
}
return nil
}
func (s Store) Append(info VideoInfo) Store {
return append(s, info)
}
func (s Store) Hashes() []string {
var hashes []string
for _, m := range s {
hashes = append(hashes, m.Hash)
}
return hashes
}
// Exists
func (s Store) HashExists(hash string) (VideoInfo, bool) {
for _, m := range s {
if m.Hash == hash {
return m, true
}
}
return VideoInfo{}, false
}
func (s Store) Update(info VideoInfo) {
for i, m := range s {
if m.Hash == info.Hash {
s[i] = info
break
}
}
}