From 3d08cc7612a27b2245845f0bf5d6b5a435c3bac9 Mon Sep 17 00:00:00 2001 From: Jason Streifling Date: Mon, 20 Jan 2025 20:25:50 +0100 Subject: [PATCH] Make background image check way more efficient --- cmd/backend/images.go | 86 ++++++++++++++++++++++++------------------- 1 file changed, 49 insertions(+), 37 deletions(-) diff --git a/cmd/backend/images.go b/cmd/backend/images.go index 861f5d4..f7c5160 100644 --- a/cmd/backend/images.go +++ b/cmd/backend/images.go @@ -17,6 +17,53 @@ import ( var ErrUnsupportedFormat error = image.ErrFormat // used internally by imaging +func checkImageUsage(c *Config, db *DB, name string) (bool, error) { + imageWasFound := false + + if err := filepath.Walk(c.ArticleDir, func(path string, info fs.FileInfo, err error) error { + if err != nil { + return fmt.Errorf("error walking articles filepath: %v", err) + } + + if !info.IsDir() { + mdFile, err := os.Open(path) + if err != nil { + return fmt.Errorf("error opening article %v: %v", info.Name(), err) + } + defer mdFile.Close() + + scanner := bufio.NewScanner(mdFile) + for scanner.Scan() { + if strings.Contains(scanner.Text(), name) { + imageWasFound = true + return nil + } + } + + return scanner.Err() + } + + return nil + }); err != nil { + return false, fmt.Errorf("error walking articles filepath: %v", err) + } + + if !imageWasFound { + users, err := db.GetAllUsers(c) + if err != nil { + return false, fmt.Errorf("error getting all users: %v", err) + } + + for _, user := range users { + if name == user.ProfilePicLink { + return true, nil + } + } + } + + return imageWasFound, nil +} + func SaveImage(src io.Reader, maxHeight, maxWidth int, path string) (string, error) { img, err := imaging.Decode(src, imaging.AutoOrientation(true)) if err != nil { @@ -56,45 +103,10 @@ func CleanUpImages(c *Config, db *DB) error { if !info.IsDir() { imageName := info.Name() imagePath := path - imageWasFound := false - if err = filepath.Walk(c.ArticleDir, func(path string, info fs.FileInfo, err error) error { - if err != nil { - return fmt.Errorf("error walking articles filepath: %v", err) - } - - if !info.IsDir() { - mdFile, err := os.Open(path) - if err != nil { - return fmt.Errorf("error opening article %v: %v", info.Name(), err) - } - defer mdFile.Close() - - scanner := bufio.NewScanner(mdFile) - - for scanner.Scan() { - if strings.Contains(scanner.Text(), imageName) { - imageWasFound = true - } - } - - return scanner.Err() - } - - return nil - }); err != nil { - return fmt.Errorf("error walking articles filepath: %v", err) - } - - users, err := db.GetAllUsers(c) + imageWasFound, err := checkImageUsage(c, db, imageName) if err != nil { - return fmt.Errorf("error getting all users: %v", err) - } - - for _, user := range users { - if imageName == user.ProfilePicLink { - imageWasFound = true - } + return fmt.Errorf("error checking image usage: %v", err) } if !imageWasFound {