From 07975c4fbe6a6bf9097ffbb3eb12e53cba91f74f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20B=C3=B6sche?= Date: Thu, 29 Jan 2026 23:12:12 +0100 Subject: [PATCH] Improve avatar cache handling by adding fallback directory creation and enhancing read logic --- go_cloud/internal/http/routes.go | 58 +++++++++++++++++++++----------- 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/go_cloud/internal/http/routes.go b/go_cloud/internal/http/routes.go index 40c8c9c..93333da 100644 --- a/go_cloud/internal/http/routes.go +++ b/go_cloud/internal/http/routes.go @@ -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")