2023-11-23 16:57:43 +01:00
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 ( )
2023-11-24 09:57:48 +01:00
loggo . Info ( "scanning directory for images and subdirectories..." , "interval: " + strconv . FormatFloat ( config . ScanInterval . Seconds ( ) , 'f' , 0 , 64 ) + " seconds" , "directory: " + directory )
2023-11-23 16:57:43 +01:00
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 ) {
2023-11-23 17:08:06 +01:00
loggo . Debug ( "sleeping for " + strconv . FormatInt ( config . ScanInterval . Milliseconds ( ) , 10 ) + "ms before next scan..." )
2023-11-23 16:57:43 +01:00
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" )
}