gopaper/files.go

49 lines
1.1 KiB
Go

package main
import (
"log"
"math/rand"
"os"
"regexp"
)
func getRandomFile(dir string) (path string, filename string, error error) {
files, err := os.ReadDir(dir)
if err != nil {
return "", "", err
}
var randomIndex int
var randomImg os.DirEntry
for {
randomIndex = rand.Intn(len(files))
randomImg = files[randomIndex]
//re-roll if you get a directory
if files[randomIndex].IsDir() {
log.Printf("%v is a directory. Trying again... \n", randomImg.Name())
continue
}
//re-roll if not a recognised image type
isImage, _ := regexp.Match(".jpg$|.jpeg$|.png$|.bmp$|.webp$", []byte(randomImg.Name()))
if !isImage {
log.Printf("%v is not a recognised image format\n", randomImg.Name())
continue
}
//TODO: re-roll if you get the same image
return dir + "/" + randomImg.Name(), randomImg.Name(), nil
}
}
func fileExistsInCache(filename string) (bool, error) {
files, err := os.ReadDir(config.Cache)
if err != nil {
return false, err
}
for _, file := range files {
if file.Name() == filename {
return true, nil
}
}
return false, nil
}