95 lines
2.2 KiB
Go
95 lines
2.2 KiB
Go
package store
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"gitea.benny.dog/torjus/ezshare/pb"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
var _ FileStore = &FileSystemStore{}
|
|
|
|
type FileSystemStore struct {
|
|
dir string
|
|
}
|
|
|
|
func NewFileSystemStore(dir string) *FileSystemStore {
|
|
return &FileSystemStore{dir: dir}
|
|
}
|
|
|
|
func (s *FileSystemStore) GetFile(id string) (*pb.File, error) {
|
|
path := filepath.Join(s.dir, id)
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
if os.IsNotExist(os.ErrNotExist) {
|
|
return nil, ErrNoSuchFile
|
|
}
|
|
return nil, fmt.Errorf("unable to open file: %w", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
fm, err := os.Open(fmt.Sprintf("%s.metadata", path))
|
|
if err != nil {
|
|
// TODO: Different error if file not found
|
|
return nil, fmt.Errorf("unable to open file: %w", err)
|
|
}
|
|
defer fm.Close()
|
|
|
|
var file pb.File
|
|
if file.Data, err = ioutil.ReadAll(f); err != nil {
|
|
return nil, fmt.Errorf("unable to read file: %w", err)
|
|
}
|
|
decoder := json.NewDecoder(fm)
|
|
if err := decoder.Decode(&file.Metadata); err != nil {
|
|
return nil, fmt.Errorf("unable to read file metadata: %w", err)
|
|
}
|
|
|
|
return &file, nil
|
|
}
|
|
|
|
func (s *FileSystemStore) StoreFile(file *pb.File) (string, error) {
|
|
id := uuid.Must(uuid.NewRandom()).String()
|
|
file.FileId = id
|
|
|
|
path := filepath.Join(s.dir, file.FileId)
|
|
f, err := os.Create(path)
|
|
if err != nil {
|
|
return "", fmt.Errorf("unable to store file: %w", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
fm, err := os.Create(fmt.Sprintf("%s.metadata", path))
|
|
if err != nil {
|
|
return "", fmt.Errorf("unable to store metadata: %w", err)
|
|
}
|
|
defer fm.Close()
|
|
|
|
if _, err := f.Write(file.Data); err != nil {
|
|
return "", fmt.Errorf("unable to write file to store: %w", err)
|
|
}
|
|
|
|
// TODO: Write metadata
|
|
encoder := json.NewEncoder(fm)
|
|
if err := encoder.Encode(file.Metadata); err != nil {
|
|
return "", fmt.Errorf("unable to write file to store: %w", err)
|
|
}
|
|
return file.FileId, nil
|
|
}
|
|
|
|
func (s *FileSystemStore) DeleteFile(id string) error {
|
|
path := filepath.Join(s.dir, id)
|
|
metadataPath := fmt.Sprintf("%s.metadata", path)
|
|
if err := os.Remove(path); err != nil {
|
|
return fmt.Errorf("error deleting file: %w", err)
|
|
}
|
|
if err := os.Remove(metadataPath); err != nil {
|
|
return fmt.Errorf("error deleting file metadata: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|