subsonic-tui/internal/client/artwork_cache.go
Sagi Dayan 99e8e299e4
Some checks failed
ci / check for spelling errors (pull_request) Failing after 22s
ci / Make sure build does not fail (pull_request) Successful in 2m52s
ci / code quality (lint/tests) (pull_request) Has been skipped
Added ci workflow + fixed linting issues
Signed-off-by: Sagi Dayan <sagidayan@gmail.com>
2024-12-18 17:29:16 +02:00

107 lines
1.5 KiB
Go

package client
import (
"fmt"
"image"
"image/jpeg"
"io/fs"
"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, id+".jpg")
}
func (c *artcache) Destroy() {
os.RemoveAll(c.cacheDir)
}
func init() {
tmpDir := os.TempDir()
cacheDir := path.Join(tmpDir, fmt.Sprintf("subsonic-tui-%d", os.Getpid()))
var permissions fs.FileMode = 0o777
err := os.Mkdir(cacheDir, permissions)
if err != nil {
panic("Failed to create cacheDir")
}
ArtCache = &artcache{
cacheDir: cacheDir,
artPaths: make(map[string]string),
}
}