etheryo/backend/core/file.go

119 lines
3 KiB
Go

package core
import (
"backend/util"
"encoding/json"
"errors"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"time"
)
type PictureData struct {
Name string `json:"name"`
Date time.Time `json:"date"`
Album string `json:"album"`
URL string `json:"url"`
URLCompressed string `json:"urlcompressed"`
Title string `json:"title"`
Localisation string `json:"localisation"`
Description string `json:"description"`
}
type PictureJson struct {
Title string `json:"title"`
Localisation string `json:"localisation"`
Description string `json:"description"`
}
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() && !util.StringInSlice(info.Name(), util.GetConfig().IgnoreFolder) {
// 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(path, 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(path string, info fs.FileInfo, picd []PictureData, actualdir string) []PictureData {
if isPicture(info.Name()) {
title := strings.TrimSuffix(info.Name(), filepath.Ext(info.Name()))
file, err := os.Open(filepath.Join(path, title+".json"))
var pictureinfo PictureJson
if err == nil {
decoder := json.NewDecoder(file)
decoder.DisallowUnknownFields()
decoder.Decode(&pictureinfo)
}
defer file.Close()
// Setting parameters
if pictureinfo.Title != "" {
title = pictureinfo.Title
}
picd = append(picd, PictureData{
Name: info.Name(),
Date: info.ModTime(),
Album: actualdir,
URL: "http://localhost:8085/photo/" + actualdir + "/" + info.Name(),
Title: title,
Localisation: pictureinfo.Localisation,
Description: pictureinfo.Description,
})
util.Logformatrn(util.INFO, "Reading %d files...", len(picd))
}
// Ordering by most recent
sort.Slice(picd, func(i, j int) bool {
return picd[i].Date.After(picd[j].Date) // descending: newer dates first
})
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
}