Better Way of Caching

Instead of Caching by maintaining a cache file as mentioned here https://github.com/aditya-K2/goMP/issues/14#issuecomment-989141798
We can directly check if the file exists if it exists then we can just
pass the path to it else we can copy the default image to the path of
the imagePath
This commit is contained in:
aditya-K2 2021-12-09 02:25:46 +05:30
parent e6f30f4081
commit 4d55f233d0

60
cache/cache.go vendored
View File

@ -3,70 +3,30 @@ package cache
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"strings" "strings"
) )
var ( var (
USER_CACHE_DIR, err = os.UserCacheDir() CACHE_DIR string
CACHE_LIST map[[2]string]string = make(map[[2]string]string) DEFAULT_IMG string
CACHE_DIR string = USER_CACHE_DIR
DEFAULT_IMG string
) )
func SetCacheDir(path string) { func SetCacheDir(path string) {
CACHE_DIR = path CACHE_DIR = path
} }
func SetDefaultPath(path string) { func Exists(artist, album string) bool {
DEFAULT_IMG = path if _, err := os.Stat(GenerateName(artist, album)); errors.Is(err, os.ErrNotExist) {
} return false
func LoadCache(path string) error {
cacheFileContent, err := ioutil.ReadFile(path)
if err != nil {
return errors.New("Could Not Read From Cache File")
}
lineSlice := strings.Split(string(cacheFileContent), "\n")
for _, line := range lineSlice {
if len(line) != 0 {
param := strings.Split(line, "\t")
if len(param) == 3 {
CACHE_LIST[[2]string{param[0], param[1]}] = param[2]
}
}
}
return nil
}
func GetFromCache(artist, album string) (string, error) {
if val, ok := CACHE_LIST[[2]string{artist, album}]; ok {
return val, nil
} else { } else {
return "", errors.New("Element Not In Cache") return true
}
}
func PointToDefault(artist, album string) {
CACHE_LIST[[2]string{artist, album}] = DEFAULT_IMG
}
func AddToCache(artist, album string) string {
fileName := CACHE_DIR + GenerateName(artist, album)
CACHE_LIST[[2]string{artist, album}] = fileName
return fileName
}
func WriteCache(path string) {
b, err := os.Create(path)
if err == nil {
for k, v := range CACHE_LIST {
b.Write([]byte(fmt.Sprintf("%s\t%s\t%s\n", k[0], k[1], v)))
}
} }
} }
func GenerateName(artist, album string) string { func GenerateName(artist, album string) string {
return strings.Replace(strings.Replace(fmt.Sprintf("%s-%s.jpg", artist, album), " ", "_", -1), "/", "_", -1) if (artist == "" && album == "") || (artist == " " && album == " ") {
return CACHE_DIR + "UnknownArtist-UnknownAlbum.jpg"
}
return CACHE_DIR + strings.Replace(strings.Replace(fmt.Sprintf("%s-%s.jpg", artist, album), " ", "_", -1), "/", "_", -1)
} }