Add ability to clean up unused images

This commit is contained in:
Jason Streifling 2025-01-17 05:04:03 +01:00
parent 3d3cda319d
commit ff36d65cc3

View File

@ -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)
}
}