feat: add media store and store medias
This commit is contained in:
80
backend/common/media_store/store.go
Normal file
80
backend/common/media_store/store.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package media_store
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Store []UUIDMap
|
||||
|
||||
type UUIDMap struct {
|
||||
UUID string
|
||||
Name string
|
||||
}
|
||||
|
||||
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) Add(uuid, name string) {
|
||||
*s = append(*s, UUIDMap{UUID: uuid, Name: name})
|
||||
}
|
||||
|
||||
func (s *Store) UUIDs() []string {
|
||||
var uuids []string
|
||||
for _, m := range *s {
|
||||
uuids = append(uuids, m.UUID)
|
||||
}
|
||||
|
||||
return uuids
|
||||
}
|
||||
|
||||
// Exists
|
||||
func (s *Store) Exists(name string) bool {
|
||||
for _, m := range *s {
|
||||
if m.Name == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user