diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go index cb2e445..e1186e3 100644 --- a/internal/notifications/notifications.go +++ b/internal/notifications/notifications.go @@ -79,26 +79,36 @@ func getCachedProfileImage(avatarHash discord.Hash, url string) (string, error) return "", err } - path = filepath.Join(path, avatarHash+".png") - if _, err := os.Stat(path); err == nil { - return path, nil - } - - file, err := os.Create(path) + root, err := os.OpenRoot(path) if err != nil { + return "", fmt.Errorf("failed to open avatars dir: %w", err) + } + defer root.Close() + + filename := avatarHash + ".png" + _, err = root.Stat(filename) + switch { + case err == nil: + return filepath.Join(path, filename), nil + case os.IsNotExist(err): + file, err := root.Create(filename) + if err != nil { + return "", err + } + defer file.Close() + + resp, err := http.Get(url) + if err != nil { + return "", err + } + defer resp.Body.Close() + + if _, err := io.Copy(file, resp.Body); err != nil { + return "", err + } + + return file.Name(), nil + default: return "", err } - defer file.Close() - - resp, err := http.Get(url) - if err != nil { - return "", err - } - defer resp.Body.Close() - - if _, err := io.Copy(file, resp.Body); err != nil { - return "", err - } - - return path, nil } diff --git a/internal/ui/chat/messages_list.go b/internal/ui/chat/messages_list.go index c8b8c0f..c2edacc 100644 --- a/internal/ui/chat/messages_list.go +++ b/internal/ui/chat/messages_list.go @@ -1202,10 +1202,16 @@ func (ml *messagesList) openAttachment(attachment discord.Attachment) { return } - path = filepath.Join(path, attachment.Filename) - file, err := os.Create(path) + root, err := os.OpenRoot(path) if err != nil { - slog.Error("failed to create attachment file", "err", err, "path", path) + slog.Error("failed to open attachments dir", "err", err, "path", path) + return + } + defer root.Close() + + file, err := root.Create(attachment.Filename) + if err != nil { + slog.Error("failed to create attachment file", "err", err, "filename", attachment.Filename) return } defer file.Close() @@ -1215,8 +1221,8 @@ func (ml *messagesList) openAttachment(attachment discord.Attachment) { return } - if err := open.Start(path); err != nil { - slog.Error("failed to open attachment file", "err", err, "path", path) + if err := open.Start(file.Name()); err != nil { + slog.Error("failed to open attachment file", "err", err, "path", file.Name()) return } }