slideshow-api/internal/scanner.go
2023-11-28 15:52:53 +01:00

81 lines
2 KiB
Go

package internal
import (
"errors"
"io/fs"
"math/rand"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"git.velvettear.de/velvettear/loggo"
"git.velvettear.de/velvettear/slideshow/internal/config"
)
// slice of images
var images []string
// temporary slice of images
var tmpImages []string
// Scan the specified directory
func Scan() {
timestamp := time.Now()
directory := config.Directory
loggo.Info("scanning directory for images and subdirectories...", "interval: "+strconv.FormatFloat(config.ScanInterval.Seconds(), 'f', 0, 64)+" seconds", "directory: "+directory)
filepath.WalkDir(directory, checkDirectory)
images = tmpImages
tmpImages = nil
loggo.InfoTimed("found "+strconv.Itoa(len(images))+" image(s)", timestamp.UnixMilli())
go scheduleRescan()
}
// check if images has been found
func HasFoundImages() bool {
return len(images) > 0
}
// get a random image
func GetRandomImage() (string, []byte, error) {
var name string
var data []byte
var error error
if len(images) == 0 {
return name, data, errors.New("no images have been found")
}
image := images[rand.Intn(len(images))]
if config.IsResolutionSet() {
data, error = ScaleImage(image)
} else {
data, error = os.ReadFile(image)
}
return image, data, error
}
// sleep the specified interval and then trigger a rescan of the specified directory
func scheduleRescan() {
loggo.Debug("sleeping for " + strconv.FormatInt(config.ScanInterval.Milliseconds(), 10) + "ms before next scan...")
time.Sleep(config.ScanInterval)
Scan()
}
// add image files to the slice of images and subdirectoies to the watcher
func checkDirectory(path string, dir fs.DirEntry, err error) error {
if err != nil {
return err
}
if dir.IsDir() || !isImage(path) {
return nil
}
tmpImages = append(tmpImages, path)
loggo.Debug("added image to temporary slice of images", path)
return nil
}
// check if a file is an image
func isImage(file string) bool {
return strings.HasSuffix(file, ".jpeg") || strings.HasSuffix(file, ".jpg") || strings.HasSuffix(file, ".png")
}