youp0m/backend_local.go

107 lines
2.2 KiB
Go

package main
import (
"image"
"image/jpeg"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"time"
)
func init() {
existing_backends = append(existing_backends, "local")
}
type LocalFileBackend struct {
BaseDir string
}
func (l *LocalFileBackend) getPath(box, name string) string {
return path.Join(l.BaseDir, box, name+".jpg")
}
func (l *LocalFileBackend) DeletePicture(box, name string) error {
return os.Remove(l.getPath(box, name))
}
func (l *LocalFileBackend) ServeFile() http.Handler {
return http.FileServer(http.Dir(l.BaseDir))
}
func (l *LocalFileBackend) createPictureInfo(local_path, name string, file os.FileInfo) *Picture {
return &Picture{
local_path, // Path
name, // Basename
name[:len(name)-len(path.Ext(name))], // Sanitized filename
file.ModTime(), // UploadTime
}
}
func (l *LocalFileBackend) GetPicture(box, name string, w io.Writer) error {
local_path := l.getPath(box, name)
fd, err := os.Open(local_path)
if err != nil {
return err
}
defer fd.Close()
_, err = io.Copy(w, fd)
return err
}
func (l *LocalFileBackend) GetPictureInfo(box, name string) (*Picture, error) {
local_path := l.getPath(box, name)
file, err := os.Stat(local_path)
if err != nil {
return nil, err
}
return l.createPictureInfo(path.Join(box, name+".jpg"), name, file), nil
}
func (l *LocalFileBackend) ListPictures(box string) ([]*Picture, error) {
files, err := ioutil.ReadDir(path.Join(l.BaseDir, box))
if err != nil {
return nil, err
}
pictures := make([]*Picture, 0)
for _, file := range files {
if !file.IsDir() {
pictures = append(pictures, l.createPictureInfo(path.Join(box, file.Name()), file.Name(), file))
}
}
return pictures, nil
}
func (l *LocalFileBackend) MovePicture(box_from, box_to, name string) error {
newpath := l.getPath(box_to, name)
err := os.Rename(
l.getPath(box_from, name),
newpath,
)
if err != nil {
return err
}
return os.Chtimes(newpath, time.Now(), time.Now())
}
func (l *LocalFileBackend) PutPicture(box, name string, img *image.Image) error {
fd, err := os.OpenFile(l.getPath(box, name), os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return err
}
defer fd.Close()
return jpeg.Encode(fd, *img, nil)
}