Actualiser api.php

This commit is contained in:
2026-06-24 13:23:48 +02:00
parent a2d174df75
commit ab9e60b5dd
+142 -181
View File
@@ -25,7 +25,6 @@ try {
$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, actors TEXT)");
try { $pdo->exec("ALTER TABLE videotheque ADD COLUMN actors TEXT AFTER description"); } catch (\Exception $e) {}
// 🔥 SUPPRESSION DE LA TABLE CACHE SI ELLE EXISTE ENCORE
try { $pdo->exec("DROP TABLE IF EXISTS cache_api"); } catch (\Exception $e) {}
} catch (\PDOException $e) { echo json_encode(["error" => "Erreur BDD : " . $e->getMessage()]); exit; }
@@ -106,32 +105,12 @@ function extractYear($dateStr) {
return '';
}
// ── 1. API UPCitemDB (SANS CACHE) ──
function fetchUPCitemdb($ean, $pdo) {
if (empty($ean) || strlen($ean) < 8) return null;
$url = "https://api.upcitemdb.com/prod/trial/lookup?upc=" . urlencode($ean);
$res = httpGet($url, 5);
if (!$res) return null;
$data = json_decode($res, true);
if (isset($data['code']) && $data['code'] === 'OK' && !empty($data['items'])) {
$item = $data['items'][0];
return [
'title' => $item['title'] ?? '',
'poster' => $item['images'][0] ?? '',
'publisher' => $item['brand'] ?? $item['publisher'] ?? '',
'format' => detectFormat($item['title'] ?? '', $item['description'] ?? '')
];
}
return null;
}
// ── 2. API DVDFr (SANS CACHE - Récupération complète) ──
// ── 1. API DVDFr (SANS CACHE) ──
function fetchDVDFr($ean, $pdo) {
if (empty($ean) || strlen($ean) < 8) return null;
$ua = 'MonCinema/1.0 (collection privée; contact@moncineapp.fr)';
// Étape 1 : recherche par gencode → récupère l'id DVDFr
$searchUrl = "https://www.dvdfr.com/api/search.php?gencode=" . urlencode($ean);
$ch = curl_init($searchUrl);
curl_setopt_array($ch, [
@@ -155,7 +134,6 @@ function fetchDVDFr($ean, $pdo) {
$dvdId = (string)$xml->dvd[0]->id;
if (empty($dvdId)) return null;
// Étape 2 : fiche complète via dvd.php?id=
$ficheUrl = "https://www.dvdfr.com/api/dvd.php?id=" . urlencode($dvdId);
$ch2 = curl_init($ficheUrl);
curl_setopt_array($ch2, [
@@ -178,12 +156,10 @@ function fetchDVDFr($ean, $pdo) {
$dvd = $fiche->dvd[0];
// Extraction de la jaquette
$poster = '';
if (isset($dvd->cover)) $poster = (string)$dvd->cover;
if (empty($poster) && isset($dvd->covers->cover[0])) $poster = (string)$dvd->covers->cover[0];
// Extraction des métadonnées techniques
$result = [
'poster' => $poster,
'publisher' => isset($dvd->editeur) ? (string)$dvd->editeur : '',
@@ -196,19 +172,17 @@ function fetchDVDFr($ean, $pdo) {
return (!empty($result['poster']) || !empty($result['publisher'])) ? $result : null;
}
// ── 2. API TMDB (SANS CACHE - TITRE FRANÇAIS) ──
function fetchTMDBFull($title, $year, $apiKey, $pdo) {
if (empty($apiKey) || empty($title)) return null;
$cleanTitle = cleanTitle($title);
$cacheKey = 'tmdb_full_' . md5(strtolower($cleanTitle) . '|' . $year);
$cached = getCache($pdo, $cacheKey);
if ($cached) return $cached;
// 1. Recherche avec l'année
// 🔥 SUPPRESSION DES APPELS À getCache() QUI N'EXISTE PLUS
$searchUrl = "https://api.themoviedb.org/3/search/movie?api_key={$apiKey}&query=" . urlencode($cleanTitle) . "&year={$year}&language=fr-FR";
$searchRes = httpGet($searchUrl, 5);
$searchData = $searchRes ? json_decode($searchRes, true) : [];
// 2. Fallback sans l'année
if (empty($searchData['results'])) {
$searchUrl = "https://api.themoviedb.org/3/search/movie?api_key={$apiKey}&query=" . urlencode($cleanTitle) . "&language=fr-FR";
$searchRes = httpGet($searchUrl, 5);
@@ -218,16 +192,13 @@ function fetchTMDBFull($title, $year, $apiKey, $pdo) {
if (empty($searchData['results'])) return null;
$movieId = $searchData['results'][0]['id'];
// 🔥 AJOUT : On demande aussi les translations pour récupérer le titre français
$detailsUrl = "https://api.themoviedb.org/3/movie/{$movieId}?api_key={$apiKey}&append_to_response=credits,watch/providers,translations&language=fr-FR";
$detailsRes = httpGet($detailsUrl, 5);
if (!$detailsRes) return null;
$details = json_decode($detailsRes, true);
// 🔥 RÉCUPÉRATION DU TITRE FRANÇAIS
$frenchTitle = $details['title'] ?? ''; // Titre par défaut (peut être l'original)
$frenchTitle = $details['title'] ?? '';
// Chercher le titre français dans les traductions
if (!empty($details['translations']['translations'])) {
foreach ($details['translations']['translations'] as $translation) {
if ($translation['iso_3166_1'] === 'FR' && !empty($translation['data']['title'])) {
@@ -237,7 +208,6 @@ function fetchTMDBFull($title, $year, $apiKey, $pdo) {
}
}
// Extraction Réalisateurs
$director = '';
if (!empty($details['credits']['crew'])) {
$directorsList = [];
@@ -247,17 +217,14 @@ function fetchTMDBFull($title, $year, $apiKey, $pdo) {
$director = implode(', ', $directorsList);
}
// Extraction Acteurs (Top 4)
$cast = [];
if (!empty($details['credits']['cast'])) {
$topCast = array_slice($details['credits']['cast'], 0, 4);
foreach ($topCast as $actor) $cast[] = $actor['name'];
}
// Synopsis
$overview = $details['overview'] ?? '';
// Streaming
$streaming = '';
$frProviders = $details['watch/providers']['results']['FR'] ?? [];
$platforms = [];
@@ -269,7 +236,7 @@ function fetchTMDBFull($title, $year, $apiKey, $pdo) {
if (!empty($platforms)) $streaming = implode(', ', array_unique($platforms));
$result = [
'title' => $frenchTitle, // 🔥 Titre français prioritaire
'title' => $frenchTitle,
'year' => !empty($details['release_date']) ? substr($details['release_date'], 0, 4) : '',
'director' => $director,
'poster' => !empty($details['poster_path']) ? "https://image.tmdb.org/t/p/w500" . $details['poster_path'] : '',
@@ -279,7 +246,8 @@ function fetchTMDBFull($title, $year, $apiKey, $pdo) {
'cast' => $cast
];
setCache($pdo, $cacheKey, $result, 'tmdb');
// 🔥 SUPPRESSION DE L'APPEL À setCache() QUI N'EXISTE PLUS
return $result;
}
@@ -354,7 +322,6 @@ switch ($action) {
'length' => '', 'number_of_discs' => 1, 'aspect_ratio' => '', 'actors' => ''
];
// DVDFr en priorité
$dvdfrData = fetchDVDFr($ean, $pdo);
if (!empty($dvdfrData)) {
if (!empty($dvdfrData['poster'])) $result['poster'] = $dvdfrData['poster'];
@@ -365,7 +332,6 @@ switch ($action) {
if (!empty($dvdfrData['discs'])) $result['number_of_discs'] = (int)$dvdfrData['discs'];
}
// TMDB pour le reste
$tmdbKey = getTmdbApiKey($pdo);
if ($tmdbKey && !empty($result['publisher'])) {
$tmdbData = fetchTMDBFull($result['publisher'], '', $tmdbKey, $pdo);
@@ -423,156 +389,151 @@ switch ($action) {
else { http_response_code(400); echo json_encode(["success" => false, "error" => "Aucun élément sélectionné."]); }
break;
case 'import_batch':
checkAuth($pdo);
set_time_limit(0);
$items = $data['items'] ?? [];
$type = $data['type'] ?? 'videotheque';
$tmdbApiKey = getTmdbApiKey($pdo);
$imported = 0;
$debugLog = [];
case 'import_batch':
checkAuth($pdo);
set_time_limit(0);
$items = $data['items'] ?? [];
$type = $data['type'] ?? 'videotheque';
$tmdbApiKey = getTmdbApiKey($pdo);
$imported = 0;
$debugLog = [];
$pdo->beginTransaction(); // 🔥 UNE SEULE TRANSACTION
try {
foreach ($items as $rowData) {
$title = $rowData['title'] ?? $rowData['Name'] ?? $rowData['Title'] ?? 'Sans titre';
$publishDate = $rowData['publish_date'] ?? $rowData['Year'] ?? $rowData['year'] ?? $rowData['Date'] ?? '';
$year = extractYear($publishDate);
$id = makeStableId($type, $title, $year);
$pdo->beginTransaction();
try {
foreach ($items as $rowData) {
$title = $rowData['title'] ?? $rowData['Name'] ?? $rowData['Title'] ?? 'Sans titre';
$publishDate = $rowData['publish_date'] ?? $rowData['Year'] ?? $rowData['year'] ?? $rowData['Date'] ?? '';
$year = extractYear($publishDate);
$id = makeStableId($type, $title, $year);
if ($type === 'videotheque') {
// Acteurs depuis CSV
$csvActors = $rowData['ensemble'] ?? $rowData['creators'] ?? '';
$actors = '';
if (!empty($csvActors)) {
$actorsArray = array_map('trim', explode(',', $csvActors));
$actors = implode(', ', array_slice($actorsArray, 0, 4));
}
// Normalisation EAN
$ean = $rowData['ean_isbn13'] ?? $rowData['EAN'] ?? '';
if (!empty($ean)) {
$eanFloat = floatval($ean);
if ($eanFloat > 0) $ean = (string) round($eanFloat);
$ean = preg_replace('/[^0-9]/', '', $ean);
}
$lengthRaw = $rowData['length'] ?? '';
$length = '';
if ($lengthRaw !== '' && $lengthRaw !== null) {
$lengthVal = floatval($lengthRaw);
if ($lengthVal > 0) $length = (string) round($lengthVal);
}
$discsRaw = $rowData['number_of_discs'] ?? '';
$discs = (is_numeric($discsRaw) && floatval($discsRaw) > 0) ? (int) round(floatval($discsRaw)) : 1;
$description = $rowData['description'] ?? $rowData['Description'] ?? '';
$publisher = $rowData['publisher'] ?? '';
$aspect = $rowData['aspect_ratio'] ?? '';
$format = $rowData['format'] ?? detectFormat($title, $description);
$poster = $rowData['poster'] ?? '';
$director = '';
// 1. DVDFr (priorité pour les supports physiques FR)
if (!empty($ean)) {
$dvdfrData = fetchDVDFr($ean, $pdo);
if (!empty($dvdfrData)) {
if (!empty($dvdfrData['poster'])) $poster = $dvdfrData['poster'];
if (!empty($dvdfrData['publisher'])) $publisher = $dvdfrData['publisher'];
if (!empty($dvdfrData['format'])) $format = $dvdfrData['format'];
if (!empty($dvdfrData['length']) && empty($length)) $length = $dvdfrData['length'];
if (!empty($dvdfrData['aspect']) && empty($aspect)) $aspect = $dvdfrData['aspect'];
if (!empty($dvdfrData['discs']) && $discs === 1) $discs = (int)$dvdfrData['discs'];
if ($type === 'videotheque') {
$csvActors = $rowData['ensemble'] ?? $rowData['creators'] ?? '';
$actors = '';
if (!empty($csvActors)) {
$actorsArray = array_map('trim', explode(',', $csvActors));
$actors = implode(', ', array_slice($actorsArray, 0, 4));
}
}
// 2. TMDB (réalisateur, synopsis, acteurs)
if ($tmdbApiKey && !empty($title)) {
$tmdbTitle = $title;
$tmdbTitle = preg_replace('/\s*[\[\(].*?[\]\)]\s*/', '', $tmdbTitle);
$tmdbTitle = preg_replace('/\s*-\s*(Édition|Edition|Collector|Simple|Spéciale|Digibook|Ultimate|Intégrale|Combo|SteelBook|Boîtier|Coffret).*$/i', '', $tmdbTitle);
$tmdbTitle = preg_replace('/\s*(Blu-ray|Bluray|DVD|4K|Ultra HD|Combo|VHS|BDRip|\[.*\]).*$/i', '', $tmdbTitle);
$tmdbTitle = preg_replace('/\s*(Coffret|Trilogie|Quadrilogie|Collection|Anthologie).*$/i', '', $tmdbTitle);
$tmdbTitle = preg_split('/\s*(\/|\+|:)\s*/', $tmdbTitle)[0];
$tmdbTitle = explode(' - ', $tmdbTitle)[0];
$tmdbTitle = trim($tmdbTitle);
$ean = $rowData['ean_isbn13'] ?? $rowData['EAN'] ?? '';
if (!empty($ean)) {
$eanFloat = floatval($ean);
if ($eanFloat > 0) $ean = (string) round($eanFloat);
$ean = preg_replace('/[^0-9]/', '', $ean);
}
$tmdbData = fetchTMDBFull($tmdbTitle, $year, $tmdbApiKey, $pdo);
if (!$tmdbData && $tmdbTitle !== $title) {
$lengthRaw = $rowData['length'] ?? '';
$length = '';
if ($lengthRaw !== '' && $lengthRaw !== null) {
$lengthVal = floatval($lengthRaw);
if ($lengthVal > 0) $length = (string) round($lengthVal);
}
$discsRaw = $rowData['number_of_discs'] ?? '';
$discs = (is_numeric($discsRaw) && floatval($discsRaw) > 0) ? (int) round(floatval($discsRaw)) : 1;
$description = $rowData['description'] ?? $rowData['Description'] ?? '';
$publisher = $rowData['publisher'] ?? '';
$aspect = $rowData['aspect_ratio'] ?? '';
$format = $rowData['format'] ?? detectFormat($title, $description);
$poster = $rowData['poster'] ?? '';
$director = '';
if (!empty($ean)) {
$dvdfrData = fetchDVDFr($ean, $pdo);
if (!empty($dvdfrData)) {
if (!empty($dvdfrData['poster'])) $poster = $dvdfrData['poster'];
if (!empty($dvdfrData['publisher'])) $publisher = $dvdfrData['publisher'];
if (!empty($dvdfrData['format'])) $format = $dvdfrData['format'];
if (!empty($dvdfrData['length']) && empty($length)) $length = $dvdfrData['length'];
if (!empty($dvdfrData['aspect']) && empty($aspect)) $aspect = $dvdfrData['aspect'];
if (!empty($dvdfrData['discs']) && $discs === 1) $discs = (int)$dvdfrData['discs'];
}
}
if ($tmdbApiKey && !empty($title)) {
$tmdbTitle = $title;
$tmdbTitle = preg_replace('/\s*[\[\(].*?[\]\)]\s*/', '', $tmdbTitle);
$tmdbTitle = preg_replace('/\s*-\s*(Édition|Edition|Collector|Simple|Spéciale|Digibook|Ultimate|Intégrale|Combo|SteelBook|Boîtier|Coffret).*$/i', '', $tmdbTitle);
$tmdbTitle = preg_replace('/\s*(Blu-ray|Bluray|DVD|4K|Ultra HD|Combo|VHS|BDRip|\[.*\]).*$/i', '', $tmdbTitle);
$tmdbTitle = preg_replace('/\s*(Coffret|Trilogie|Quadrilogie|Collection|Anthologie).*$/i', '', $tmdbTitle);
$tmdbTitle = preg_split('/\s*(\/|\+|:)\s*/', $tmdbTitle)[0];
$tmdbTitle = explode(' - ', $tmdbTitle)[0];
$tmdbTitle = trim($tmdbTitle);
$tmdbData = fetchTMDBFull($tmdbTitle, $year, $tmdbApiKey, $pdo);
if (!$tmdbData && $tmdbTitle !== $title) {
$tmdbData = fetchTMDBFull($title, $year, $tmdbApiKey, $pdo);
}
if ($tmdbData) {
if (!empty($tmdbData['title'])) $title = $tmdbData['title'];
if (empty($director)) $director = $tmdbData['director'] ?? '';
if (empty($year) && !empty($tmdbData['year'])) $year = $tmdbData['year'];
if (empty($length) && !empty($tmdbData['length'])) $length = $tmdbData['length'];
if (!empty($tmdbData['overview'])) $description = $tmdbData['overview'];
if (!empty($tmdbData['cast'])) $actors = implode(', ', $tmdbData['cast']);
}
}
$sql = "INSERT INTO videotheque (id, title, year, director, poster, format, length, publisher, ean_isbn13, number_of_discs, aspect_ratio, description, actors)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
title=VALUES(title), year=VALUES(year),
director=IF(VALUES(director)!='',VALUES(director),director),
poster=IF(VALUES(poster)!='',VALUES(poster),poster),
format=IF(VALUES(format)!='',VALUES(format),format),
length=IF(VALUES(length)!='',VALUES(length),length),
publisher=IF(VALUES(publisher)!='',VALUES(publisher),publisher),
ean_isbn13=IF(VALUES(ean_isbn13)!='',VALUES(ean_isbn13),ean_isbn13),
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),
description=IF(VALUES(description)!='',VALUES(description),description),
actors=IF(VALUES(actors)!='',VALUES(actors),actors)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id, $title, $year, $director, $poster, $format, $length, $publisher, $ean, $discs, $aspect, $description, $actors]);
} else {
$ratingRaw = $rowData['Rating'] ?? $rowData['rating'] ?? '';
$rating = ($ratingRaw !== '' && $ratingRaw !== null) ? (float)$ratingRaw : null;
$review = $rowData['Review'] ?? $rowData['review'] ?? '';
$director = ''; $poster = ''; $streaming = '';
if ($tmdbApiKey && !empty($title)) {
$tmdbData = fetchTMDBFull($title, $year, $tmdbApiKey, $pdo);
if ($tmdbData) {
$director = $tmdbData['director'];
$poster = $tmdbData['poster'];
$streaming = $tmdbData['streaming'];
if (empty($year)) $year = $tmdbData['year'];
if (!empty($tmdbData['title'])) $title = $tmdbData['title'];
}
}
if (empty($streaming)) $streaming = 'Support physique / Cinéma';
if ($tmdbData) {
if (!empty($tmdbData['title'])) $title = $tmdbData['title'];
if (empty($director)) $director = $tmdbData['director'] ?? '';
if (empty($year) && !empty($tmdbData['year'])) $year = $tmdbData['year'];
if (empty($length) && !empty($tmdbData['length'])) $length = $tmdbData['length'];
if (!empty($tmdbData['overview'])) $description = $tmdbData['overview'];
if (!empty($tmdbData['cast'])) $actors = implode(', ', $tmdbData['cast']);
}
$sql = "INSERT INTO critiques (id, title, year, director, poster, rating, review, streaming)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
title=VALUES(title), year=VALUES(year),
rating=VALUES(rating),
review=IF(VALUES(review)!='',VALUES(review),review),
director=IF(VALUES(director)!='',VALUES(director),director),
poster=IF(VALUES(poster)!='',VALUES(poster),poster),
streaming=IF(VALUES(streaming)!='',VALUES(streaming),streaming)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id, $title, $year, $director, $poster, $rating, $review, $streaming]);
}
$sql = "INSERT INTO videotheque (id, title, year, director, poster, format, length, publisher, ean_isbn13, number_of_discs, aspect_ratio, description, actors)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
title=VALUES(title), year=VALUES(year),
director=IF(VALUES(director)!='',VALUES(director),director),
poster=IF(VALUES(poster)!='',VALUES(poster),poster),
format=IF(VALUES(format)!='',VALUES(format),format),
length=IF(VALUES(length)!='',VALUES(length),length),
publisher=IF(VALUES(publisher)!='',VALUES(publisher),publisher),
ean_isbn13=IF(VALUES(ean_isbn13)!='',VALUES(ean_isbn13),ean_isbn13),
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),
description=IF(VALUES(description)!='',VALUES(description),description),
actors=IF(VALUES(actors)!='',VALUES(actors),actors)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id, $title, $year, $director, $poster, $format, $length, $publisher, $ean, $discs, $aspect, $description, $actors]);
} else {
// Pour les critiques
$ratingRaw = $rowData['Rating'] ?? $rowData['rating'] ?? '';
$rating = ($ratingRaw !== '' && $ratingRaw !== null) ? (float)$ratingRaw : null;
$review = $rowData['Review'] ?? $rowData['review'] ?? '';
$director = ''; $poster = ''; $streaming = '';
if ($tmdbApiKey && !empty($title)) {
$tmdbData = fetchTMDBFull($title, $year, $tmdbApiKey, $pdo);
if ($tmdbData) {
$director = $tmdbData['director'];
$poster = $tmdbData['poster'];
$streaming = $tmdbData['streaming'];
if (empty($year)) $year = $tmdbData['year'];
if (!empty($tmdbData['title'])) $title = $tmdbData['title'];
}
}
if (empty($streaming)) $streaming = 'Support physique / Cinéma';
$sql = "INSERT INTO critiques (id, title, year, director, poster, rating, review, streaming)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
title=VALUES(title), year=VALUES(year),
rating=VALUES(rating),
review=IF(VALUES(review)!='',VALUES(review),review),
director=IF(VALUES(director)!='',VALUES(director),director),
poster=IF(VALUES(poster)!='',VALUES(poster),poster),
streaming=IF(VALUES(streaming)!='',VALUES(streaming),streaming)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id, $title, $year, $director, $poster, $rating, $review, $streaming]);
$imported++;
}
$imported++;
}
$pdo->commit();
echo json_encode(["success" => true, "imported" => $imported, "debug" => $debugLog]);
$pdo->commit();
echo json_encode(["success" => true, "imported" => $imported, "debug" => $debugLog]);
} catch (\Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
} catch (\Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
http_response_code(500);
echo json_encode(["success" => false, "error" => "Erreur serveur : " . $e->getMessage(), "debug" => $debugLog]);
}
http_response_code(500);
echo json_encode(["success" => false, "error" => "Erreur serveur : " . $e->getMessage(), "debug" => $debugLog]);
}
break;
break;
}