This commit is contained in:
Lizandro Guarnizo
2026-02-20 11:01:33 -05:00
parent a35a6725fc
commit c965135af9
2 changed files with 57 additions and 0 deletions
+51
View File
@@ -137,6 +137,57 @@ if ($mediaId) {
}
}
// ── Si no hay archivo local, descargar con MediaService y guardar como cache permanente ──
if ($mediaId) {
try {
require_once __DIR__ . '/../../classes/MediaService.php';
$ms = new MediaService();
$subdir = date('Y/m');
$result = $ms->fetchAndStoreFromGraph($mediaId, $subdir);
if ($result && !empty($result['local_file'])) {
// Actualizar BD para que próximas peticiones se sirvan desde local
try {
$db = $db ?? Database::getInstance();
$db->query(
"UPDATE conversations SET local_file = :lf, local_thumb = :lt, mime_type = :mt WHERE (media_url = :mid OR whatsapp_media_id = :mid2) AND (local_file IS NULL OR local_file = '')",
[
'lf' => $result['local_file'],
'lt' => $result['local_thumb'] ?? null,
'mt' => $result['mime_type'] ?? null,
'mid' => $mediaId,
'mid2' => $mediaId
]
);
media_log("Auto-cached media {$mediaId}{$result['local_file']}");
} catch (Exception $dbErr) {
media_log("DB update failed after caching media {$mediaId}: " . $dbErr->getMessage());
}
// Servir el archivo recién descargado
$localPath = realpath(__DIR__ . '/../../' . ltrim($result['local_file'], '/'));
if ($localPath && file_exists($localPath)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$ctype = finfo_file($finfo, $localPath) ?: ($result['mime_type'] ?? 'application/octet-stream');
finfo_close($finfo);
header_remove('Content-Type');
header('Cache-Control: public, max-age=86400');
header('Content-Type: ' . $ctype);
header('Content-Length: ' . filesize($localPath));
if ($download) {
$fname = basename($localPath);
header('Content-Disposition: attachment; filename="' . $fname . '"');
}
readfile($localPath);
exit;
}
}
} catch (Exception $e) {
media_log("Auto-download failed for media {$mediaId}: " . $e->getMessage());
// Continuar con Graph API proxy como fallback
}
}
$mediaUrl = null;
if ($providedUrl) {
+6
View File
@@ -209,6 +209,12 @@ class WhatsAppWebhook {
$mimeType = $message['document']['mime_type'] ?? null;
$filename = $message['document']['filename'] ?? null;
} elseif (isset($message['sticker'])) {
$messageType = 'sticker';
$mediaUrl = $message['sticker']['url'] ?? ($message['sticker']['id'] ?? null);
$mimeType = $message['sticker']['mime_type'] ?? null;
$filename = $message['sticker']['filename'] ?? null;
}
// Log debug (temporal) para verificar cómo llegan media_url/filename