diff --git a/api.php b/api.php index 4aa1e6e..8e53003 100644 --- a/api.php +++ b/api.php @@ -10,7 +10,10 @@ header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS"); header("Access-Control-Allow-Headers: Content-Type, Authorization"); -if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; } +if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { + http_response_code(200); + exit; +} define('ENCRYPTION_KEY', 'MaCleSecreteSuperRobuste123!'); @@ -23,9 +26,12 @@ try { $pdo->exec("CREATE TABLE IF NOT EXISTS config (key_name VARCHAR(50) PRIMARY KEY, key_value TEXT)"); $pdo->exec("CREATE TABLE IF NOT EXISTS critiques (id BIGINT PRIMARY KEY, title VARCHAR(255), year VARCHAR(10), director VARCHAR(255), poster TEXT, rating DECIMAL(3,1), review TEXT, streaming VARCHAR(255))"); $pdo->exec("CREATE TABLE IF NOT EXISTS videotheque (id BIGINT PRIMARY KEY, title VARCHAR(255), year VARCHAR(10), director VARCHAR(255), poster TEXT, format VARCHAR(50), length VARCHAR(50), publisher VARCHAR(255), ean_isbn13 VARCHAR(50), number_of_discs INT DEFAULT 1, aspect_ratio VARCHAR(50), description TEXT, actors TEXT)"); -} catch (PDOException $e) { die(json_encode(["error" => "Connexion BDD échouée"])); } +} catch (PDOException $e) { + die(json_encode(["error" => "Connexion BDD échouée"])); +} // --- Fonctions Utilitaires --- + function getAuthToken() { if (!empty($_SERVER['HTTP_AUTHORIZATION'])) return $_SERVER['HTTP_AUTHORIZATION']; if (!empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) return $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; @@ -41,7 +47,8 @@ function checkAuth($pdo) { if ($pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() == 0) return true; $token = getAuthToken(); if ($token !== md5(ENCRYPTION_KEY . 'session')) { - http_response_code(403); exit; + http_response_code(403); + exit; } } @@ -69,19 +76,16 @@ function httpGet($url, $timeout = 10, $headers = []) { curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $timeout, - CURLOPT_CONNECTTIMEOUT => 5, // Échoue vite si le serveur est injoignable - CURLOPT_FOLLOWLOCATION => true, // Indispensable : suit les redirections 301/302 - CURLOPT_ENCODING => '', // Gère automatiquement la compression (Gzip/Deflate) - CURLOPT_SSL_VERIFYPEER => false, // À passer à true en production + CURLOPT_CONNECTTIMEOUT => 5, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_ENCODING => '', + CURLOPT_SSL_VERIFYPEER => false, CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0', CURLOPT_HTTPHEADER => $headers ]); - $res = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); - - // On accepte le code 200 (OK), mais aussi 201 ou 202 selon les APIs return ($code >= 200 && $code < 300) ? $res : null; } @@ -93,11 +97,12 @@ function removeAccentsForUrl($str) { return $str; } +// CORRECTION : Ajout du modificateur /u pour une gestion parfaite de l'UTF-8 et des accents function cleanTitle($title) { - $clean = preg_replace('/\s*[\[\(].*?[\]\)]\s*/', '', $title); - $clean = preg_replace('/\s*-\s*(Édition|Edition|Collector|Simple|Spéciale|Digibook|Ultimate|Intégrale|Combo|SteelBook|Boîtier).*$/i', '', $clean); - $clean = preg_replace('/(blu-ray|bluray|dvd|4k|ultra hd|combo|vhs|bdrip).*$/i', '', $clean); - return trim(preg_replace('/\s{2,}/', ' ', $clean)); + $clean = preg_replace('/\s*[\[\(].*?[\]\)]\s*/u', '', $title); + $clean = preg_replace('/\s*-\s*(édition|Edition|Collector|Simple|Spéciale|Digibook|Ultimate|Intégrale|Combo|SteelBook|Boîtier).*$/iu', '', $clean); + $clean = preg_replace('/(blu-ray|bluray|dvd|4k|ultra hd|combo|vhs|bdrip).*$/iu', '', $clean); + return trim(preg_replace('/\s{2,}/u', ' ', $clean)); } function detectFormat($title, $desc = '') { @@ -122,52 +127,25 @@ function emptyPhysicalResult() { ]; } -// ── NOUVELLE FONCTION : SCRAPPING DVDFR.COM ── +// --- SCRAPING DVDFR.COM --- function fetchFromDvdfr($ean) { $empty = emptyPhysicalResult(); $url = "https://www.dvdfr.com/listeliv.php?base=dvd&mots_recherche=" . urlencode($ean); $html = httpGet($url, 15); if (!$html) return $empty; - - // Recherche du premier produit trouvé dans la liste if (preg_match('/
([^<]+)<\/PRE>/is', $html, $m)) {
- $idmc = trim($m[1]);
- } elseif (preg_match('/([^<]+)<\/PRE>/is', $html, $m)) $idmc = trim($m[1]);
+ elseif (preg_match('/]*title="Recto[^"]*"[^>]*src="([^"]+)"/i', $html, $m)) $empty['poster'] = $m[1];
elseif (preg_match('/]*property="og:image"[^>]*content="([^"]+)"/i', $html, $m)) $empty['poster'] = $m[1];
}
-
if (preg_match('/Réalisateur<\/TH>\s*]*>.*?]*>([^<]+)<\/a>/is', $html, $m)) $empty['director'] = trim($m[1]);
if (preg_match('/Année<\/TH>\s* ]*>.*?]*>(\d{4})<\/a>/is', $html, $m)) $empty['year'] = $m[1];
if (preg_match('/Durée<\/TH>\s* ]*>([\dH]+[\dmin]*)/is', $html, $m)) $empty['length'] = trim($m[1]);
if (preg_match_all('/([^<]+)<\/a>/i', $html, $matches)) $empty['actors'] = implode(', ', array_slice($matches[1], 0, 5));
if (preg_match('/]*property="og:description"[^>]*content="([^"]+)"/i', $html, $m)) $empty['description'] = html_entity_decode($m[1]);
-
return $empty;
}
-// ── AGGREGATEUR PHYSIQUE (VERSION MODIFIÉE AVEC DVDFR) ──
function fetchPhysicalByEan($ean, $pdo = null) {
error_log("=== DEBUT fetchPhysicalByEan EAN=$ean ===");
-
$res = emptyPhysicalResult();
$title = '';
-
- // 1. DVDFR.COM (Priorité 1 - pour titre, image et métadonnées)
$dvdfrData = fetchFromDvdfr($ean);
- error_log("DVDFR -> title='" . ($dvdfrData['title'] ?? '') . "' poster='" . ($dvdfrData['poster'] ?? '') . "' director='" . ($dvdfrData['director'] ?? '') . "'");
-
if (!empty($dvdfrData['title'])) {
$title = $dvdfrData['title'];
$res = $dvdfrData;
}
-
- // 2. UPCINDEX.COM (Priorité 2 - pour métadonnées physiques détaillées)
$upcIndexData = fetchFromUpcIndex($ean);
- error_log("UPCINDEX -> title='" . ($upcIndexData['title'] ?? '') . "' director='" . ($upcIndexData['director'] ?? '') . "'");
-
- if (!empty($upcIndexData['title']) && empty($title)) {
- $title = $upcIndexData['title'];
- }
-
- // Fusionner les données UPCINDEX (métadonnées physiques)
+ if (!empty($upcIndexData['title']) && empty($title)) $title = $upcIndexData['title'];
if (!empty($upcIndexData)) {
- if (!empty($upcIndexData['director']) && empty($res['director'])) {
- $res['director'] = $upcIndexData['director'];
- }
+ if (!empty($upcIndexData['director']) && empty($res['director'])) $res['director'] = $upcIndexData['director'];
if (!empty($upcIndexData['actors'])) $res['actors'] = $upcIndexData['actors'];
- if (!empty($upcIndexData['format']) && empty($res['format'])) {
- $res['format'] = $upcIndexData['format'];
- }
+ if (!empty($upcIndexData['format']) && empty($res['format'])) $res['format'] = $upcIndexData['format'];
if (!empty($upcIndexData['aspect_ratio'])) $res['aspect_ratio'] = $upcIndexData['aspect_ratio'];
if (!empty($upcIndexData['number_of_discs'])) $res['number_of_discs'] = $upcIndexData['number_of_discs'];
- if (!empty($upcIndexData['publisher']) && empty($res['publisher'])) {
- $res['publisher'] = $upcIndexData['publisher'];
- }
+ if (!empty($upcIndexData['publisher']) && empty($res['publisher'])) $res['publisher'] = $upcIndexData['publisher'];
if (!empty($upcIndexData['description'])) $res['description'] = $upcIndexData['description'];
if (!empty($upcIndexData['year'])) $res['year'] = $upcIndexData['year'];
- // Garder l'image de DVD.fr en priorité
- if (empty($res['poster']) && !empty($upcIndexData['poster'])) {
- $res['poster'] = $upcIndexData['poster'];
- }
+ if (empty($res['poster']) && !empty($upcIndexData['poster'])) $res['poster'] = $upcIndexData['poster'];
}
-
- // 3. FNAC (Fallback si pas de titre)
if (empty($title)) {
$fnacData = fetchFromFnac($ean);
- error_log("FNAC -> title='" . ($fnacData['title'] ?? '') . "'");
if (!empty($fnacData['title'])) {
$title = $fnacData['title'];
if (empty($res['title'])) $res = $fnacData;
}
}
-
- // 4. MovieCovers (pour jaquette HD FR si pas d'image)
if (!empty($title) && empty($res['poster'])) {
$mc = fetchFromMovieCovers($title, $res['year'] ?? '');
- error_log("MOVIECOVERS -> poster='" . ($mc['poster'] ?? '') . "'");
if (!empty($mc['poster'])) $res['poster'] = $mc['poster'];
}
-
- error_log("=== FIN fetchPhysicalByEan -> title FINAL='" . ($res['title'] ?? '') . "' poster='" . ($res['poster'] ?? '') . "' ===");
return $res;
}
-// ── ROUTEUR PRINCIPAL ──
+// --- ROUTEUR PRINCIPAL ---
$action = $_GET['action'] ?? '';
$data = json_decode(file_get_contents('php://input'), true) ?? [];
@@ -641,30 +516,36 @@ switch ($action) {
case 'check_security_status':
echo json_encode(["is_blank" => ($pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() == 0)]);
break;
-
+
case 'login':
if ($pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() == 0) {
echo json_encode(["success" => true, "token" => md5(ENCRYPTION_KEY . 'session'), "blank" => true]);
} else {
$stmt = $pdo->prepare("SELECT password_hash FROM users WHERE username = 'admin'");
- $stmt->execute(); $user = $stmt->fetch();
+ $stmt->execute();
+ $user = $stmt->fetch();
if ($user && password_verify($data['password'] ?? '', $user['password_hash'])) {
echo json_encode(["success" => true, "token" => md5(ENCRYPTION_KEY . 'session'), "blank" => false]);
- } else { http_response_code(401); echo json_encode(["error" => "Mot de passe incorrect."]); }
+ } else {
+ http_response_code(401);
+ echo json_encode(["error" => "Mot de passe incorrect."]);
+ }
}
break;
-
- case 'setup_admin': case 'update_password':
+
+ case 'setup_admin':
+ case 'update_password':
checkAuth($pdo);
$pwd = $data['password'] ?? $data['new_password'] ?? '';
$stmt = $pdo->prepare("REPLACE INTO users (id, username, password_hash) VALUES (1, 'admin', :pass)");
$stmt->execute([':pass' => password_hash($pwd, PASSWORD_BCRYPT)]);
echo json_encode(["success" => true]);
break;
-
+
case 'get_config_keys':
$stmt = $pdo->prepare("SELECT key_value FROM config WHERE key_name = 'tmdb_api_key'");
- $stmt->execute(); $row = $stmt->fetch();
+ $stmt->execute();
+ $row = $stmt->fetch();
echo json_encode(['tmdb_api_key' => $row ? decryptData($row['key_value']) : '']);
break;
@@ -672,15 +553,19 @@ switch ($action) {
checkAuth($pdo);
$name = $data['key_name'] ?? '';
$val = trim($data['key_value'] ?? '');
- if ($name !== 'tmdb_api_key' || empty($val)) { http_response_code(400); echo json_encode(["error" => "Clé invalide."]); break; }
+ if ($name !== 'tmdb_api_key' || empty($val)) {
+ http_response_code(400);
+ echo json_encode(["error" => "Clé invalide."]);
+ break;
+ }
$stmt = $pdo->prepare("REPLACE INTO config (key_name, key_value) VALUES (?, ?)");
$stmt->execute([$name, encryptData($val)]);
echo json_encode(["success" => true]);
break;
-
+
case 'get_films':
$critiques = $pdo->query("SELECT id, title, year, director, poster, rating, review, NULL AS description, streaming, 'critique' AS type, NULL AS format FROM critiques ORDER BY id DESC")->fetchAll();
- foreach ($critiques as $row) {
+ foreach ($critiques as &$row) {
if ($row['rating'] !== null) {
$ratingVal = (float)$row['rating'];
$row['rating'] = ($ratingVal == floor($ratingVal)) ? (int)$ratingVal : $ratingVal;
@@ -690,12 +575,11 @@ switch ($action) {
$videotheque = $pdo->query("SELECT id, title, year, director, poster, NULL AS rating, NULL AS review, description, NULL AS streaming, 'videotheque' AS type, format FROM videotheque ORDER BY id DESC")->fetchAll();
echo json_encode(['critique' => $critiques, 'videotheque' => $videotheque]);
break;
-
+
case 'save_film':
checkAuth($pdo);
$type = $data['type'] ?? 'critique';
$id = !empty($data['id']) ? $data['id'] : makeStableId($type, $data['title'] ?? '', $data['year'] ?? '0000');
-
if ($type === 'critique') {
if (empty($data['director']) || empty($data['poster'])) {
$tmdbData = fetchTmdbPosterAndSynopsis($data['title'] ?? '', $data['year'] ?? '', $pdo);
@@ -722,118 +606,110 @@ switch ($action) {
}
echo json_encode(["success" => true]);
break;
-
+
case 'delete_film':
checkAuth($pdo);
- $type = $_GET['type'] ?? 'critique'; $table = ($type === 'videotheque') ? 'videotheque' : 'critiques';
+ $type = $_GET['type'] ?? 'critique';
+ $table = ($type === 'videotheque') ? 'videotheque' : 'critiques';
$id = $_GET['id'] ?? null;
if (!$id) { http_response_code(400); echo json_encode(["error" => "ID manquant."]); break; }
- $stmt = $pdo->prepare("DELETE FROM $table WHERE id = ?"); $stmt->execute([$id]);
+ $stmt = $pdo->prepare("DELETE FROM $table WHERE id = ?");
+ $stmt->execute([$id]);
echo json_encode(["success" => true]);
break;
-
+
case 'bulk_delete':
checkAuth($pdo);
- $ids = $data['ids'] ?? []; $type = $data['type'] ?? 'critique'; $table = ($type === 'videotheque') ? 'videotheque' : 'critiques';
- if (!empty($ids)) { $placeholders = implode(',', array_fill(0, count($ids), '?')); $stmt = $pdo->prepare("DELETE FROM $table WHERE id IN ($placeholders)"); $stmt->execute($ids); echo json_encode(["success" => true]); }
- else { http_response_code(400); echo json_encode(["success" => false, "error" => "Aucun élément sélectionné."]); }
+ $ids = $data['ids'] ?? [];
+ $type = $data['type'] ?? 'critique';
+ $table = ($type === 'videotheque') ? 'videotheque' : 'critiques';
+ if (!empty($ids)) {
+ $placeholders = implode(',', array_fill(0, count($ids), '?'));
+ $stmt = $pdo->prepare("DELETE FROM $table WHERE id IN ($placeholders)");
+ $stmt->execute($ids);
+ echo json_encode(["success" => true]);
+ } else {
+ http_response_code(400);
+ echo json_encode(["success" => false, "error" => "Aucun élément sélectionné."]);
+ }
break;
-
-case 'add_item_by_ean':
- $ean = preg_replace('/[^0-9]/', '', $data['ean'] ?? '');
- if (strlen($ean) < 8) { echo json_encode(["success" => false, "error" => "EAN invalide"]); exit; }
-
- $physicalData = fetchPhysicalByEan($ean, $pdo);
- $rawTitle = $physicalData['title'] ?? '';
-
- $tmdbData = fetchTmdbPosterAndSynopsis($rawTitle, $physicalData['year'] ?? '', $pdo);
-
- $finalTitle = !empty($tmdbData['title']) ? $tmdbData['title'] : $rawTitle;
-
- // ✅ PRIORITÉ ABSOLUE À L'IMAGE DE GO-UPC/PHYSICAL
- $poster = !empty($physicalData['poster']) ? $physicalData['poster'] :
- (($tmdbData['poster'] !== 'assets/img/default_physical_media.jpg') ? $tmdbData['poster'] : 'assets/img/default_physical_media.jpg');
-
- $year = $tmdbData['year'] ?? $physicalData['year'] ?? '';
- $id = makeStableId('videotheque', $finalTitle, $year);
-
- $stmt = $pdo->prepare("INSERT INTO videotheque (id, title, year, poster, description, director, actors, ean_isbn13, format, length, publisher, number_of_discs, aspect_ratio) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title=VALUES(title), year=VALUES(year), poster=IF(VALUES(poster)!='', VALUES(poster), poster), description=IF(VALUES(description)!='', VALUES(description), description), director=IF(VALUES(director)!='', VALUES(director), director), actors=IF(VALUES(actors)!='', VALUES(actors), actors)");
- $stmt->execute([
- $id, $finalTitle, $year, $poster,
- $tmdbData['description'] ?? $physicalData['description'] ?? '',
- $physicalData['director'] ?: $tmdbData['director'], // ✅ Priorité aux données physiques
- $physicalData['actors'] ?: $tmdbData['actors'], // ✅ Priorité aux données physiques
- $ean, $physicalData['format'] ?? detectFormat($rawTitle),
- $tmdbData['length'] ?: ($physicalData['length'] ?? ''),
- $physicalData['publisher'] ?? '', $physicalData['number_of_discs'] ?? 1, $physicalData['aspect_ratio'] ?? ''
- ]);
-
- echo json_encode(["success" => true, "title" => $finalTitle, "director" => $physicalData['director'] ?: $tmdbData['director'], "year" => $year]);
- break;
-
-case 'import_batch':
- checkAuth($pdo);
- $type = $data['type'] ?? '';
- $items = $data['items'] ?? [];
- $pdo->beginTransaction();
- $imported = 0; $skipped = 0;
-
- try {
- if ($type === 'videotheque') {
- $stmt = $pdo->prepare("INSERT INTO videotheque (id, title, year, format, poster, ean_isbn13, description, length, number_of_discs, aspect_ratio, actors, publisher, director) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE title=VALUES(title), year=VALUES(year), format=VALUES(format), poster=IF(VALUES(poster)!='assets/img/default_physical_media.jpg', VALUES(poster), poster), ean_isbn13=IF(VALUES(ean_isbn13)!='', VALUES(ean_isbn13), ean_isbn13), description=IF(VALUES(description)!='', VALUES(description), description), length=IF(VALUES(length)!='', VALUES(length), length), number_of_discs=IF(VALUES(number_of_discs)!=1, VALUES(number_of_discs), number_of_discs), aspect_ratio=IF(VALUES(aspect_ratio)!='', VALUES(aspect_ratio), aspect_ratio), actors=IF(VALUES(actors)!='', VALUES(actors), actors), publisher=IF(VALUES(publisher)!='', VALUES(publisher), publisher), director=IF(VALUES(director)!='', VALUES(director), director)");
-
- foreach ($items as $item) {
- $ean = preg_replace('/[^0-9]/', '', (string)($item['ean'] ?? ''));
- if (strlen($ean) < 8) { $skipped++; continue; }
-
- $physicalData = fetchPhysicalByEan($ean, $pdo);
- $title = $physicalData['title'] ?? '';
- $year = $physicalData['year'] ?? '';
- $format = $physicalData['format'] ?: detectFormat($title);
- $publisher = $physicalData['publisher'] ?? '';
- $discs = $physicalData['number_of_discs'] ?: 1;
- $aspect = $physicalData['aspect_ratio'] ?? '';
- $length = $physicalData['length'] ?? '';
-
- // ✅ PRIORITÉ À L'IMAGE DE GO-UPC
- $poster = !empty($physicalData['poster']) ? $physicalData['poster'] : 'assets/img/default_physical_media.jpg';
-
- $desc = $physicalData['description'] ?? '';
- $director = $physicalData['director'] ?? '';
- $actors = $physicalData['actors'] ?? '';
-
- if (empty($poster) || empty($director) || empty($actors) || empty($desc) || empty($title)) {
- $tmdb = fetchTmdbPosterAndSynopsis($title, $year, $pdo);
- if (empty($title)) $title = $tmdb['title'] ?? "EAN: $ean";
- // ⚠️ NE PAS ÉCRASER L'IMAGE DE GO-UPC
- if (empty($poster) && $tmdb['poster'] !== 'assets/img/default_physical_media.jpg') {
- $poster = $tmdb['poster'];
+
+ case 'add_item_by_ean':
+ $ean = preg_replace('/[^0-9]/', '', $data['ean'] ?? '');
+ if (strlen($ean) < 8) { echo json_encode(["success" => false, "error" => "EAN invalide"]); exit; }
+ $physicalData = fetchPhysicalByEan($ean, $pdo);
+ $rawTitle = $physicalData['title'] ?? '';
+ $tmdbData = fetchTmdbPosterAndSynopsis($rawTitle, $physicalData['year'] ?? '', $pdo);
+ $finalTitle = !empty($tmdbData['title']) ? $tmdbData['title'] : $rawTitle;
+ $poster = !empty($physicalData['poster']) ? $physicalData['poster'] : (($tmdbData['poster'] !== 'assets/img/default_physical_media.jpg') ? $tmdbData['poster'] : 'assets/img/default_physical_media.jpg');
+ $year = $tmdbData['year'] ?? $physicalData['year'] ?? '';
+ $id = makeStableId('videotheque', $finalTitle, $year);
+ $stmt = $pdo->prepare("INSERT INTO videotheque (id, title, year, poster, description, director, actors, ean_isbn13, format, length, publisher, number_of_discs, aspect_ratio) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title=VALUES(title), year=VALUES(year), poster=IF(VALUES(poster)!='', VALUES(poster), poster), description=IF(VALUES(description)!='', VALUES(description), description), director=IF(VALUES(director)!='', VALUES(director), director), actors=IF(VALUES(actors)!='', VALUES(actors), actors)");
+ $stmt->execute([
+ $id, $finalTitle, $year, $poster,
+ $tmdbData['description'] ?? $physicalData['description'] ?? '',
+ $physicalData['director'] ?: $tmdbData['director'],
+ $physicalData['actors'] ?: $tmdbData['actors'],
+ $ean, $physicalData['format'] ?? detectFormat($rawTitle),
+ $tmdbData['length'] ?: ($physicalData['length'] ?? ''),
+ $physicalData['publisher'] ?? '', $physicalData['number_of_discs'] ?? 1, $physicalData['aspect_ratio'] ?? ''
+ ]);
+ echo json_encode(["success" => true, "title" => $finalTitle, "director" => $physicalData['director'] ?: $tmdbData['director'], "year" => $year]);
+ break;
+
+ case 'import_batch':
+ checkAuth($pdo);
+ $type = $data['type'] ?? '';
+ $items = $data['items'] ?? [];
+ $pdo->beginTransaction();
+ $imported = 0; $skipped = 0;
+
+ try {
+ if ($type === 'videotheque') {
+ $stmt = $pdo->prepare("INSERT INTO videotheque (id, title, year, format, poster, ean_isbn13, description, length, number_of_discs, aspect_ratio, actors, publisher, director) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE title=VALUES(title), year=VALUES(year), format=VALUES(format), poster=IF(VALUES(poster)!='assets/img/default_physical_media.jpg', VALUES(poster), poster), ean_isbn13=IF(VALUES(ean_isbn13)!='', VALUES(ean_isbn13), ean_isbn13), description=IF(VALUES(description)!='', VALUES(description), description), length=IF(VALUES(length)!='', VALUES(length), length), number_of_discs=IF(VALUES(number_of_discs)!=1, VALUES(number_of_discs), number_of_discs), aspect_ratio=IF(VALUES(aspect_ratio)!='', VALUES(aspect_ratio), aspect_ratio), actors=IF(VALUES(actors)!='', VALUES(actors), actors), publisher=IF(VALUES(publisher)!='', VALUES(publisher), publisher), director=IF(VALUES(director)!='', VALUES(director), director)");
+ foreach ($items as $item) {
+ $ean = preg_replace('/[^0-9]/', '', (string)($item['ean'] ?? ''));
+ if (strlen($ean) < 8) { $skipped++; continue; }
+ $physicalData = fetchPhysicalByEan($ean, $pdo);
+ $title = $physicalData['title'] ?? '';
+ $year = $physicalData['year'] ?? '';
+ $format = $physicalData['format'] ?: detectFormat($title);
+ $publisher = $physicalData['publisher'] ?? '';
+ $discs = $physicalData['number_of_discs'] ?: 1;
+ $aspect = $physicalData['aspect_ratio'] ?? '';
+ $length = $physicalData['length'] ?? '';
+ $poster = !empty($physicalData['poster']) ? $physicalData['poster'] : 'assets/img/default_physical_media.jpg';
+ $desc = $physicalData['description'] ?? '';
+ $director = $physicalData['director'] ?? '';
+ $actors = $physicalData['actors'] ?? '';
+ if (empty($poster) || empty($director) || empty($actors) || empty($desc) || empty($title)) {
+ $tmdb = fetchTmdbPosterAndSynopsis($title, $year, $pdo);
+ if (empty($title)) $title = $tmdb['title'] ?? "EAN: $ean";
+ if (empty($poster) && $tmdb['poster'] !== 'assets/img/default_physical_media.jpg') {
+ $poster = $tmdb['poster'];
+ }
+ if (empty($director)) $director = $tmdb['director'] ?? '';
+ if (empty($actors)) $actors = $tmdb['actors'] ?? '';
+ if (empty($desc)) $desc = $tmdb['description'] ?? '';
+ if (empty($length) && !empty($tmdb['length'])) $length = $tmdb['length'];
+ if (empty($year) && !empty($tmdb['year'])) $year = $tmdb['year'];
}
- if (empty($director)) $director = $tmdb['director'] ?? '';
- if (empty($actors)) $actors = $tmdb['actors'] ?? '';
- if (empty($desc)) $desc = $tmdb['description'] ?? '';
- if (empty($length) && !empty($tmdb['length'])) $length = $tmdb['length'];
- if (empty($year) && !empty($tmdb['year'])) $year = $tmdb['year'];
+ if (empty($title)) { $skipped++; continue; }
+ $id = makeStableId('videotheque', $title, $year);
+ $stmt->execute([$id, $title, $year, $format, $poster, $ean, $desc, $length, $discs, $aspect, $actors, $publisher, $director]);
+ $imported++;
}
-
- if (empty($title)) { $skipped++; continue; }
- $id = makeStableId('videotheque', $title, $year);
- $stmt->execute([$id, $title, $year, $format, $poster, $ean, $desc, $length, $discs, $aspect, $actors, $publisher, $director]);
- $imported++;
- }
} else {
$stmtCritiques = $pdo->prepare("INSERT INTO critiques (id, title, year, director, poster, rating, review, streaming) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title=VALUES(title), year=VALUES(year), director=VALUES(director), poster=VALUES(poster), rating=VALUES(rating), review=VALUES(review), streaming=VALUES(streaming)");
foreach ($items as $rowData) {
- // Supporte "Name" (Letterboxd standard) ou "Title"
$title = $rowData['Title'] ?? $rowData['title'] ?? $rowData['Name'] ?? '';
if (empty($title)) continue;
- // PRIORITY FIX : On cherche la vraie année du film, on ignore publish_date pour la recherche TMDB
$year = $rowData['Year'] ?? $rowData['year'] ?? '';
if (empty($year) && !empty($rowData['Release Date'])) {
$year = substr($rowData['Release Date'], 0, 4);
}
-
+
$id = makeStableId('critique', $title, $year);
$ratingRaw = $rowData['Rating'] ?? $rowData['rating'] ?? '';
$rating = ($ratingRaw !== '' && $ratingRaw !== null) ? (float)$ratingRaw : null;
@@ -842,7 +718,7 @@ case 'import_batch':
$poster = 'assets/img/default_physical_media.jpg';
$streaming = 'Support physique / Cinéma';
- // Appel TMDB
+ // Appel TMDB intelligent
$tmdbData = fetchTmdbPosterAndSynopsis($title, $year, $pdo);
if ($tmdbData) {
if (!empty($tmdbData['director'])) $director = $tmdbData['director'];
@@ -852,7 +728,7 @@ case 'import_batch':
$stmtCritiques->execute([$id, $title, $year, $director, $poster, $rating, $review, $streaming]);
- // PAUSE ANTI-BLOCAGE : 250 millisecondes entre chaque film pour respecter le quota TMDB
+ // PAUSE ANTI-BLOCAGE : 250 ms
usleep(250000);
$imported++;
}