aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--internal/thumbnail/cache.go11
-rw-r--r--internal/thumbnail/generator.go10
-rw-r--r--internal/thumbnail/init.go56
3 files changed, 72 insertions, 5 deletions
diff --git a/internal/thumbnail/cache.go b/internal/thumbnail/cache.go
index 80164e9..740268a 100644
--- a/internal/thumbnail/cache.go
+++ b/internal/thumbnail/cache.go
@@ -1,16 +1,21 @@
package thumbnail
import (
+ "fmt"
"path/filepath"
"github.com/RanXom/galleryd/internal/gallery"
)
const (
- thumbnailVersion = "v1"
- thumbnailExtension = ".webp"
+ thumbnailCacheVersion = 1
+ thumbnailExtension = ".webp"
)
+func cacheVersion() string {
+ return fmt.Sprintf("v%d", thumbnailCacheVersion)
+}
+
// cachePath returns the on-disk cache location for a photo thumbnail.
//
// Thumbnails are sharded by the first two characters of the photo ID to
@@ -23,7 +28,7 @@ func (g *Generator) cachePath(photo gallery.Photo) string {
return filepath.Join(
g.cacheDir,
"thumbs",
- thumbnailVersion,
+ cacheVersion(),
shard,
filename,
)
diff --git a/internal/thumbnail/generator.go b/internal/thumbnail/generator.go
index 423ead2..b18c712 100644
--- a/internal/thumbnail/generator.go
+++ b/internal/thumbnail/generator.go
@@ -11,10 +11,16 @@ type Generator struct {
cacheDir string
}
-func New(cacheDir string) *Generator {
- return &Generator{
+func New(cacheDir string) (*Generator, error) {
+ g := &Generator{
cacheDir: cacheDir,
}
+
+ if err := g.initializeCache(); err != nil {
+ return nil, err
+ }
+
+ return g, nil
}
// Generate creates (or retrieves) a thumbnail
diff --git a/internal/thumbnail/init.go b/internal/thumbnail/init.go
new file mode 100644
index 0000000..64f3b38
--- /dev/null
+++ b/internal/thumbnail/init.go
@@ -0,0 +1,56 @@
+package thumbnail
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// initializeCache prepares the thumbnail cache directory.
+//
+// It creates the current cache generation and removes obsolete cache
+// generations left behind by previous versions.
+func (g *Generator) initializeCache() error {
+ thumbsDir := filepath.Join(g.cacheDir, "thumbs")
+
+ if err := os.MkdirAll(
+ filepath.Join(thumbsDir, cacheVersion()),
+ 0o775,
+ ); err != nil {
+ return fmt.Errorf("create cache directory: %w", err)
+ }
+
+ entries, err := os.ReadDir(thumbsDir)
+ if err != nil {
+ return fmt.Errorf("read cache directory: %w", err)
+ }
+
+ current := cacheVersion()
+
+ for _, entry := range entries {
+ if !entry.IsDir() {
+ continue
+ }
+
+ name := entry.Name()
+
+ if strings.HasPrefix(name, "v") {
+ continue
+ }
+
+ if name == current {
+ continue
+ }
+
+ if err := os.RemoveAll(filepath.Join(thumbsDir, name)); err != nil {
+ return fmt.Errorf(
+ "remove obsolete cache %q: %w",
+ name,
+ err,
+ )
+ }
+ }
+
+ return nil
+}