Actualiser js/admin.js
This commit is contained in:
+54
-73
@@ -5,19 +5,14 @@
|
||||
* =========================================================================
|
||||
*/
|
||||
|
||||
// ── PARSEUR CSV UNIVERSEL (Robuste & Hybride) ──
|
||||
/**
|
||||
* Analyse une chaîne de caractères CSV de manière flexible.
|
||||
* Détecte automatiquement si le séparateur principal est une virgule ou un point-virgule.
|
||||
* Gère correctement les sauts de ligne internes et le double-échappement des guillemets.
|
||||
*/
|
||||
// ── PARSEUR CSV UNIVERSEL (Gestion avancée des guillemets et séparateurs) ──
|
||||
function parseFlexibleCSV(text) {
|
||||
const rows = [];
|
||||
let row = [""];
|
||||
let inQuotes = false;
|
||||
|
||||
// Détection dynamique du séparateur principal (, ou ;) basé sur la première ligne
|
||||
const firstLine = text.split(/\r?\n/)[0];
|
||||
const firstLine = text.split(/\r?\n/)[0] || "";
|
||||
const semiColonCount = (firstLine.match(/;/g) || []).length;
|
||||
const commaCount = (firstLine.match(/,/g) || []).length;
|
||||
const separator = semiColonCount > commaCount ? ';' : ',';
|
||||
@@ -28,11 +23,9 @@ function parseFlexibleCSV(text) {
|
||||
|
||||
if (c === '"') {
|
||||
if (inQuotes && next === '"') {
|
||||
// Gestion des doubles guillemets internes (ex: ""citation"")
|
||||
row[row.length - 1] += '"';
|
||||
i++;
|
||||
} else {
|
||||
// Bascule de l'état de lecture entre intérieur/extérieur des guillemets
|
||||
inQuotes = !inQuotes;
|
||||
}
|
||||
} else if (c === separator && !inQuotes) {
|
||||
@@ -49,11 +42,7 @@ function parseFlexibleCSV(text) {
|
||||
return rows;
|
||||
}
|
||||
|
||||
// ── FONCTION PRINCIPALE D'IMPORTATION CSV ──
|
||||
/**
|
||||
* Gère l'importation de fichiers CSV (Format d'export Mon Cinéma, importcinetest.csv ou Letterboxd).
|
||||
* Déduplique les entrées existantes et récupère les métadonnées TMDB si nécessaire.
|
||||
*/
|
||||
// ── FONCTION D'IMPORTATION REVISITÉE ──
|
||||
function importFromCSV(input) {
|
||||
const file = input.files[0];
|
||||
if (!file) return;
|
||||
@@ -64,24 +53,25 @@ function importFromCSV(input) {
|
||||
const rows = parseFlexibleCSV(text);
|
||||
|
||||
if (rows.length <= 1) {
|
||||
alert("Le fichier semble vide ou invalide.");
|
||||
alert("Le fichier semble vide ou illisible.");
|
||||
input.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
// Normalisation des entêtes pour la correspondance des colonnes (insensible à la casse)
|
||||
const headers = rows[0].map(h => h.trim().toLowerCase());
|
||||
// Nettoyage et normalisation des entêtes pour ignorer les accents et la casse
|
||||
const cleanHeader = (h) => h.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
||||
const headers = rows[0].map(cleanHeader);
|
||||
|
||||
// Mappage adaptatif des indices de colonnes (Français vs Anglais / Letterboxd)
|
||||
const idxTitle = headers.includes('titre') ? headers.indexOf('titre') : (headers.includes('name') ? headers.indexOf('name') : headers.indexOf('title'));
|
||||
const idxYear = headers.includes('annee') ? headers.indexOf('annee') : (headers.includes('year') ? headers.indexOf('year') : headers.indexOf('publish_date'));
|
||||
const idxDirector = headers.includes('realisateur') ? headers.indexOf('realisateur') : headers.indexOf('creators');
|
||||
const idxRating = headers.indexOf('note') !== -1 ? headers.indexOf('note') : headers.indexOf('rating');
|
||||
const idxReview = headers.indexOf('critique') !== -1 ? headers.indexOf('critique') : headers.indexOf('review');
|
||||
const idxPoster = headers.indexOf('url_affiche') !== -1 ? headers.indexOf('url_affiche') : headers.indexOf('url');
|
||||
// Mappage ultra-large des colonnes (gère vos deux structures de fichiers)
|
||||
const idxTitle = headers.findIndex(h => h === 'titre' || h === 'title' || h === 'name');
|
||||
const idxYear = headers.findIndex(h => h === 'annee' || h === 'year' || h === 'publish_date');
|
||||
const idxDirector = headers.findIndex(h => h === 'realisateur' || h === 'director' || h === 'creators');
|
||||
const idxRating = headers.findIndex(h => h === 'note' || h === 'rating');
|
||||
const idxReview = headers.findIndex(h => h === 'critique' || h === 'review' || h === 'description');
|
||||
const idxPoster = headers.findIndex(h => h === 'url_affiche' || h === 'url');
|
||||
|
||||
if (idxTitle === -1) {
|
||||
alert("Erreur : Impossible de localiser la colonne contenant les titres des films.");
|
||||
alert("Erreur : Impossible de trouver la colonne des titres. Entêtes détectés : " + rows[0].join(', '));
|
||||
input.value = '';
|
||||
return;
|
||||
}
|
||||
@@ -89,28 +79,30 @@ function importFromCSV(input) {
|
||||
const toImport = [];
|
||||
let duplicateCount = 0;
|
||||
|
||||
// Phase 1 : Extraction et nettoyage des données brutes
|
||||
for (let i = 1; i < rows.length; i++) {
|
||||
const cols = rows[i];
|
||||
if (!cols || cols.length === 0 || (cols.length === 1 && cols[0] === '')) continue;
|
||||
|
||||
const titleRaw = cols[idxTitle]?.trim();
|
||||
if (!titleRaw) continue;
|
||||
|
||||
// Nettoyage des suffixes d'éditions spéciales souvent présents dans les inventaires de DVD
|
||||
// Nettoyage des chaînes parasites
|
||||
let title = titleRaw.replace(/\s*\[.*?\]/g, "").replace(/\s*- Édition.*/gi, "");
|
||||
|
||||
// Extraction de l'année (Format AAAAmj ou juste AAAA)
|
||||
// Année (on extrait les 4 premiers chiffres)
|
||||
let year = '';
|
||||
if (idxYear >= 0 && cols[idxYear]) {
|
||||
year = cols[idxYear].trim().substring(0, 4);
|
||||
const match = cols[idxYear].trim().match(/\d{4}/);
|
||||
year = match ? match[0] : cols[idxYear].trim().substring(0, 4);
|
||||
}
|
||||
|
||||
// Extraction du réalisateur (Prend le premier si liste séparée par des virgules)
|
||||
// Réalisateur
|
||||
let director = '';
|
||||
if (idxDirector >= 0 && cols[idxDirector]) {
|
||||
director = cols[idxDirector].split(',')[0].trim();
|
||||
}
|
||||
|
||||
// Extraction et normalisation de la note (Borne entre 1 et 5)
|
||||
// Note (de 1 à 5)
|
||||
let rating = 0;
|
||||
if (idxRating >= 0 && cols[idxRating]) {
|
||||
const ratingRaw = parseFloat(cols[idxRating]);
|
||||
@@ -118,17 +110,17 @@ function importFromCSV(input) {
|
||||
rating = Math.round(Math.min(5, Math.max(1, ratingRaw)));
|
||||
}
|
||||
}
|
||||
if (rating === 0) rating = 3; // Note par défaut si non spécifiée
|
||||
if (rating === 0) rating = 3; // Note par défaut
|
||||
|
||||
// Extraction de la critique
|
||||
// Critique ou description longue
|
||||
let review = idxReview >= 0 && cols[idxReview] ? cols[idxReview].trim() : '';
|
||||
|
||||
// Extraction de l'URL de l'affiche si elle existe déjà
|
||||
// Lien vers l'affiche
|
||||
let filePoster = idxPoster >= 0 && cols[idxPoster] ? cols[idxPoster].trim() : '';
|
||||
|
||||
// Vérification des doublons (Même titre et même année)
|
||||
// Vérification des doublons élargie (titre + année identiques, peu importe le type)
|
||||
const alreadyExists = films.some(
|
||||
f => f.type === 'critique' && f.title.toLowerCase() === title.toLowerCase() && f.year === year
|
||||
f => f.title.toLowerCase() === title.toLowerCase() && (year === '' || f.year === year)
|
||||
);
|
||||
|
||||
if (alreadyExists) {
|
||||
@@ -139,9 +131,8 @@ function importFromCSV(input) {
|
||||
toImport.push({ title, year, director, rating, review, filePoster });
|
||||
}
|
||||
|
||||
// Sortie anticipée si aucun élément n'est à importer
|
||||
if (toImport.length === 0) {
|
||||
alert(`Aucun nouveau film à ajouter.\n⚠️ ${duplicateCount} doublon(s) ignoré(s).`);
|
||||
alert(`Aucun nouveau film inséré.\n⚠️ ${duplicateCount} doublon(s) filtré(s) ou lignes vides.`);
|
||||
input.value = '';
|
||||
return;
|
||||
}
|
||||
@@ -151,31 +142,29 @@ function importFromCSV(input) {
|
||||
|
||||
let importedCount = 0;
|
||||
|
||||
// Phase 2 : Traitement séquentiel et enrichissement TMDB
|
||||
for (let i = 0; i < toImport.length; i++) {
|
||||
const { title, year, director, rating, review, filePoster } = toImport[i];
|
||||
updateImportProgress(i, toImport.length, `🎬 Traitement : ${title}`);
|
||||
updateImportProgress(i, toImport.length, `🎬 Intégration : ${title}`);
|
||||
|
||||
let poster = filePoster;
|
||||
let streaming = "Disponible au cinéma ou support physique";
|
||||
let streaming = "Disponible sur vos étagères ou au cinéma";
|
||||
|
||||
// Si aucune affiche n'est fournie mais que l'API TMDB est dispo -> On cherche l'affiche
|
||||
// Si l'affiche locale manque et que TMDB est configuré, on interroge l'API
|
||||
if (!poster && hasTmdb) {
|
||||
const details = await fetchTmdbDetails(title, year);
|
||||
poster = details.poster;
|
||||
streaming = details.streaming;
|
||||
await new Promise(r => setTimeout(r, 200)); // Temporisation pour l'API Rate-Limit
|
||||
await new Promise(r => setTimeout(r, 150));
|
||||
} else if (hasTmdb && poster) {
|
||||
// Si l'affiche est fournie mais qu'on veut rafraîchir les plateformes de streaming uniquement
|
||||
const details = await fetchTmdbDetails(title, year);
|
||||
streaming = details.streaming;
|
||||
if (details.streaming) streaming = details.streaming;
|
||||
}
|
||||
|
||||
// Injection dans la base globale de l'application
|
||||
// Structure globale unifiée pour 'critique' ou 'film'
|
||||
films.push({
|
||||
id: Date.now() + Math.floor(Math.random() * 100000) + i,
|
||||
id: Date.now() + Math.floor(Math.random() * 1000) + i,
|
||||
title,
|
||||
type: 'critique',
|
||||
type: 'critique', // Forcer le type attendu par l'affichage principal de vos onglets
|
||||
year,
|
||||
director,
|
||||
rating,
|
||||
@@ -187,43 +176,41 @@ function importFromCSV(input) {
|
||||
importedCount++;
|
||||
}
|
||||
|
||||
// Finalisation de l'affichage de progression
|
||||
updateImportProgress(toImport.length, toImport.length, '✅ Terminé !');
|
||||
await new Promise(r => setTimeout(r, 400));
|
||||
await new Promise(r => setTimeout(r, 300));
|
||||
hideImportProgress();
|
||||
|
||||
// Tri de la collection par nouveautés (IDs les plus récents en premier)
|
||||
// Tri et persistance immédiate
|
||||
films.sort((a, b) => b.id - a.id);
|
||||
persist();
|
||||
switchTab('critique');
|
||||
|
||||
alert(
|
||||
`Importation réussie avec succès !\n` +
|
||||
`✅ ${importedCount} critique(s) ajoutée(s) depuis "${file.name}".\n` +
|
||||
`⚠️ ${duplicateCount} doublon(s) évité(s).`
|
||||
);
|
||||
alert(`Succès ! ${importedCount} films ajoutés.\n(${duplicateCount} doublons ignorés)`);
|
||||
input.value = '';
|
||||
};
|
||||
|
||||
reader.readAsText(file, 'UTF-8');
|
||||
// Utilisation de ISO-8859-1 (Latin-1) pour lire sans encombre les exports Windows/Excel contenant des accents
|
||||
reader.readAsText(file, 'ISO-8859-1');
|
||||
}
|
||||
|
||||
// ── FONCTIONS UTILITAIRES DE PROGRESSION DE L'IMPORT ──
|
||||
// ── COMPOSANTS ET OUTILS DE SUIVI DE L'IMPORT ──
|
||||
function showImportProgress(total) {
|
||||
let overlay = document.getElementById('import-overlay');
|
||||
if (!overlay) {
|
||||
overlay = document.createElement('div');
|
||||
overlay.id = 'import-overlay';
|
||||
overlay.innerHTML = `
|
||||
<div class="import-card">
|
||||
<h3>Importation du catalogue CSV</h3>
|
||||
<div class="import-progress-bar"><div id="import-progress-fill"></div></div>
|
||||
<p id="import-progress-text">Préparation...</p>
|
||||
<div class="import-card" style="position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:#222;color:#fff;padding:20px;border-radius:8px;z-index:9999;box-shadow:0 4px 15px rgba(0,0,0,0.5);font-family:sans-serif;width:320px;">
|
||||
<h3 style="margin-top:0;">Importation en cours...</h3>
|
||||
<div style="background:#444;width:100%;height:10px;border-radius:5px;overflow:hidden;margin:15px 0;">
|
||||
<div id="import-progress-fill" style="background:#00bcd4;width:0%;height:100%;transition:width 0.1s;"></div>
|
||||
</div>
|
||||
<p id="import-progress-text" style="font-size:13px;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">Initialisation...</p>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(overlay);
|
||||
}
|
||||
overlay.style.display = 'flex';
|
||||
overlay.style.display = 'block';
|
||||
}
|
||||
|
||||
function updateImportProgress(current, total, message) {
|
||||
@@ -240,18 +227,13 @@ function hideImportProgress() {
|
||||
}
|
||||
|
||||
// ── FONCTION D'EXPORTATION DU CATALOGUE (CSV) ──
|
||||
/**
|
||||
* Génère et déclenche le téléchargement d'un fichier CSV contenant l'ensemble de la bibliothèque actuelle.
|
||||
*/
|
||||
function exportToCSV() {
|
||||
if (!films || films.length === 0) {
|
||||
alert("Aucune donnée à exporter.");
|
||||
alert("Aucune donnée disponible pour l'exportation.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Définition des entêtes conformes à la structure globale de l'application Mon Cinéma
|
||||
const headers = ['ID', 'Titre', 'Annee', 'Realisateur', 'Note', 'Critique', 'URL_Affiche'];
|
||||
|
||||
const csvRows = [headers.join(';')];
|
||||
|
||||
films.forEach(f => {
|
||||
@@ -267,7 +249,7 @@ function exportToCSV() {
|
||||
csvRows.push(row.join(';'));
|
||||
});
|
||||
|
||||
const csvContent = "\uFEFF" + csvRows.join("\n"); // Ajout du BOM UTF-8 pour Excel
|
||||
const csvContent = "\uFEFF" + csvRows.join("\n");
|
||||
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
@@ -279,7 +261,7 @@ function exportToCSV() {
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
|
||||
// ── PERSISTANCE & SYNCHRONISATION LOCALSTORAGE ──
|
||||
// ── ENREGISTREMENT LOCAL STORAGE ──
|
||||
function persist() {
|
||||
localStorage.setItem('mon-cinema-films', JSON.stringify(films));
|
||||
if (typeof renderFilms === 'function') {
|
||||
@@ -287,7 +269,7 @@ function persist() {
|
||||
}
|
||||
}
|
||||
|
||||
// ── GESTION DE LA NAVIGATION PAR ONGLETS ──
|
||||
// ── COMMUTATION DE L'ONGLET ACTIF ──
|
||||
function switchTab(tabName) {
|
||||
document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
|
||||
document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
|
||||
@@ -298,6 +280,5 @@ function switchTab(tabName) {
|
||||
if (targetTab) targetTab.classList.add('active');
|
||||
if (targetBtn) targetBtn.classList.add('active');
|
||||
|
||||
// Sauvegarde de l'onglet actif pour reconexion
|
||||
localStorage.setItem('mon-cinema-active-tab', tabName);
|
||||
}
|
||||
Reference in New Issue
Block a user