Update MediaService.php

This commit is contained in:
Lizandro Guarnizo
2026-02-21 09:27:09 -05:00
parent ad04c49d27
commit 07333be7ce
+19 -5
View File
@@ -23,7 +23,7 @@ class MediaService {
}
public function fetchAndStoreFromGraph($mediaId, $subdir = '') {
// Obtener metadata (url)
// Obtener metadata (url) via Graph API
$endpoint = "{$this->apiUrl}/{$mediaId}";
$ch = curl_init();
curl_setopt_array($ch, [
@@ -46,11 +46,25 @@ class MediaService {
$mediaUrl = $decoded['url'] ?? ($decoded['data'][0]['url'] ?? null);
if (!$mediaUrl) throw new Exception('No media url from Graph');
// Descargar contenido (primer intento)
$content = $this->downloadUrl($mediaUrl);
// Descargar contenido: primero wget (más confiable con Facebook CDN), luego curl como fallback
$content = $this->downloadWithWget($mediaUrl, !empty($this->token) ? ['Authorization: Bearer ' . $this->token] : []);
if ($content === false) {
// Reintentar con header Referer (algunos endpoints requieren referer)
$content = $this->downloadUrl($mediaUrl, ['Referer: https://graph.facebook.com']);
// Obtener URL fresca del Graph API (la anterior puede haber expirado tras el intento fallido)
error_log("[MediaService] wget failed, trying curl with fresh URL...");
$ch2 = curl_init($endpoint);
curl_setopt_array($ch2, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $this->token],
CURLOPT_TIMEOUT => 15,
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
]);
$resp2 = curl_exec($ch2);
curl_close($ch2);
$decoded2 = json_decode($resp2, true);
$freshUrl = $decoded2['url'] ?? $mediaUrl;
$content = $this->downloadUrl($freshUrl);
}
if ($content === false) throw new Exception('Failed to download media content from ' . $mediaUrl);