shelfy-v2/internal/utils/lib.go
2025-08-18 21:34:13 +02:00

82 lines
2.0 KiB
Go

package utils
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"gorm.io/gorm"
"canguidev/shelfy/internal/models"
)
func CreateDefaultFolder(db *gorm.DB) {
type item struct {
Name string
}
defs := []item{
{Name: "Film"},
{Name: "Série"},
{Name: "Manga"},
{Name: "Magazine"},
}
for _, it := range defs {
path := filepath.Join("upload", it.Name)
// 1) Dossier : on s'assure qu'il existe
if err := os.MkdirAll(path, 0o755); err != nil {
log.Printf("[FOLDER] Erreur création '%s' : %v", path, err)
continue
}
// 2) Base : chercher une ligne existante par path OU path_name
var existing models.PathDownload
err := db.Where("path = ? OR path_name = ?", path, it.Name).First(&existing).Error
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
// 2a) Pas trouvé -> on crée
row := models.PathDownload{
Path: path,
PathName: it.Name,
}
if err := db.Create(&row).Error; err != nil {
log.Printf("[DB] Échec création PathDownload(%s, %s) : %v", path, it.Name, err)
} else {
log.Printf("[DB] Ligne créée PathDownload id=%v (%s | %s)", row.ID, row.PathName, row.Path)
}
case err != nil:
// 2b) Erreur DB
log.Printf("[DB] Erreur recherche PathDownload(%s | %s) : %v", path, it.Name, err)
default:
// 2c) Trouvé -> on normalise si besoin
updates := map[string]interface{}{}
if existing.Path != path {
updates["path"] = path
}
if existing.PathName != it.Name {
updates["path_name"] = it.Name
}
if len(updates) > 0 {
if err := db.Model(&existing).Updates(updates).Error; err != nil {
log.Printf("[DB] Échec mise à jour PathDownload id=%v : %v", existing.ID, err)
} else {
log.Printf("[DB] Mis à jour PathDownload id=%v -> %#v", existing.ID, updates)
}
} else {
log.Printf("[DB] OK PathDownload id=%v déjà synchro (%s | %s)", existing.ID, existing.PathName, existing.Path)
}
}
// 3) (Facultatif) log côté fichiers
if fi, err := os.Stat(path); err == nil && fi.IsDir() {
fmt.Printf("[FOLDER] OK : %s\n", path)
}
}
}