roulette/cmd/files.go

265 lines
4.9 KiB
Go
Raw Normal View History

2022-09-08 15:57:59 +00:00
/*
Copyright © 2022 Seednode <seednode@seedno.de>
*/
package cmd
import (
"errors"
"fmt"
2022-09-08 15:57:59 +00:00
"math/rand"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
2022-09-08 15:57:59 +00:00
"time"
"github.com/h2non/filetype"
2022-09-08 15:57:59 +00:00
)
var (
ErrNoImagesFound = fmt.Errorf("no supported image formats found")
)
func appendPaths(m map[string][]string, path, filter string) (map[string][]string, error) {
absolutePath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
directory, _ := filepath.Split(absolutePath)
switch {
case filter != "" && strings.Contains(path, filter):
m[directory] = append(m[directory], path)
case filter == "":
m[directory] = append(m[directory], path)
}
return m, nil
}
func getFirstFile(path string) (string, error) {
re := regexp.MustCompile(`(.+)([0-9]{3})(\..+)`)
split := re.FindAllStringSubmatch(path, -1)
if len(split) < 1 || len(split[0]) < 3 {
return "", nil
}
base := split[0][1]
number := 1
extension := split[0][3]
fileName := fmt.Sprintf("%v%.3d%v", base, number, extension)
nextFile, err := checkNextFile(fileName)
if err != nil {
return "", err
}
if !nextFile {
return "", nil
}
return fileName, nil
}
func getNextFile(path string) (string, error) {
re := regexp.MustCompile(`(.+)([0-9]{3})(\..+)`)
split := re.FindAllStringSubmatch(path, -1)
2022-09-17 18:12:22 +00:00
if len(split) < 1 || len(split[0]) < 3 {
2022-09-17 17:42:25 +00:00
return "", nil
}
base := split[0][1]
number, err := strconv.Atoi(split[0][2])
if err != nil {
2022-09-17 17:42:25 +00:00
return "", err
}
extension := split[0][3]
incremented := number + 1
fileName := fmt.Sprintf("%v%.3d%v", base, incremented, extension)
nextFile, err := checkNextFile(fileName)
if err != nil {
return "", err
}
if !nextFile {
return "", nil
}
return fileName, nil
}
func checkNextFile(path string) (bool, error) {
_, err := os.Stat(path)
switch {
case err == nil:
return true, nil
case errors.Is(err, os.ErrNotExist):
return false, nil
default:
return false, err
}
}
func checkIfImage(path string) (bool, error) {
file, err := os.Open(path)
if err != nil {
return false, err
}
defer file.Close()
head := make([]byte, 261)
file.Read(head)
if filetype.IsImage(head) {
return true, nil
}
return false, nil
}
func getFiles(m map[string][]string, path, filter string) (map[string][]string, error) {
err := filepath.WalkDir(path, func(p string, info os.DirEntry, err error) error {
if err != nil {
return err
}
2022-09-08 20:30:51 +00:00
switch {
case !Recursive && info.IsDir() && p != path:
return filepath.SkipDir
case filter != "" && !info.IsDir():
m, err = appendPaths(m, p, filter)
if err != nil {
return err
}
case !info.IsDir():
m, err = appendPaths(m, p, "")
if err != nil {
return err
}
2022-09-08 17:12:58 +00:00
}
2022-09-08 17:12:58 +00:00
return err
})
if err != nil {
return nil, err
}
2022-09-08 17:12:58 +00:00
return m, nil
2022-09-08 17:12:58 +00:00
}
func getFileList(paths []string, filter string) (map[string][]string, error) {
fileMap := map[string][]string{}
var err error
2022-09-08 15:57:59 +00:00
for i := 0; i < len(paths); i++ {
fileMap, err = getFiles(fileMap, paths[i], filter)
if err != nil {
return nil, err
2022-09-08 17:12:58 +00:00
}
}
return fileMap, nil
}
func cleanFilename(filename string) string {
filename = filename[:len(filename)-(len(filepath.Ext(filename))+3)]
return filename
}
func prepareDirectory(directory []string) []string {
_, first := filepath.Split(directory[0])
first = cleanFilename(first)
_, last := filepath.Split(directory[len(directory)-1])
last = cleanFilename(last)
fmt.Printf("Comparing %v to %v\n", first, last)
if first == last {
d := append([]string{}, directory[0])
fmt.Printf("Appending %v to empty directory\n", d)
return d
} else {
fmt.Printf("Returning directory as-is\n")
return directory
2022-09-08 15:57:59 +00:00
}
}
2022-09-08 15:57:59 +00:00
func prepareDirectories(m map[string][]string, successive string) []string {
directories := []string{}
keys := make([]string, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
switch {
case successive != "":
for i := 0; i < len(keys); i++ {
directories = append(directories, prepareDirectory(m[keys[i]])...)
}
default:
for i := 0; i < len(keys); i++ {
directories = append(directories, m[keys[i]]...)
}
}
return directories
2022-09-08 17:12:58 +00:00
}
2022-09-08 15:57:59 +00:00
func pickFile(args []string, filter, successive string) (string, error) {
fileMap, err := getFileList(args, filter)
if err != nil {
return "", err
}
rand.Seed(time.Now().UnixNano())
fileList := prepareDirectories(fileMap, successive)
rand.Shuffle(len(fileList), func(i, j int) { fileList[i], fileList[j] = fileList[j], fileList[i] })
for i := 0; i < len(fileList); i++ {
filePath := fileList[i]
isImage, err := checkIfImage(filePath)
if err != nil {
return "", err
}
if isImage {
return filePath, nil
}
}
2022-09-08 17:12:58 +00:00
return "", ErrNoImagesFound
2022-09-08 20:30:51 +00:00
}
func normalizePaths(args []string) ([]string, error) {
2022-09-08 20:30:51 +00:00
var paths []string
for i := 0; i < len(args); i++ {
absolutePath, err := filepath.Abs(args[i])
if err != nil {
return nil, err
2022-09-08 20:30:51 +00:00
}
paths = append(paths, absolutePath)
}
return paths, nil
2022-09-08 15:57:59 +00:00
}