slideshow/internal/watcher/watcher.go
2023-11-16 15:26:24 +01:00

89 lines
2.1 KiB
Go

package watcher
import (
"io/fs"
"math/rand"
"path/filepath"
"strconv"
"strings"
"time"
"git.velvettear.de/velvettear/loggo"
"github.com/fsnotify/fsnotify"
)
// the watcher
var watcher *fsnotify.Watcher
// slice of images
var images []string
// initialize the watcher
func Initialize(directory string) {
timestamp := time.Now().UnixMilli()
tmp, error := fsnotify.NewWatcher()
if error != nil {
loggo.FatalTimed("encountered an error initializing the watcher", timestamp, error.Error())
}
watcher = tmp
loggo.Info("scanning directory for images and subdirectories...", directory)
filepath.WalkDir(directory, checkDirectory)
loggo.InfoTimed("found "+strconv.Itoa(len(images))+" images "+strconv.Itoa(len(watcher.WatchList()))+" directories to watch", timestamp)
go func() {
for {
event := <-watcher.Events
if !isImage(event.Name) {
continue
}
if event.Has(fsnotify.Create) {
images = append(images, event.Name)
loggo.Debug("added image to slice of images", event.Name)
} else if event.Has(fsnotify.Remove) {
for index, tmp := range images {
if tmp != event.Name {
continue
}
images = append(images[:index], images[index+1:]...)
loggo.Debug("removed image from slice of images", event.Name)
}
}
}
}()
}
// stop the watcher
func Stop() {
error := watcher.Close()
if error != nil {
loggo.Fatal("encountered an error closing the watcher", error.Error())
}
}
// get a random image
func GetRandomImage() string {
return images[rand.Intn(len(images))]
}
// 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() {
watcher.Add(path)
loggo.Debug("added directory to watcher", path)
return nil
}
if !isImage(path) {
return nil
}
images = append(images, path)
loggo.Debug("added image to 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")
}