etheryo/backend/core/file.go

81 lines
1.7 KiB
Go

package core
import (
"backend/util"
"errors"
"io/fs"
"os"
"strings"
"time"
)
type PictureData struct {
Name string `json:"name"`
Date time.Time `json:"date"`
Album string `json:"album"`
}
var picd []PictureData
func listFiles(path string, actualdir string, picd []PictureData) []PictureData {
entries, err := os.ReadDir(path)
if err != nil {
util.Logformat(util.WARNING, "Could not read files in '%s'\n", path)
return picd
}
for _, entry := range entries {
info, err := entry.Info()
if err != nil {
continue
}
if info.IsDir() {
// fmt.Printf("\uf07b %s\n", entry.Name())
picd = listFiles(path+"/"+info.Name(), info.Name(), picd)
} else {
// fmt.Printf("\uf15b %s: %do\n", entry.Name(), info.Size())
picd = getFileInfo(info, picd, actualdir)
}
}
return picd
}
func isPicture(s string) bool {
extensions := []string{".jpg", ".jpeg", ".jfif", ".pjpeg", ".pjp", ".webp", ".png", ".apng", ".svg", ".avif"}
for _, ext := range extensions {
if strings.HasSuffix(s, ext) {
return true
}
}
return false
}
func getFileInfo(info fs.FileInfo, picd []PictureData, actualdir string) []PictureData {
if isPicture(info.Name()) {
picd = append(picd, PictureData{
Name: info.Name(),
Date: info.ModTime(),
Album: actualdir,
})
util.Logformatrn(util.INFO, "Reading %d files...", len(picd))
}
return picd
}
func ListFiles(path string) error {
start := time.Now()
picd = listFiles(path, "", picd)
if len(picd) == 0 {
return errors.New("ListFiles(): Could not gather any file")
} else {
elapsed := time.Since(start)
print("\n")
util.Logformat(util.CORRECT, "Gathered %d files in %dms.\n", len(picd), elapsed.Milliseconds())
return nil
}
}
func GetPictureData() []PictureData {
return picd
}