diff --git a/api/version/media-url.php b/api/version/media-url.php index 0b883a0..d661bc9 100644 --- a/api/version/media-url.php +++ b/api/version/media-url.php @@ -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) { diff --git a/api/webhook.php b/api/webhook.php index fddf376..e4e4890 100644 --- a/api/webhook.php +++ b/api/webhook.php @@ -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