From 1940fde7cc279951e0921e7447282eb0a1979e76 Mon Sep 17 00:00:00 2001 From: cangui Date: Mon, 18 Aug 2025 21:45:27 +0200 Subject: [PATCH] up --- internal/utils/lib.go | 58 ++++++++++++++++++++----------------------- 1 file changed, 27 insertions(+), 31 deletions(-) diff --git a/internal/utils/lib.go b/internal/utils/lib.go index 9f8744f..ada5659 100644 --- a/internal/utils/lib.go +++ b/internal/utils/lib.go @@ -13,25 +13,26 @@ import ( "canguidev/shelfy/internal/models" ) +// Synchronise le disque avec la base : Film, Série, Manga, Magazine. +// - Disque : crée "upload/" si manquant +// - DB : 1 ligne unique par nom (Path="", PathName="") func CreateDefaultFolder(db *gorm.DB) { - // noms “logiques” attendus en base targets := []string{"Film", "Série", "Manga", "Magazine"} - // 0) Nettoyage global : si des lignes ont path "upload/XXX", on les normalise en "XXX" + // 0) Normalise les entrées existantes (upload/X -> X) et dédoublonne if err := normalizeExistingPaths(db); err != nil { - log.Printf("[DB] Warning: normalisation initiale partielle: %v", err) + log.Printf("[DB] Avertissement: normalisation partielle: %v", err) } for _, name := range targets { - diskPath := filepath.Join("upload", name) // répertoire physique - // 1) Toujours créer le dossier physique + // 1) Dossier physique + diskPath := filepath.Join("upload", name) if err := os.MkdirAll(diskPath, 0o755); err != nil { log.Printf("[FOLDER] Erreur création '%s' : %v", diskPath, err) continue } - // 2) En base : on veut UNE ligne unique avec Path=Name et PathName=Name - // On cherche tout ce qui pourrait correspondre à ce nom (avec ou sans "upload/") + // 2) DB : cherche toute ligne liée à ce nom (avec/ sans 'upload/') var rows []models.PathDownload if err := db.Where("path = ? OR path = ? OR path_name = ? OR path_name = ?", name, "upload/"+name, name, "upload/"+name, @@ -42,20 +43,17 @@ func CreateDefaultFolder(db *gorm.DB) { switch len(rows) { case 0: - // 2a) Rien trouvé → créer la ligne normalisée + // crée proprement row := models.PathDownload{Path: name, PathName: name} if err := db.Create(&row).Error; err != nil { log.Printf("[DB] Création PathDownload('%s') KO : %v", name, err) } else { log.Printf("[DB] Créé PathDownload id=%v (%s)", row.ID, name) } - default: - // 2b) On a des lignes → on les normalise et on garde une seule - // 1) mettre à jour la première ligne en Path=Name, PathName=Name + // garde la première, normalise, supprime doublons main := rows[0] - needUpdate := (main.Path != name) || (main.PathName != name) - if needUpdate { + if main.Path != name || main.PathName != name { if err := db.Model(&main).Updates(map[string]any{ "path": name, "path_name": name, @@ -65,14 +63,12 @@ func CreateDefaultFolder(db *gorm.DB) { log.Printf("[DB] Normalisé id=%v -> (%s|%s)", main.ID, name, name) } } - - // 2) supprimer les doublons résiduels (même nom logique) if len(rows) > 1 { - var dupIDs []uint + var dupIDs []int64 for _, r := range rows[1:] { - dupIDs = append(dupIDs, r.ID) + dupIDs = append(dupIDs, r.ID) // ID en int64 } - if err := db.Where("id IN ?", dupIDs).Delete(&models.PathDownload{}).Error; err != nil { + if err := db.Where("id IN ?", dupIDs).Delete(&models.PathDownload{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { log.Printf("[DB] Suppression doublons (%v) KO : %v", dupIDs, err) } else { log.Printf("[DB] Doublons supprimés pour '%s' : %v", name, dupIDs) @@ -84,16 +80,14 @@ func CreateDefaultFolder(db *gorm.DB) { } } -// normalizeExistingPaths met à jour toutes les lignes dont path commence par "upload/" -// en supprimant ce préfixe, et aligne path_name si nécessaire. Elle supprime aussi -// d’éventuels doublons créés par cette normalisation. +// Met à jour toutes les lignes path="upload/..." -> path="...", +// aligne path_name si nécessaire, puis supprime les doublons. func normalizeExistingPaths(db *gorm.DB) error { - // 1) Récupérer les lignes impactées + // 1) Normalisation des paths var rows []models.PathDownload if err := db.Where("path LIKE ?", "upload/%").Find(&rows).Error; err != nil { return err } - for _, r := range rows { trimmed := strings.TrimPrefix(r.Path, "upload/") updates := map[string]any{"path": trimmed} @@ -105,22 +99,24 @@ func normalizeExistingPaths(db *gorm.DB) error { } } - // 2) Éliminer d’éventuels doublons (même path normalisé), on garde le plus petit id + // 2) Déduplication par path (on garde le plus petit id) type rec struct { - ID uint + ID int64 // <-- int64 Path string } var all []rec - if err := db.Model(&models.PathDownload{}).Select("id, path").Order("path, id").Scan(&all).Error; err != nil { + if err := db.Model(&models.PathDownload{}). + Select("id, path"). + Order("path, id"). + Scan(&all).Error; err != nil { return err } - seen := make(map[string]uint) - var dupIDs []uint + + seen := make(map[string]int64) + var dupIDs []int64 for _, r := range all { - if keep, ok := seen[r.Path]; ok { - // doublon : on marque pour suppression + if _, ok := seen[r.Path]; ok { dupIDs = append(dupIDs, r.ID) - _ = keep } else { seen[r.Path] = r.ID }