subsonic-tui/internal/client/artwork_cache.go
Sagi Dayan a3923cf42c initial commit
Signed-off-by: Sagi Dayan <sagidayan@gmail.com>
2024-03-29 17:56:39 +03:00

97 lines
1.5 KiB
Go

package client
import (
"fmt"
"image"
"image/jpeg"
"os"
"path"
)
type artcache struct {
artPaths map[string]string
cacheDir string
}
var ArtCache *artcache
func (c *artcache) saveArt(id string, img image.Image) *string {
path := c.GetPath(id)
if path != nil {
return path
}
path = c.saveImage(id, img)
if path != nil {
c.artPaths[id] = *path
}
return path
}
func (c *artcache) saveImage(id string, img image.Image) *string {
filePath := c.filepath(id)
f, err := os.Create(filePath)
defer func() {
_ = f.Close()
}()
if err != nil {
return nil
}
err = jpeg.Encode(f, img, nil)
if err != nil {
return nil
}
return &filePath
}
func (c *artcache) GetPath(id string) *string {
if path, ok := c.artPaths[id]; ok {
return &path
}
return nil
}
func (c *artcache) GetImage(id string) *image.Image {
path := c.GetPath(id)
if path == nil {
return nil
}
f, err := os.Open(*path)
if err != nil {
return nil
}
defer func() {
_ = f.Close()
}()
img, err := jpeg.Decode(f)
if err != nil {
return nil
}
return &img
}
func (c *artcache) filepath(id string) string {
return path.Join(c.cacheDir, fmt.Sprintf("%s.jpg", id))
}
func (c *artcache) Destroy() {
os.RemoveAll(c.cacheDir)
}
func init() {
tmpDir := os.TempDir()
cacheDir := path.Join(tmpDir, fmt.Sprintf("subsonic-tui-%d", os.Getpid()))
err := os.Mkdir(cacheDir, 0777)
if err != nil {
panic("Failed to create cacheDir")
}
ArtCache = &artcache{
cacheDir: cacheDir,
artPaths: make(map[string]string),
}
}