infoalloggi-monorepo/apps/backend/image_handler.go

101 lines
1.9 KiB
Go
Raw Normal View History

2025-08-04 17:45:44 +02:00
package main
import (
"backend/config"
"backend/queries"
"backend/typesdefs"
2025-08-04 17:45:44 +02:00
"fmt"
"log"
"os"
"path/filepath"
)
type ImageRefManager struct {
}
func NewImageRefManager() *ImageRefManager {
return &ImageRefManager{}
}
func (i *ImageRefManager) InsertImagesRef(annunci *typesdefs.AnnunciXML) error {
2025-08-04 17:45:44 +02:00
return queries.ImagesBatchInsert(annunci)
2025-08-04 17:45:44 +02:00
}
func (i *ImageRefManager) FindIsUpdate(annunci *typesdefs.AnnunciXML) ([]string, error) {
r, err := queries.ImagesGetAll()
2025-08-04 17:45:44 +02:00
if err != nil {
return nil, err
}
refMap := make(map[string][]string) // Convert slice to map for faster lookup
for _, ref := range r {
if ref.Foto != nil {
refMap[ref.Codice] = *ref.Foto
}
}
var result []string
for _, annuncio := range annunci.Annuncio {
if annuncio.Codice != nil && annuncio.Foto != nil {
refFoto, exists := refMap[*annuncio.Codice]
if !exists {
fmt.Println("new codice", *annuncio.Codice)
result = append(result, *annuncio.Codice)
continue
}
if len(*annuncio.Foto) != len(refFoto) {
fmt.Println("Different length", *annuncio.Foto, refFoto)
result = append(result, *annuncio.Codice)
continue
}
for i, foto := range *annuncio.Foto {
if foto != refFoto[i] {
fmt.Println("Different content", *annuncio.Foto, refFoto)
result = append(result, *annuncio.Codice)
break
}
}
}
}
return result, nil
}
func (i *ImageRefManager) ClearImages(to_clear []string) error {
for _, codice := range to_clear {
folder := filepath.Join(config.Cfg.Images.Path, codice)
2025-08-04 17:45:44 +02:00
err := os.RemoveAll(folder)
if err != nil {
return err
}
}
return nil
}
func (i *ImageRefManager) Reset() error {
err := queries.ImagesClear()
2025-08-04 17:45:44 +02:00
if err != nil {
return err
}
err = queries.AnnunciResetImages()
2025-08-04 17:45:44 +02:00
if err != nil {
return err
}
err = os.RemoveAll(config.Cfg.Images.Path)
2025-08-04 17:45:44 +02:00
if err != nil {
log.Fatal(err)
}
err = os.Mkdir(config.Cfg.Images.Path, 0755)
2025-08-04 17:45:44 +02:00
if err != nil {
log.Fatal(err)
}
return nil
}