Backend: Added multiple endpoints to gather pictures: both uncompressed and compressed.

This commit is contained in:
Yohan Boujon 2025-06-01 12:41:59 +02:00
parent a810fcbd76
commit 64818f0970
5 changed files with 94 additions and 30 deletions

View file

@ -5,14 +5,20 @@ import (
"errors" "errors"
"io/fs" "io/fs"
"os" "os"
"path/filepath"
"strings" "strings"
"time" "time"
) )
type PictureData struct { type PictureData struct {
Name string `json:"name"` Name string `json:"name"`
Date time.Time `json:"date"` Date time.Time `json:"date"`
Album string `json:"album"` Album string `json:"album"`
URL string `json:"url"`
URLCompressed string `json:"urlcompressed"`
Title string `json:"title"`
Localisation string `json:"localisation"`
Description string `json:"description"`
} }
var picd []PictureData var picd []PictureData
@ -53,9 +59,12 @@ func isPicture(s string) bool {
func getFileInfo(info fs.FileInfo, picd []PictureData, actualdir string) []PictureData { func getFileInfo(info fs.FileInfo, picd []PictureData, actualdir string) []PictureData {
if isPicture(info.Name()) { if isPicture(info.Name()) {
picd = append(picd, PictureData{ picd = append(picd, PictureData{
Name: info.Name(), Name: info.Name(),
Date: info.ModTime(), Date: info.ModTime(),
Album: actualdir, Album: actualdir,
URL: "http://localhost:8085/photo/" + actualdir + "/" + info.Name(),
Title: strings.TrimSuffix(info.Name(), filepath.Ext(info.Name())),
Localisation: "Paris, France",
}) })
util.Logformatrn(util.INFO, "Reading %d files...", len(picd)) util.Logformatrn(util.INFO, "Reading %d files...", len(picd))
} }

View file

@ -13,27 +13,35 @@ import (
"github.com/disintegration/imaging" "github.com/disintegration/imaging"
) )
func CompressImage(path string, name string) error { func CompressImage(path string, name string) (string, error) {
// Gathering base folder
basedir, err := os.Getwd()
if err != nil {
return "", err
}
name = name + "_compressed.jpeg"
basedir = filepath.Join(basedir, ".temp", name)
// Creating folder // Creating folder
if err := os.MkdirAll(".temp", 0755); err != nil { if err := os.MkdirAll(".temp", 0755); err != nil {
return err return "", err
} }
// Checking output file // Checking output file
if _, err := os.Stat(".temp/" + name + "_compressed.jpeg"); err == nil { if _, err := os.Stat(basedir); err == nil {
return errors.New("file already created") return name, errors.New("file already created")
} }
// Create file // Create file
outputFile, err := os.Create(".temp/" + name + "_compressed.jpeg") outputFile, err := os.Create(basedir)
if err != nil { if err != nil {
return err return "", err
} }
defer outputFile.Close() defer outputFile.Close()
// Opening image + Reducing its size and quality // Opening image + Reducing its size and quality
img, err := imaging.Open(path) img, err := imaging.Open(path)
if err != nil { if err != nil {
return err return "", err
} }
width := float64(img.Bounds().Dx()) width := float64(img.Bounds().Dx())
height := float64(img.Bounds().Dy()) height := float64(img.Bounds().Dy())
@ -41,33 +49,36 @@ func CompressImage(path string, name string) error {
var imgOutput *image.NRGBA var imgOutput *image.NRGBA
if width < height { if width < height {
ratio = height / width ratio = height / width
imgOutput = imaging.Resize(img, 283, int(283*ratio), imaging.Lanczos) imgOutput = imaging.Resize(img, 320, int(320*ratio), imaging.Lanczos)
} else { } else {
ratio = width / height ratio = width / height
imgOutput = imaging.Resize(img, int(283*ratio), 283, imaging.Lanczos) imgOutput = imaging.Resize(img, int(320*ratio), 320, imaging.Lanczos)
} }
// Encoding to jpeg afterwards // Encoding to jpeg afterwards
if err := jpeg.Encode(outputFile, imgOutput, &jpeg.Options{Quality: 30}); err != nil { if err := jpeg.Encode(outputFile, imgOutput, &jpeg.Options{Quality: 100}); err != nil {
return err return "", err
} }
return nil return name, nil
} }
func CompressFiles(basePath string) { func CompressFiles(basePath string) {
picd := GetPictureData() picd := GetPictureData()
count := 0 count := 0
start := time.Now() start := time.Now()
for _, p := range picd { for i := range picd {
path := basePath + "/" + p.Album + "/" + p.Name path := filepath.Join(basePath, picd[i].Album, picd[i].Name)
name := strings.TrimSuffix(p.Name, filepath.Ext(p.Name)) name := strings.TrimSuffix(picd[i].Name, filepath.Ext(picd[i].Name))
err := CompressImage(path, name) compressed_name, err := CompressImage(path, name)
if err != nil { if err != nil {
if strings.Compare(err.Error(), "file already created") != 0 { if strings.Compare(err.Error(), "file already created") != 0 {
util.Logformat(util.WARNING, "Failed to compress '%s' : (%v)\n", p.Name, err) util.Logformat(util.WARNING, "Failed to compress '%s' : (%v)\n", picd[i].Name, err)
} else {
picd[i].URLCompressed = "http://localhost:8085/photo_compressed/" + compressed_name
} }
} else { } else {
util.Logformatrn(util.INFO, "Compressing %d files...", count) util.Logformatrn(util.INFO, "Compressing %d files...", count)
picd[i].URLCompressed = "http://localhost:8085/photo_compressed/" + compressed_name
count++ count++
} }
} }

View file

@ -6,7 +6,7 @@ import (
"net/http" "net/http"
) )
func getphoto(w http.ResponseWriter, r *http.Request) { func getphotolist(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" { if r.Method != "GET" {
util.Logformat(util.ERROR, "%s: Only GET is accepted (%s received)", util.GetFunctionName(), r.Method) util.Logformat(util.ERROR, "%s: Only GET is accepted (%s received)", util.GetFunctionName(), r.Method)
http.Error(w, "Only GET method is accepted", http.StatusBadRequest) http.Error(w, "Only GET method is accepted", http.StatusBadRequest)
@ -14,3 +14,23 @@ func getphoto(w http.ResponseWriter, r *http.Request) {
sendResponse(w, core.GetPictureData()) sendResponse(w, core.GetPictureData())
} }
} }
func getphoto(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
util.Logformat(util.ERROR, "%s: Only GET is accepted (%s received)", util.GetFunctionName(), r.Method)
http.Error(w, "Only GET method is accepted", http.StatusBadRequest)
} else {
util_config := util.GetConfig()
http.StripPrefix("/photo/", http.FileServer(http.Dir(util_config.PhotoPath))).ServeHTTP(w, r)
}
}
func getphoto_compressed(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
util.Logformat(util.ERROR, "%s: Only GET is accepted (%s received)", util.GetFunctionName(), r.Method)
http.Error(w, "Only GET method is accepted", http.StatusBadRequest)
} else {
util_config := util.GetConfig()
http.StripPrefix("/photo_compressed/", http.FileServer(http.Dir(util_config.PhotoCompressPath))).ServeHTTP(w, r)
}
}

View file

@ -9,7 +9,9 @@ import (
func Start(port int64) { func Start(port int64) {
// Creating endpoints // Creating endpoints
http.HandleFunc("/photo", wrapHeader(getphoto)) http.HandleFunc("/photo_list", wrapHeader(getphotolist))
http.HandleFunc("/photo/", wrapHeader(getphoto))
http.HandleFunc("/photo_compressed/", wrapHeader(getphoto_compressed))
util.Logformat(util.INFO, "Starting server on port %d...\n", port) util.Logformat(util.INFO, "Starting server on port %d...\n", port)
if err := http.ListenAndServe(":"+strconv.FormatInt(port, 10), nil); err != nil { if err := http.ListenAndServe(":"+strconv.FormatInt(port, 10), nil); err != nil {

View file

@ -4,24 +4,46 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"os" "os"
"path/filepath"
) )
type Config struct { type ConfigJSON struct {
PhotoPath string PhotoPath string
} }
type Config struct {
PhotoPath string
PhotoCompressPath string
}
var main_config Config
func GetConfig() Config {
return main_config
}
func ReadConfig(path string) (Config, error) { func ReadConfig(path string) (Config, error) {
var cfg Config var cfg ConfigJSON
// Gathering temp folder
basedir, err := os.Getwd()
if err != nil {
return main_config, err
}
main_config.PhotoCompressPath = filepath.Join(basedir, ".temp")
// Gathering photo path
file, err := os.Open(path) file, err := os.Open(path)
if err != nil { if err != nil {
return cfg, err return main_config, err
} }
defer file.Close() defer file.Close()
decoder := json.NewDecoder(file) decoder := json.NewDecoder(file)
decoder.DisallowUnknownFields() decoder.DisallowUnknownFields()
err = decoder.Decode(&cfg) err = decoder.Decode(&cfg)
return cfg, err main_config.PhotoPath = cfg.PhotoPath
return main_config, err
} }
func createConfigFile(cfg Config) { func createConfigFile(cfg Config) {