Improve avatar cache handling by adding fallback directory creation and enhancing read logic
This commit is contained in:
@@ -65,32 +65,50 @@ func avatarCachePath(cfg *config.Config, userID string, ext string) string {
|
||||
}
|
||||
|
||||
func writeAvatarCache(cfg *config.Config, userID string, ext string, data []byte) error {
|
||||
p := avatarCachePath(cfg, userID, ext)
|
||||
return os.WriteFile(p, data, 0644)
|
||||
}
|
||||
|
||||
func readAvatarCache(cfg *config.Config, userID string) ([]byte, string, error) {
|
||||
dir := cfg.AvatarCacheDir
|
||||
if dir == "" {
|
||||
dir = "/var/cache/b0esche/avatars"
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
// Try to create the directory; if it fails, fall back to temp dir
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
fmt.Printf("[WARN] failed to create avatar cache dir %s: %v; trying fallback to tmp dir\n", dir, err)
|
||||
fallback := filepath.Join(os.TempDir(), "b0esche_avatars")
|
||||
if err2 := os.MkdirAll(fallback, 0755); err2 != nil {
|
||||
return fmt.Errorf("failed to create avatar cache dir: %v; fallback failed: %v", err, err2)
|
||||
}
|
||||
dir = fallback
|
||||
}
|
||||
for _, e := range entries {
|
||||
if strings.HasPrefix(e.Name(), userID+".") {
|
||||
p := filepath.Join(dir, e.Name())
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
p := filepath.Join(dir, fmt.Sprintf("%s%s", userID, ext))
|
||||
return os.WriteFile(p, data, 0644)
|
||||
}
|
||||
|
||||
func readAvatarCache(cfg *config.Config, userID string) ([]byte, string, error) {
|
||||
checkDirs := []string{cfg.AvatarCacheDir}
|
||||
if checkDirs[0] == "" {
|
||||
checkDirs[0] = "/var/cache/b0esche/avatars"
|
||||
}
|
||||
// Also check fallback tmp dir
|
||||
checkDirs = append(checkDirs, filepath.Join(os.TempDir(), "b0esche_avatars"))
|
||||
|
||||
for _, dir := range checkDirs {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, e := range entries {
|
||||
if strings.HasPrefix(e.Name(), userID+".") {
|
||||
p := filepath.Join(dir, e.Name())
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
ext := filepath.Ext(e.Name())
|
||||
ct := mime.TypeByExtension(ext)
|
||||
if ct == "" {
|
||||
ct = "application/octet-stream"
|
||||
}
|
||||
return b, ct, nil
|
||||
}
|
||||
ext := filepath.Ext(e.Name())
|
||||
ct := mime.TypeByExtension(ext)
|
||||
if ct == "" {
|
||||
ct = "application/octet-stream"
|
||||
}
|
||||
return b, ct, nil
|
||||
}
|
||||
}
|
||||
return nil, "", fmt.Errorf("cache miss")
|
||||
|
||||
Reference in New Issue
Block a user