add album art caching

This commit is contained in:
Drew Weymouth
2022-12-18 10:17:22 -08:00
parent 34710c7b08
commit 378eb8868a
5 changed files with 57 additions and 23 deletions
+42 -3
View File
@@ -1,36 +1,75 @@
package backend
import (
"fmt"
"image"
"image/jpeg"
"log"
"os"
"path/filepath"
"github.com/20after4/configdir"
"github.com/bluele/gcache"
subsonic "github.com/dweymouth/go-subsonic"
)
type ImageManager struct {
s *subsonic.Client
cacheDir string
thumbnailCache gcache.Cache
}
func NewImageManager(s *subsonic.Client) *ImageManager {
func NewImageManager(s *subsonic.Client, cacheDir string) *ImageManager {
cache := gcache.New(100).LRU().Build()
if err := configdir.MakePath(cacheDir); err != nil {
log.Println("failed to create album cover cache dir")
cacheDir = ""
}
return &ImageManager{
s: s,
cacheDir: cacheDir,
thumbnailCache: cache,
}
}
func (i *ImageManager) GetAlbumThumbnail(albumID string) (image.Image, error) {
// in-memory cache
if i.thumbnailCache.Has(albumID) {
if img, err := i.thumbnailCache.Get(albumID); err == nil {
return img.(image.Image), nil
}
}
// TODO: on disc cache
img, err := i.s.GetCoverArt(albumID, map[string]string{"size": "250"})
// on disc cache
path := filepath.Join(i.cacheDir, fmt.Sprintf("%s.jpg", albumID))
if i.cacheDir != "" {
if _, err := os.Stat(path); err == nil {
// serve image from on-disc cache
// TODO: image may have changed on server.
// first, return cached image, then fetch fresh img from server in background
if f, err := os.Open(path); err == nil {
defer f.Close()
if img, _, err := image.Decode(f); err == nil {
i.thumbnailCache.Set(albumID, img)
return img, nil
}
}
}
}
// fetch from server
img, err := i.s.GetCoverArt(albumID, map[string]string{"size": "300"})
if err != nil {
return nil, err
}
if i.cacheDir != "" {
if f, err := os.Create(path); err == nil {
defer f.Close()
if err := jpeg.Encode(f, img, nil /*options*/); err != nil {
log.Printf("failed to cache image: %s", err.Error())
}
}
}
i.thumbnailCache.Set(albumID, img)
return img, nil
}