2024-01-16 15:21:35 +00:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"image"
|
|
|
|
"image/jpeg"
|
2024-12-18 15:29:16 +00:00
|
|
|
"io/fs"
|
2024-01-16 15:21:35 +00:00
|
|
|
"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
|
|
|
|
}
|
2024-12-18 15:29:16 +00:00
|
|
|
|
2024-01-16 15:21:35 +00:00
|
|
|
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
|
|
|
|
}
|
2024-12-18 15:29:16 +00:00
|
|
|
|
2024-01-16 15:21:35 +00:00
|
|
|
err = jpeg.Encode(f, img, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
2024-12-18 15:29:16 +00:00
|
|
|
|
2024-01-16 15:21:35 +00:00
|
|
|
return &filePath
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *artcache) GetPath(id string) *string {
|
|
|
|
if path, ok := c.artPaths[id]; ok {
|
|
|
|
return &path
|
|
|
|
}
|
2024-12-18 15:29:16 +00:00
|
|
|
|
2024-01-16 15:21:35 +00:00
|
|
|
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
|
|
|
|
}
|
2024-12-18 15:29:16 +00:00
|
|
|
|
2024-01-16 15:21:35 +00:00
|
|
|
return &img
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *artcache) filepath(id string) string {
|
2024-12-18 15:29:16 +00:00
|
|
|
return path.Join(c.cacheDir, id+".jpg")
|
2024-01-16 15:21:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *artcache) Destroy() {
|
|
|
|
os.RemoveAll(c.cacheDir)
|
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
tmpDir := os.TempDir()
|
|
|
|
cacheDir := path.Join(tmpDir, fmt.Sprintf("subsonic-tui-%d", os.Getpid()))
|
2024-12-18 15:29:16 +00:00
|
|
|
|
|
|
|
var permissions fs.FileMode = 0o777
|
|
|
|
|
|
|
|
err := os.Mkdir(cacheDir, permissions)
|
2024-01-16 15:21:35 +00:00
|
|
|
if err != nil {
|
|
|
|
panic("Failed to create cacheDir")
|
|
|
|
}
|
2024-12-18 15:29:16 +00:00
|
|
|
|
2024-01-16 15:21:35 +00:00
|
|
|
ArtCache = &artcache{
|
|
|
|
cacheDir: cacheDir,
|
|
|
|
artPaths: make(map[string]string),
|
|
|
|
}
|
|
|
|
}
|