package backend import ( "bufio" "fmt" "image" "io" "io/fs" "log" "os" "path/filepath" "strings" "time" "github.com/chai2010/webp" "github.com/disintegration/imaging" "github.com/google/uuid" ) var ErrUnsupportedFormat error = image.ErrFormat // used internally by imaging func SaveImage(src io.Reader, maxHeight, maxWidth int, path string) (string, error) { img, err := imaging.Decode(src, imaging.AutoOrientation(true)) if err != nil { if err == ErrUnsupportedFormat { return "", ErrUnsupportedFormat } return "", fmt.Errorf("error decoding image: %v", err) } if img.Bounds().Dy() > maxHeight { img = imaging.Resize(img, 0, maxHeight, imaging.Lanczos) } if img.Bounds().Dx() > maxWidth { img = imaging.Resize(img, maxWidth, 0, imaging.Lanczos) } filename := fmt.Sprint(uuid.New(), ".webp") file, err := os.Create(filepath.Join(path, filename)) if err != nil { return "", fmt.Errorf("error creating new image file: %v", err) } defer file.Close() if err = webp.Encode(file, img, &webp.Options{Quality: 80}); err != nil { return "", fmt.Errorf("error encoding image as webp: %v", 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) } }