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 uint } 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) bool { for _, m := range s { if m.Hash == hash { return true } } return false }