Actualiser api.php

This commit is contained in:
2026-06-21 18:01:28 +02:00
parent edc571209d
commit 8391400c0c
+114 -174
View File
@@ -8,7 +8,7 @@ header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; } if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
define('ENCRYPTION_KEY', 'MaCleSecreteSuperRobuste123!'); define('ENCRYPTION_KEY', 'MaCleSecreteSuperRobuste123!');
define('TMDB_CACHE_TTL', 604800); // 7 jours de cache define('CACHE_TTL', 604800); // 7 jours
try { try {
$pdo = new PDO("mysql:host=localhost;dbname=mon_cinema;charset=utf8mb4", "root", "", [ $pdo = new PDO("mysql:host=localhost;dbname=mon_cinema;charset=utf8mb4", "root", "", [
@@ -21,28 +21,21 @@ try {
$pdo->exec("ALTER TABLE critiques MODIFY COLUMN rating DECIMAL(3,1) DEFAULT 3.0;"); $pdo->exec("ALTER TABLE critiques MODIFY COLUMN rating DECIMAL(3,1) DEFAULT 3.0;");
$pdo->exec("CREATE TABLE IF NOT EXISTS videotheque (id BIGINT PRIMARY KEY, title VARCHAR(255) NOT NULL, 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)"); $pdo->exec("CREATE TABLE IF NOT EXISTS videotheque (id BIGINT PRIMARY KEY, title VARCHAR(255) NOT NULL, 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)");
// 🆕 Tables de cache // Cache unifié pour toutes les APIs
$pdo->exec("CREATE TABLE IF NOT EXISTS cache_tmdb ( $pdo->exec("CREATE TABLE IF NOT EXISTS cache_api (
cache_key VARCHAR(100) PRIMARY KEY, cache_key VARCHAR(120) PRIMARY KEY,
data TEXT NOT NULL, data TEXT NOT NULL,
created_at INT NOT NULL source VARCHAR(20) NOT NULL,
)");
$pdo->exec("CREATE TABLE IF NOT EXISTS cache_ean (
ean VARCHAR(20) PRIMARY KEY,
image_url TEXT,
source VARCHAR(20),
created_at INT NOT NULL created_at INT NOT NULL
)"); )");
} catch (\PDOException $e) { echo json_encode(["error" => "Erreur BDD : " . $e->getMessage()]); exit; } } catch (\PDOException $e) { echo json_encode(["error" => "Erreur BDD : " . $e->getMessage()]); exit; }
function makeStableId($title, $year) { function makeStableId($title, $year) {
$key = strtolower(trim($title ?? '')) . '|' . trim($year ?? ''); return (abs(crc32(strtolower(trim($title ?? '')) . '|' . trim($year ?? ''))) % 2000000000) + 100000000;
return (abs(crc32($key)) % 2000000000) + 100000000;
} }
function checkAuth($pdo) { function checkAuth($pdo) {
$stmtCheck = $pdo->query("SELECT COUNT(*) FROM users"); if ($pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() == 0) return true;
if ($stmtCheck->fetchColumn() == 0) return true;
$token = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (empty($token) && function_exists('apache_request_headers')) { if (empty($token) && function_exists('apache_request_headers')) {
$headers = apache_request_headers(); $headers = apache_request_headers();
@@ -54,152 +47,121 @@ function checkAuth($pdo) {
function encryptData($data) { function encryptData($data) {
$iv = openssl_random_pseudo_bytes(16); $iv = openssl_random_pseudo_bytes(16);
$key = hash('sha256', ENCRYPTION_KEY, true); $key = hash('sha256', ENCRYPTION_KEY, true);
$encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv); return base64_encode(openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv) . '::' . $iv);
return base64_encode($encrypted . '::' . $iv);
} }
function decryptData($encryptedStr) { function decryptData($str) {
$decoded = base64_decode($encryptedStr); $decoded = base64_decode($str);
if (strpos($decoded, '::') !== false) { list($encData, $iv) = explode('::', $decoded, 2); } else { return null; } if (strpos($decoded, '::') === false) return null;
$key = hash('sha256', ENCRYPTION_KEY, true); list($enc, $iv) = explode('::', $decoded, 2);
$iv = substr($iv, 0, 16); return openssl_decrypt($enc, 'AES-256-CBC', hash('sha256', ENCRYPTION_KEY, true), OPENSSL_RAW_DATA, substr($iv, 0, 16));
return openssl_decrypt($encData, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
} }
function getTmdbApiKey($pdo) { function getTmdbApiKey($pdo) {
$stmt = $pdo->prepare("SELECT key_value FROM config WHERE key_name = 'tmdb_api_key'"); $stmt = $pdo->prepare("SELECT key_value FROM config WHERE key_name = 'tmdb_api_key'");
$stmt->execute(); $stmt->execute();
$row = $stmt->fetch(); $row = $stmt->fetch();
if (!$row) return null; return $row ? decryptData($row['key_value']) : null;
return decryptData($row['key_value']);
} }
// ─ HTTP unifié avec cURL ── // ─ HTTP avec cURL (timeout court pour vitesse) ──
function httpGet($url, $timeout = 8) { function httpGet($url, $timeout = 5) {
if (function_exists('curl_init')) { if (!function_exists('curl_init')) {
$ctx = stream_context_create(['http' => ['timeout' => $timeout, 'user_agent' => 'MonCinema/4.0']]);
return @file_get_contents($url, false, $ctx);
}
$ch = curl_init($url); $ch = curl_init($url);
curl_setopt_array($ch, [ curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $timeout, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_USERAGENT => 'MonCinema/4.0', CURLOPT_FOLLOWLOCATION => true]);
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => 'MonCinema/3.0',
CURLOPT_FOLLOWLOCATION => true
]);
$res = curl_exec($ch); $res = curl_exec($ch);
curl_close($ch); curl_close($ch);
return $res ?: null; return $res ?: null;
} }
$ctx = stream_context_create(['http' => ['timeout' => $timeout, 'user_agent' => 'MonCinema/3.0']]);
return @file_get_contents($url, false, $ctx); // ── Cache BDD ──
function getCache($pdo, $key) {
try {
$stmt = $pdo->prepare("SELECT data FROM cache_api WHERE cache_key = ? AND created_at > ?");
$stmt->execute([$key, time() - CACHE_TTL]);
$row = $stmt->fetch();
return $row ? json_decode($row['data'], true) : null;
} catch (\Exception $e) { return null; }
} }
// ── NETTOYAGE TITRE (crucial pour TMDB) ── function setCache($pdo, $key, $data, $source) {
function cleanTitleForTmdb($title) { try {
// Enlever tout ce qui est entre crochets/parenthèses $stmt = $pdo->prepare("REPLACE INTO cache_api (cache_key, data, source, created_at) VALUES (?, ?, ?, ?)");
$stmt->execute([$key, json_encode($data), $source, time()]);
} catch (\Exception $e) { /* ignore */ }
}
// ── NETTOYAGE TITRE pour TMDB ──
function cleanTitle($title) {
$clean = preg_replace('/\s*[\[\(].*?[\]\)]\s*/', '', $title); $clean = preg_replace('/\s*[\[\(].*?[\]\)]\s*/', '', $title);
// Enlever les mentions d'édition $clean = preg_replace('/\s*-\s*(Édition|Edition|Collector|Simple|Spéciale|Digibook|Ultimate|Intégrale|Combo|SteelBook|Boîtier).*$/i', '', $clean);
$clean = preg_replace('/\s*-\s*(Édition|Edition|Collector|Simple|Spéciale|Speciale|Digibook|Ultimate|Intégrale|Integrale).*$/i', '', $clean); $clean = preg_replace('/\s*(Blu-ray|DVD|4K|UHD|VHS|BDRip)\s*$/i', '', $clean);
// Enlever "Combo Blu-ray + DVD"
$clean = preg_replace('/\s*\[Combo.*?\]\s*/i', '', $clean);
// Enlever "Blu-ray", "DVD", "4K", "UHD" à la fin
$clean = preg_replace('/\s*(Blu-ray|DVD|4K|UHD|VHS)\s*$/i', '', $clean);
// Enlever " - Édition X DVD"
$clean = preg_replace('/\s*-\s*Édition\s+\d+\s*DVD\s*$/i', '', $clean); $clean = preg_replace('/\s*-\s*Édition\s+\d+\s*DVD\s*$/i', '', $clean);
// Nettoyer les espaces multiples et tirets en trop return trim(preg_replace('/\s{2,}/', ' ', $clean));
$clean = preg_replace('/\s*-\s*$/', '', $clean);
$clean = preg_replace('/\s{2,}/', ' ', $clean);
return trim($clean);
} }
// ── RÉCUPÉRATION IMAGE VIA EAN (UPCitemdb - spécialisé DVD/Blu-ray) ── // ── 1. MOVIEPOSTERDB (spécialisé jaquettes DVD/Blu-ray) ──
function fetchImageByEAN($ean, $pdo = null) { function fetchMoviePosterDB($title, $year, $pdo) {
$cacheKey = 'mpdb_' . md5(strtolower(cleanTitle($title)) . '|' . $year);
$cached = getCache($pdo, $cacheKey);
if ($cached) return $cached;
$url = "https://api.movieposterdb.com/v1/search?apikey=free&q=" . urlencode(cleanTitle($title)) . "&year=" . $year;
$res = httpGet($url, 4);
if (!$res) return null;
$data = json_decode($res, true);
if (empty($data['results'][0]['poster'])) return null;
$poster = $data['results'][0]['poster'];
setCache($pdo, $cacheKey, ['poster' => $poster], 'mpdb');
return ['poster' => $poster];
}
// ── 2. UPCitemdb (spécialisé codes-barres DVD/Blu-ray) ──
function fetchUPCitemdb($ean, $pdo) {
if (empty($ean) || strlen($ean) < 10) return null; if (empty($ean) || strlen($ean) < 10) return null;
$cacheKey = 'upc_' . $ean;
$cached = getCache($pdo, $cacheKey);
if ($cached) return $cached;
// Vérifier le cache
if ($pdo) {
try {
$stmt = $pdo->prepare("SELECT image_url FROM cache_ean WHERE ean = ? AND created_at > ?");
$stmt->execute([$ean, time() - TMDB_CACHE_TTL]);
$row = $stmt->fetch();
if ($row && !empty($row['image_url'])) return $row['image_url'];
} catch (\Exception $e) { /* ignore */ }
}
// UPCitemdb API (gratuit, spécialisé DVD/Blu-ray/CD)
$url = "https://api.upcitemdb.com/prod/trial/lookup?upc={$ean}"; $url = "https://api.upcitemdb.com/prod/trial/lookup?upc={$ean}";
$res = httpGet($url, 6); $res = httpGet($url, 4);
if (!$res) return null;
if ($res) {
$data = json_decode($res, true); $data = json_decode($res, true);
if (!empty($data['items'][0]['images'][0])) { if (empty($data['items'][0]['images'][0])) return null;
$imageUrl = $data['items'][0]['images'][0];
// Sauvegarder dans le cache $poster = $data['items'][0]['images'][0];
if ($pdo) { setCache($pdo, $cacheKey, ['poster' => $poster], 'upc');
try { return ['poster' => $poster];
$stmt = $pdo->prepare("REPLACE INTO cache_ean (ean, image_url, source, created_at) VALUES (?, ?, 'upcitemdb', ?)");
$stmt->execute([$ean, $imageUrl, time()]);
} catch (\Exception $e) { /* ignore */ }
}
return $imageUrl;
}
} }
// Fallback : Open Library (pour les livres/CD) // ── 3. TMDB (fallback avec curl_multi) ──
$url = "https://openlibrary.org/api/books?bibkeys=ISBN:{$ean}&jscmd=data&format=json"; function fetchTMDB($title, $year, $apiKey, $pdo) {
$res = httpGet($url, 5);
if ($res) {
$data = json_decode($res, true);
$key = "ISBN:{$ean}";
if (isset($data[$key])) {
$cover = $data[$key]['cover'] ?? [];
$imageUrl = $cover['large'] ?? $cover['medium'] ?? $cover['small'] ?? null;
if ($imageUrl) {
if ($pdo) {
try {
$stmt = $pdo->prepare("REPLACE INTO cache_ean (ean, image_url, source, created_at) VALUES (?, ?, 'openlibrary', ?)");
$stmt->execute([$ean, $imageUrl, time()]);
} catch (\Exception $e) { /* ignore */ }
}
return $imageUrl;
}
}
}
return null;
}
// ── TMDB AVEC CACHE + curl_multi ──
function fetchTmdbData($title, $year, $apiKey, $pdo = null) {
if (empty($apiKey) || empty($title)) return null; if (empty($apiKey) || empty($title)) return null;
$cleanTitle = cleanTitle($title);
$cleanTitle = cleanTitleForTmdb($title); $cacheKey = 'tmdb_' . md5(strtolower($cleanTitle) . '|' . $year);
$cacheKey = md5(strtolower($cleanTitle) . '|' . $year); $cached = getCache($pdo, $cacheKey);
if ($cached) return $cached;
// Vérifier le cache
if ($pdo) {
try {
$stmt = $pdo->prepare("SELECT data FROM cache_tmdb WHERE cache_key = ? AND created_at > ?");
$stmt->execute([$cacheKey, time() - TMDB_CACHE_TTL]);
$row = $stmt->fetch();
if ($row) return json_decode($row['data'], true);
} catch (\Exception $e) { /* ignore */ }
}
$searchUrl = "https://api.themoviedb.org/3/search/movie?api_key={$apiKey}&query=" . urlencode($cleanTitle) . "&year={$year}&language=fr-FR"; $searchUrl = "https://api.themoviedb.org/3/search/movie?api_key={$apiKey}&query=" . urlencode($cleanTitle) . "&year={$year}&language=fr-FR";
$searchRes = httpGet($searchUrl, 8); $searchRes = httpGet($searchUrl, 5);
if (!$searchRes) return null; if (!$searchRes) return null;
$searchData = json_decode($searchRes, true); $searchData = json_decode($searchRes, true);
if (empty($searchData['results'])) { if (empty($searchData['results'])) {
// 2ème tentative sans l'année // Retry sans année
$searchUrl2 = "https://api.themoviedb.org/3/search/movie?api_key={$apiKey}&query=" . urlencode($cleanTitle) . "&language=fr-FR"; $searchUrl2 = "https://api.themoviedb.org/3/search/movie?api_key={$apiKey}&query=" . urlencode($cleanTitle) . "&language=fr-FR";
$searchRes2 = httpGet($searchUrl2, 8); $searchRes2 = httpGet($searchUrl2, 5);
if ($searchRes2) { if ($searchRes2) {
$searchData2 = json_decode($searchRes2, true); $searchData2 = json_decode($searchRes2, true);
if (!empty($searchData2['results'])) $searchData = $searchData2; if (!empty($searchData2['results'])) $searchData = $searchData2;
} }
} }
if (empty($searchData['results'])) return null; if (empty($searchData['results'])) return null;
$movie = $searchData['results'][0]; $movie = $searchData['results'][0];
@@ -212,14 +174,10 @@ function fetchTmdbData($title, $year, $apiKey, $pdo = null) {
if (function_exists('curl_multi_init')) { if (function_exists('curl_multi_init')) {
$mh = curl_multi_init(); $mh = curl_multi_init();
$handles = [];
$ch1 = curl_init("https://api.themoviedb.org/3/movie/{$movieId}/credits?api_key={$apiKey}&language=fr-FR"); $ch1 = curl_init("https://api.themoviedb.org/3/movie/{$movieId}/credits?api_key={$apiKey}&language=fr-FR");
$ch2 = curl_init("https://api.themoviedb.org/3/movie/{$movieId}/watch/providers?api_key={$apiKey}"); $ch2 = curl_init("https://api.themoviedb.org/3/movie/{$movieId}/watch/providers?api_key={$apiKey}");
curl_setopt_array($ch1, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 4, CURLOPT_SSL_VERIFYPEER => false]);
curl_setopt_array($ch1, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 6, CURLOPT_SSL_VERIFYPEER => false]); curl_setopt_array($ch2, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 4, CURLOPT_SSL_VERIFYPEER => false]);
curl_setopt_array($ch2, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 6, CURLOPT_SSL_VERIFYPEER => false]);
curl_multi_add_handle($mh, $ch1); curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2); curl_multi_add_handle($mh, $ch2);
@@ -228,7 +186,6 @@ function fetchTmdbData($title, $year, $apiKey, $pdo = null) {
$creditsRes = curl_multi_getcontent($ch1); $creditsRes = curl_multi_getcontent($ch1);
$watchRes = curl_multi_getcontent($ch2); $watchRes = curl_multi_getcontent($ch2);
curl_multi_remove_handle($mh, $ch1); curl_close($ch1); curl_multi_remove_handle($mh, $ch1); curl_close($ch1);
curl_multi_remove_handle($mh, $ch2); curl_close($ch2); curl_multi_remove_handle($mh, $ch2); curl_close($ch2);
curl_multi_close($mh); curl_multi_close($mh);
@@ -241,7 +198,6 @@ function fetchTmdbData($title, $year, $apiKey, $pdo = null) {
} }
} }
} }
if ($watchRes) { if ($watchRes) {
$watchData = json_decode($watchRes, true); $watchData = json_decode($watchRes, true);
$frProviders = $watchData['results']['FR'] ?? []; $frProviders = $watchData['results']['FR'] ?? [];
@@ -256,20 +212,12 @@ function fetchTmdbData($title, $year, $apiKey, $pdo = null) {
} }
$result = ['director' => $director, 'poster' => $poster, 'streaming' => $streaming]; $result = ['director' => $director, 'poster' => $poster, 'streaming' => $streaming];
setCache($pdo, $cacheKey, $result, 'tmdb');
// Sauvegarder dans le cache
if ($pdo) {
try {
$stmt = $pdo->prepare("REPLACE INTO cache_tmdb (cache_key, data, created_at) VALUES (?, ?, ?)");
$stmt->execute([$cacheKey, json_encode($result), time()]);
} catch (\Exception $e) { /* ignore */ }
}
return $result; return $result;
} }
function detectFormat($title, $description = '') { function detectFormat($title, $desc = '') {
$t = strtoupper($title . ' ' . $description); $t = strtoupper($title . ' ' . $desc);
if (strpos($t, '4K') !== false || strpos($t, 'UHD') !== false) return 'Blu-ray 4K'; if (strpos($t, '4K') !== false || strpos($t, 'UHD') !== false) return 'Blu-ray 4K';
if (strpos($t, 'BLU-RAY') !== false || strpos($t, 'BLURAY') !== false) return 'Blu-ray'; if (strpos($t, 'BLU-RAY') !== false || strpos($t, 'BLURAY') !== false) return 'Blu-ray';
if (strpos($t, 'DVD') !== false) return 'DVD'; if (strpos($t, 'DVD') !== false) return 'DVD';
@@ -279,28 +227,28 @@ function detectFormat($title, $description = '') {
} }
function extractYear($dateStr) { function extractYear($dateStr) {
if (preg_match('/(\d{4})/', $dateStr, $matches)) return $matches[1]; if (preg_match('/(\d{4})/', $dateStr, $m)) return $m[1];
return ''; return '';
} }
// ── ROUTEUR PRINCIPAL ── // ── ROUTEUR ──
$action = $_GET['action'] ?? ''; $action = $_GET['action'] ?? '';
$data = json_decode(file_get_contents('php://input'), true) ?? []; $data = json_decode(file_get_contents('php://input'), true) ?? [];
switch ($action) { switch ($action) {
case 'check_security_status': case 'check_security_status':
$stmt = $pdo->query("SELECT COUNT(*) FROM users"); echo json_encode(["is_blank" => ($pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() == 0)]);
echo json_encode(["is_blank" => ($stmt->fetchColumn() == 0)]);
break; break;
case 'login': case 'login':
$stmt = $pdo->query("SELECT COUNT(*) FROM users"); if ($pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() == 0) {
if ($stmt->fetchColumn() == 0) { echo json_encode(["success" => true, "token" => md5(ENCRYPTION_KEY . 'session'), "blank" => true]); } echo json_encode(["success" => true, "token" => md5(ENCRYPTION_KEY . 'session'), "blank" => true]);
else { } else {
$stmt = $pdo->prepare("SELECT password_hash FROM users WHERE username = 'admin'"); $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]); } if ($user && password_verify($data['password'] ?? '', $user['password_hash'])) {
else { http_response_code(401); echo json_encode(["error" => "Mot de passe incorrect."]); } 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."]); }
} }
break; break;
@@ -333,7 +281,7 @@ switch ($action) {
$type = $data['type'] ?? 'critique'; $type = $data['type'] ?? 'critique';
$id = !empty($data['id']) ? $data['id'] : makeStableId($data['title'] ?? '', $data['year'] ?? '0000'); $id = !empty($data['id']) ? $data['id'] : makeStableId($data['title'] ?? '', $data['year'] ?? '0000');
if (empty($data['director']) || empty($data['poster'])) { if (empty($data['director']) || empty($data['poster'])) {
$tmdbData = fetchTmdbData($data['title'] ?? '', $data['year'] ?? '', getTmdbApiKey($pdo), $pdo); $tmdbData = fetchTMDB($data['title'] ?? '', $data['year'] ?? '', getTmdbApiKey($pdo), $pdo);
if ($tmdbData) { if ($tmdbData) {
if (empty($data['director'])) $data['director'] = $tmdbData['director']; if (empty($data['director'])) $data['director'] = $tmdbData['director'];
if (empty($data['poster'])) $data['poster'] = $tmdbData['poster']; if (empty($data['poster'])) $data['poster'] = $tmdbData['poster'];
@@ -367,13 +315,14 @@ switch ($action) {
else { http_response_code(400); echo json_encode(["success" => false, "error" => "Aucun élément sélectionné."]); } else { http_response_code(400); echo json_encode(["success" => false, "error" => "Aucun élément sélectionné."]); }
break; break;
// ── IMPORT PAR LOTS OPTIMISÉ ──
case 'import_batch': case 'import_batch':
checkAuth($pdo); checkAuth($pdo);
$items = $data['items'] ?? []; $items = $data['items'] ?? [];
$type = $data['type'] ?? 'videotheque'; $type = $data['type'] ?? 'videotheque';
$tmdbApiKey = getTmdbApiKey($pdo); $tmdbApiKey = getTmdbApiKey($pdo);
$imported = 0; $imported = 0;
$stats = ['ean_hits' => 0, 'tmdb_hits' => 0, 'no_image' => 0, 'ean_miss' => [], 'tmdb_miss' => []]; $stats = ['mpdb_hits' => 0, 'upc_hits' => 0, 'tmdb_hits' => 0, 'no_image' => 0];
$pdo->beginTransaction(); $pdo->beginTransaction();
@@ -403,30 +352,33 @@ switch ($action) {
$poster = $rowData['poster'] ?? $rowData['Poster'] ?? $rowData['image'] ?? ''; $poster = $rowData['poster'] ?? $rowData['Poster'] ?? $rowData['image'] ?? '';
// 1. Priorité : EAN via UPCitemdb // 1. UPCitemdb (par code-barres) - le plus fiable pour DVD/Blu-ray
if (empty($poster) && !empty($ean)) { if (empty($poster) && !empty($ean)) {
$eanImage = fetchImageByEAN($ean, $pdo); $upcData = fetchUPCitemdb($ean, $pdo);
if ($eanImage) { if ($upcData && !empty($upcData['poster'])) {
$poster = $eanImage; $poster = $upcData['poster'];
$stats['ean_hits']++; $stats['upc_hits']++;
} else {
$stats['ean_miss'][] = $ean;
} }
} }
// 2. Fallback : TMDB avec titre nettoyé // 2. MoviePosterDB (par titre) - spécialisé jaquettes physiques
if (empty($poster)) {
$mpdbData = fetchMoviePosterDB($title, $year, $pdo);
if ($mpdbData && !empty($mpdbData['poster'])) {
$poster = $mpdbData['poster'];
$stats['mpdb_hits']++;
}
}
// 3. TMDB (fallback) - affiches de films
if (empty($poster) && $tmdbApiKey) { if (empty($poster) && $tmdbApiKey) {
$tmdbData = fetchTmdbData($title, $year, $tmdbApiKey, $pdo); $tmdbData = fetchTMDB($title, $year, $tmdbApiKey, $pdo);
if ($tmdbData) { if ($tmdbData) {
if (empty($director)) $director = $tmdbData['director']; if (empty($director)) $director = $tmdbData['director'];
if (!empty($tmdbData['poster'])) { if (!empty($tmdbData['poster'])) {
$poster = $tmdbData['poster']; $poster = $tmdbData['poster'];
$stats['tmdb_hits']++; $stats['tmdb_hits']++;
} else {
$stats['tmdb_miss'][] = $title;
} }
} else {
$stats['tmdb_miss'][] = $title;
} }
} }
@@ -454,15 +406,3 @@ switch ($action) {
echo json_encode(["success" => true, "imported" => $imported, "stats" => $stats]); echo json_encode(["success" => true, "imported" => $imported, "stats" => $stats]);
break; break;
} }
function fetchPosterFromOMDb($title, $year) {
$apiKey = "VOTRE_CLE_OMDB"; // À ajouter dans votre table config
$url = "http://www.omdbapi.com/?t=" . urlencode($title) . "&y=" . $year . "&apikey=" . $apiKey;
$response = @file_get_contents($url);
$data = json_decode($response, true);
if (isset($data['Poster']) && $data['Poster'] !== 'N/A') {
return $data['Poster'];
}
return null;
}