mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-12-05 05:43:36 -05:00
What an extractor makes of a file does not depend on the size that was asked for, so it is kept under one key per file and read before the file is even downloaded. An empty entry says the file carries nothing, which keeps the next size from asking Tika again; a failed extraction is not remembered. The file cache now replaces what a key holds, as the other two backends already did, because an entry whose value can change has to be replaceable.
73 lines
1.3 KiB
Go
73 lines
1.3 KiB
Go
package cache
|
|
|
|
import (
|
|
"errors"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
// FileCache stores thumbnails on the local filesystem using hierarchical directories.
|
|
type FileCache struct {
|
|
dir string
|
|
}
|
|
|
|
func NewFileCache(dir string) *FileCache {
|
|
return &FileCache{dir: dir}
|
|
}
|
|
|
|
// The cache key is already a hierarchical relative path, so the on-disk
|
|
// location is the cache dir joined with it.
|
|
func (c *FileCache) Get(key string) ([]byte, error) {
|
|
path := filepath.Join(c.dir, key)
|
|
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return nil, ErrCacheMiss
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
return data, nil
|
|
}
|
|
|
|
func (c *FileCache) Put(key string, data []byte) error {
|
|
imgPath := filepath.Join(c.dir, key)
|
|
dir := filepath.Dir(imgPath)
|
|
|
|
if err := os.MkdirAll(dir, 0700); err != nil {
|
|
return err
|
|
}
|
|
|
|
f, err := os.CreateTemp(dir, "tmpthumb")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
tempPath := f.Name()
|
|
|
|
if _, err := f.Write(data); err != nil {
|
|
f.Close()
|
|
os.Remove(tempPath)
|
|
return err
|
|
}
|
|
|
|
if err := f.Sync(); err != nil {
|
|
f.Close()
|
|
os.Remove(tempPath)
|
|
return err
|
|
}
|
|
|
|
if err := f.Close(); err != nil {
|
|
os.Remove(tempPath)
|
|
return err
|
|
}
|
|
|
|
if err := os.Rename(tempPath, imgPath); err != nil {
|
|
os.Remove(tempPath)
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|