diff --git a/cmd/backend/images.go b/cmd/backend/images.go index 6a2619c..398e201 100644 --- a/cmd/backend/images.go +++ b/cmd/backend/images.go @@ -1,10 +1,16 @@ package backend import ( + "bufio" "fmt" "image" "io" + "io/fs" + "log" "os" + "path/filepath" + "strings" + "time" "github.com/chai2010/webp" "github.com/disintegration/imaging" @@ -30,7 +36,7 @@ func SaveImage(src io.Reader, maxHeight, maxWidth int, path string) (string, err } filename := fmt.Sprint(uuid.New(), ".webp") - file, err := os.Create(path + filename) + file, err := os.Create(filepath.Join(path, filename)) if err != nil { return "", fmt.Errorf("error creating new image file: %v", err) } @@ -42,3 +48,59 @@ func SaveImage(src io.Reader, maxHeight, maxWidth int, path string) (string, err return filename, nil } + +func CleanUpImages(c *Config) { + for { + if err := filepath.Walk(c.PicsDir, func(path string, info fs.FileInfo, err error) error { + if err != nil { + return err + } + + if !info.IsDir() { + imageName := info.Name() + absImageName := path + + if err = filepath.Walk(c.ArticleDir, func(path string, info fs.FileInfo, err error) error { + if err != nil { + return err + } + + if !info.IsDir() { + mdFile, err := os.Open(path) + if err != nil { + return err + } + defer mdFile.Close() + + scanner := bufio.NewScanner(mdFile) + imageWasFound := false + + for scanner.Scan() { + if strings.Contains(scanner.Text(), imageName) { + imageWasFound = true + } + } + + if !imageWasFound { + if err = os.Remove(absImageName); err != nil { + return err + } + } + + return scanner.Err() + } + + return nil + }); err != nil { + return err + } + } + + return nil + }); err != nil { + log.Println(err) + } + + time.Sleep(time.Hour) + } +}