slideshow/scanner/scanner.go

67 lines
1.6 KiB
Go
Raw Normal View History

package scanner
import (
"io/fs"
"math/rand"
"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 directories for images
func Initialize() {
directory := config.Directory
scan(directory)
}
// get a random image
func GetRandomImage() string {
return images[rand.Intn(len(images))]
}
// scan the specified directory
func scan(directory string) {
timestamp := time.Now().UnixMilli()
loggo.Info("scanning directory for images and subdirectories...", directory)
filepath.WalkDir(directory, checkDirectory)
images = tmpImages
tmpImages = nil
loggo.InfoTimed("found "+strconv.Itoa(len(images))+" image(s)", timestamp)
go scheduleRescan(directory)
}
// sleep the specified interval and then trigger a rescan of the specified directory
func scheduleRescan(directory string) {
loggo.Debug("sleeping for " + strconv.FormatInt(config.Interval.Milliseconds(), 10) + "ms before next scan...")
time.Sleep(config.ScanInterval)
scan(directory)
}
// 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")
}