This commit is contained in:
lizandrogd
2026-01-13 00:48:57 -05:00
parent ebf02e5188
commit 83fcabe36f
8 changed files with 1370 additions and 4 deletions
+108
View File
@@ -0,0 +1,108 @@
<?php
/**
* API - Enviar mensaje multimedia
* Fecha: 13 de enero de 2026
*/
require_once '../config/config.php';
// Verificar autenticación
requireAuthentication();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
exit;
}
try {
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
throw new Exception('Datos no válidos');
}
// Validar campos requeridos
if (empty($input['recipient']) || empty($input['media_url']) || empty($input['media_type'])) {
throw new Exception('Faltan campos requeridos: recipient, media_url, media_type');
}
$recipient = $input['recipient'];
$mediaUrl = $input['media_url'];
$mediaType = $input['media_type']; // image, video, audio, document
$caption = $input['caption'] ?? null;
$filename = $input['filename'] ?? null;
// Inicializar servicio de WhatsApp
$whatsapp = new WhatsAppService();
// Enviar según tipo de media
$response = null;
switch ($mediaType) {
case 'image':
$response = $whatsapp->sendImageMessage($recipient, $mediaUrl, $caption);
break;
case 'video':
$response = $whatsapp->sendVideoMessage($recipient, $mediaUrl, $caption);
break;
case 'audio':
$response = $whatsapp->sendAudioMessage($recipient, $mediaUrl);
break;
case 'document':
$response = $whatsapp->sendDocumentMessage($recipient, $mediaUrl, $filename, $caption);
break;
default:
throw new Exception('Tipo de media no soportado: ' . $mediaType);
}
if ($response && isset($response['messages'][0]['id'])) {
// Guardar en base de datos
$db = Database::getInstance();
// Obtener usuario
$user = $db->fetch(
"SELECT id FROM users WHERE phone_number = ?",
[$recipient]
);
if ($user) {
$db->insert('conversations', [
'user_id' => $user['id'],
'message_id' => $response['messages'][0]['id'],
'direction' => 'outgoing',
'message_type' => $mediaType,
'content' => $caption ?? $filename ?? '',
'media_url' => $mediaUrl,
'status' => 'sent',
'created_at' => date('Y-m-d H:i:s')
]);
}
echo json_encode([
'success' => true,
'message' => 'Mensaje multimedia enviado correctamente',
'data' => $response
]);
} else {
throw new Exception('Error al enviar mensaje: ' . json_encode($response));
}
} catch (Exception $e) {
error_log("Error en send_media_message.php: " . $e->getMessage());
http_response_code(500);
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}
?>
+136
View File
@@ -0,0 +1,136 @@
<?php
/**
* API - Subir archivos multimedia
* Fecha: 13 de enero de 2026
*/
require_once '../config/config.php';
// Verificar autenticación
requireAuthentication();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
exit;
}
try {
// Verificar que se subió un archivo
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
throw new Exception('No se recibió ningún archivo o hubo un error en la carga');
}
$file = $_FILES['file'];
$fileSize = $file['size'];
$fileName = basename($file['name']);
$fileTmpPath = $file['tmp_name'];
$fileType = $file['type'];
// Validar tamaño según tipo
$maxSize = 16 * 1024 * 1024; // 16MB por defecto
if (strpos($fileType, 'image/') === 0) {
$maxSize = 5 * 1024 * 1024; // 5MB para imágenes
} elseif (strpos($fileType, 'application/') === 0) {
$maxSize = 100 * 1024 * 1024; // 100MB para documentos
}
if ($fileSize > $maxSize) {
throw new Exception('El archivo es demasiado grande. Máximo: ' . ($maxSize / 1024 / 1024) . 'MB');
}
// Validar tipos de archivo permitidos
$allowedTypes = [
// Imágenes
'image/jpeg', 'image/jpg', 'image/png', 'image/webp',
// Videos
'video/mp4', 'video/3gpp', 'video/quicktime',
// Audios
'audio/aac', 'audio/mp3', 'audio/mpeg', 'audio/ogg', 'audio/amr', 'audio/webm',
// Documentos
'application/pdf',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation'
];
if (!in_array($fileType, $allowedTypes)) {
throw new Exception('Tipo de archivo no permitido: ' . $fileType);
}
// Crear directorio de uploads si no existe
$uploadDir = __DIR__ . '/../uploads/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// Generar nombre único
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$uniqueName = uniqid('media_', true) . '.' . $extension;
$uploadPath = $uploadDir . $uniqueName;
// Mover archivo
if (!move_uploaded_file($fileTmpPath, $uploadPath)) {
throw new Exception('Error al guardar el archivo en el servidor');
}
// Construir URL pública
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$publicUrl = $protocol . '://' . $host . '/whatsapp/uploads/' . $uniqueName;
// Determinar tipo de medio
$mediaType = 'document';
if (strpos($fileType, 'image/') === 0) {
$mediaType = 'image';
} elseif (strpos($fileType, 'video/') === 0) {
$mediaType = 'video';
} elseif (strpos($fileType, 'audio/') === 0) {
$mediaType = 'audio';
}
// Guardar información en base de datos (opcional)
$db = Database::getInstance();
$mediaId = $db->insert('media_files', [
'filename' => $fileName,
'unique_name' => $uniqueName,
'file_type' => $fileType,
'file_size' => $fileSize,
'media_type' => $mediaType,
'file_path' => $uploadPath,
'public_url' => $publicUrl,
'uploaded_by' => $_SESSION['user']['id'] ?? null,
'created_at' => date('Y-m-d H:i:s')
]);
echo json_encode([
'success' => true,
'message' => 'Archivo subido correctamente',
'data' => [
'id' => $mediaId,
'filename' => $fileName,
'url' => $publicUrl,
'type' => $mediaType,
'mime_type' => $fileType,
'size' => $fileSize
]
]);
} catch (Exception $e) {
error_log("Error en upload_media.php: " . $e->getMessage());
http_response_code(500);
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}
?>
+555 -2
View File
@@ -145,6 +145,151 @@ if (empty($user_id)) {
font-size: 0.8rem;
opacity: 0.8;
}
/* Estilos para multimedia */
.attach-btn {
background: transparent;
border: none;
color: #666;
padding: 12px 15px;
cursor: pointer;
font-size: 1.2rem;
}
.attach-btn:hover {
color: #25D366;
}
.media-preview {
padding: 10px;
background: #f0f0f0;
border-radius: 8px;
margin-bottom: 10px;
display: none;
}
.media-preview.show {
display: block;
animation: slideDown 0.3s ease-out;
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.media-preview-content {
display: flex;
align-items: center;
gap: 10px;
}
.media-thumbnail {
width: 60px;
height: 60px;
object-fit: cover;
border-radius: 5px;
}
.media-info {
flex: 1;
}
.media-filename {
font-weight: 500;
font-size: 0.9rem;
color: #333;
}
.media-filesize {
font-size: 0.8rem;
color: #666;
}
.message-media {
margin-top: 8px;
}
.message-media img,
.message-media video {
max-width: 100%;
border-radius: 8px;
margin-top: 5px;
}
.message-media audio {
width: 100%;
margin-top: 5px;
}
.message-document {
display: flex;
align-items: center;
gap: 10px;
padding: 10px;
background: #f0f0f0;
border-radius: 8px;
margin-top: 5px;
text-decoration: none;
color: inherit;
}
.message-document:hover {
background: #e0e0e0;
}
.message-document i {
font-size: 1.5rem;
color: #666;
}
.mic-btn {
background: transparent;
border: none;
color: #666;
padding: 12px 15px;
cursor: pointer;
font-size: 1.2rem;
}
.mic-btn:hover {
color: #25D366;
}
.mic-btn.recording {
color: #dc3545;
animation: pulse 1s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.recording-indicator {
display: none;
padding: 10px;
background: #fff3cd;
border-radius: 8px;
margin-bottom: 10px;
align-items: center;
gap: 10px;
}
.recording-indicator.show {
display: flex;
}
.recording-time {
font-weight: 500;
color: #dc3545;
}
</style>
</head>
<body>
@@ -206,7 +351,44 @@ if (empty($user_id)) {
</div>
</div>
<!-- Indicador de grabación -->
<div class="recording-indicator" id="recordingIndicator">
<i class="fas fa-microphone text-danger"></i>
<span>Grabando audio...</span>
<span class="recording-time" id="recordingTime">0:00</span>
<button type="button" class="btn btn-sm btn-success ms-auto" onclick="stopRecording()">
<i class="fas fa-stop"></i> Detener
</button>
<button type="button" class="btn btn-sm btn-danger" onclick="cancelRecording()">
<i class="fas fa-times"></i>
</button>
</div>
<!-- Preview de multimedia -->
<div class="media-preview" id="mediaPreview">
<div class="media-preview-content">
<img id="mediaThumbnail" class="media-thumbnail" style="display: none;" />
<div class="media-info">
<div class="media-filename" id="mediaFilename"></div>
<div class="media-filesize" id="mediaFilesize"></div>
</div>
<button type="button" class="btn btn-sm btn-danger" onclick="cancelMediaUpload()">
<i class="fas fa-times"></i>
</button>
</div>
<input type="text" class="form-control form-control-sm mt-2" id="mediaCaption"
placeholder="Agregar caption (opcional)...">
</div>
<div class="input-group">
<input type="file" id="fileInput" style="display: none;"
accept="image/*,video/*,audio/*,.pdf,.doc,.docx,.xls,.xlsx" />
<button type="button" class="attach-btn" id="attachBtn" title="Adjuntar archivo">
<i class="fas fa-paperclip"></i>
</button>
<button type="button" class="mic-btn" id="micBtn" title="Grabar audio">
<i class="fas fa-microphone"></i>
</button>
<input type="text" class="form-control" id="messageInput"
placeholder="Escribe un mensaje..."
onkeypress="handleEnterKey(event)">
@@ -339,13 +521,44 @@ if (empty($user_id)) {
messages.forEach(msg => {
const isOutgoing = msg.direction === 'outgoing';
const messageClass = isOutgoing ? 'message-outgoing' : 'message-incoming';
const messageContent = escapeHtml(msg.content) || '<em>Sin contenido</em>';
// Verificar si es multimedia
let contentHtml = '';
if (msg.media_url) {
// Mensaje multimedia
switch (msg.media_type) {
case 'image':
contentHtml = `<img src="${msg.media_url}" alt="Imagen" style="max-width: 100%; border-radius: 8px;">`;
break;
case 'video':
contentHtml = `<video controls style="max-width: 100%; border-radius: 8px;"><source src="${msg.media_url}"></video>`;
break;
case 'audio':
contentHtml = `<audio controls style="width: 100%;"><source src="${msg.media_url}"></audio>`;
break;
case 'document':
const filename = msg.filename || 'Documento';
contentHtml = `<a href="${msg.media_url}" target="_blank" class="message-document">
<i class="fas fa-file-alt"></i>
<span>${filename}</span>
</a>`;
break;
}
if (msg.caption) {
contentHtml += `<div style="margin-top: 5px;">${escapeHtml(msg.caption)}</div>`;
}
} else {
// Mensaje de texto normal
contentHtml = escapeHtml(msg.content) || '<em>Sin contenido</em>';
}
const messageTime = escapeHtml(msg.time || '');
html += `
<div class="d-flex ${isOutgoing ? 'justify-content-end' : 'justify-content-start'}">
<div class="message-bubble ${messageClass}">
<div class="message-content">${messageContent}</div>
<div class="message-content">${contentHtml}</div>
<div class="message-time">
${messageTime} ${isOutgoing ? '<i class="fas fa-check-double text-primary"></i>' : ''}
</div>
@@ -377,6 +590,12 @@ if (empty($user_id)) {
// Enviar mensaje
async function sendMessage() {
// Si hay un archivo seleccionado, enviar multimedia
if (selectedFile) {
await sendMediaMessage();
return;
}
const messageType = document.getElementById('messageType').value;
const messageInput = document.getElementById('messageInput');
const message = messageInput.value.trim();
@@ -568,10 +787,344 @@ if (empty($user_id)) {
showAlert(message, 'danger');
}
// ===== FUNCIONES MULTIMEDIA =====
let selectedFile = null;
let mediaRecorder = null;
let audioChunks = [];
let recordingStartTime = null;
let recordingInterval = null;
// ===== GRABACIÓN DE AUDIO =====
// Iniciar grabación de audio
async function startRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
audioChunks.push(event.data);
}
};
mediaRecorder.onstop = async () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
// Convertir a File object
const audioFile = new File([audioBlob], `audio_${Date.now()}.webm`, {
type: 'audio/webm'
});
selectedFile = audioFile;
showMediaPreview(audioFile);
// Detener el stream
stream.getTracks().forEach(track => track.stop());
};
mediaRecorder.start();
recordingStartTime = Date.now();
// Mostrar indicador de grabación
document.getElementById('recordingIndicator').classList.add('show');
document.getElementById('micBtn').classList.add('recording');
// Actualizar tiempo de grabación
updateRecordingTime();
recordingInterval = setInterval(updateRecordingTime, 1000);
} catch (error) {
console.error('Error al acceder al micrófono:', error);
showAlert('No se pudo acceder al micrófono. Verifica los permisos.', 'danger');
}
}
// Detener grabación
function stopRecording() {
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
clearInterval(recordingInterval);
document.getElementById('recordingIndicator').classList.remove('show');
document.getElementById('micBtn').classList.remove('recording');
}
}
// Cancelar grabación
function cancelRecording() {
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
audioChunks = [];
selectedFile = null;
clearInterval(recordingInterval);
document.getElementById('recordingIndicator').classList.remove('show');
document.getElementById('micBtn').classList.remove('recording');
}
}
// Actualizar tiempo de grabación
function updateRecordingTime() {
if (!recordingStartTime) return;
const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000);
const minutes = Math.floor(elapsed / 60);
const seconds = elapsed % 60;
document.getElementById('recordingTime').textContent =
`${minutes}:${seconds.toString().padStart(2, '0')}`;
}
// ===== FUNCIONES DE ARCHIVOS =====
// Manejar selección de archivo
function handleFileSelect(event) {
const file = event.target.files[0];
if (!file) return;
// Validar tipo de archivo
const allowedTypes = {
image: ['image/jpeg', 'image/png', 'image/jpg'],
video: ['video/mp4', 'video/3gpp'],
audio: ['audio/mpeg', 'audio/mp3', 'audio/aac', 'audio/ogg'],
document: ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
};
let mediaType = null;
for (const [type, mimes] of Object.entries(allowedTypes)) {
if (mimes.includes(file.type)) {
mediaType = type;
break;
}
}
if (!mediaType) {
showAlert('Tipo de archivo no soportado', 'danger');
event.target.value = '';
return;
}
// Validar tamaño
const maxSizes = {
image: 5 * 1024 * 1024, // 5MB
video: 16 * 1024 * 1024, // 16MB
audio: 16 * 1024 * 1024, // 16MB
document: 100 * 1024 * 1024 // 100MB
};
if (file.size > maxSizes[mediaType]) {
showAlert(`Archivo muy grande. Máximo: ${formatFileSize(maxSizes[mediaType])}`, 'danger');
event.target.value = '';
return;
}
selectedFile = file;
showMediaPreview(file);
}
// Mostrar preview del archivo
function showMediaPreview(file) {
const preview = document.getElementById('mediaPreview');
const thumbnail = document.getElementById('mediaThumbnail');
const filename = document.getElementById('mediaFilename');
const filesize = document.getElementById('mediaFilesize');
filename.textContent = file.name;
filesize.textContent = formatFileSize(file.size);
// Mostrar thumbnail si es imagen
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = function(e) {
thumbnail.src = e.target.result;
thumbnail.style.display = 'block';
};
reader.readAsDataURL(file);
} else if (file.type.startsWith('audio/')) {
// Mostrar reproductor para audio
const reader = new FileReader();
reader.onload = function(e) {
thumbnail.outerHTML = `<audio controls style="width: 100%; margin-bottom: 10px;" id="mediaThumbnail">
<source src="${e.target.result}" type="${file.type}">
</audio>`;
};
reader.readAsDataURL(file);
} else {
thumbnail.style.display = 'none';
}
preview.classList.add('show');
}
// Formatear tamaño de archivo
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}
// Cancelar subida de multimedia
function cancelMediaUpload() {
selectedFile = null;
document.getElementById('fileInput').value = '';
// Restaurar thumbnail si se cambió por audio
const thumbnailElement = document.getElementById('mediaThumbnail');
if (thumbnailElement && thumbnailElement.tagName === 'AUDIO') {
thumbnailElement.outerHTML = '<img id="mediaThumbnail" class="media-thumbnail" style="display: none;" />';
}
document.getElementById('mediaPreview').classList.remove('show');
document.getElementById('mediaCaption').value = '';
}
// Enviar mensaje multimedia
async function sendMediaMessage() {
if (!selectedFile) return;
try {
showTyping();
// Subir archivo
const formData = new FormData();
formData.append('file', selectedFile);
formData.append('uploaded_by', userId);
const uploadResponse = await fetch('api/upload_media.php', {
method: 'POST',
body: formData
});
const uploadData = await uploadResponse.json();
if (!uploadData.success) {
throw new Error(uploadData.error || 'Error subiendo archivo');
}
// Enviar mensaje con el archivo
const caption = document.getElementById('mediaCaption').value.trim();
const sendResponse = await whatsappManager.apiCall('send_media_message.php', {
body: {
recipient: currentUser.phone_number,
media_url: uploadData.public_url,
media_type: uploadData.media_type,
caption: caption || null,
filename: uploadData.filename
}
});
hideTyping();
if (sendResponse && sendResponse.success) {
cancelMediaUpload();
showAlert('Multimedia enviado correctamente', 'success');
await loadUserData(); // Recargar mensajes
} else {
throw new Error(sendResponse.error || 'Error enviando multimedia');
}
} catch (error) {
hideTyping();
console.error('Error enviando multimedia:', error);
showAlert('Error enviando multimedia: ' + error.message, 'danger');
}
}
// Modificar renderMessage para soportar multimedia
const originalAddMessageToView = addMessageToView;
addMessageToView = function(content, type, timestamp = null) {
if (typeof content === 'object' && content.media_url) {
// Es un mensaje multimedia
return renderMediaMessage(content, type, timestamp);
}
return originalAddMessageToView(content, type, timestamp);
};
// Renderizar mensaje multimedia
function renderMediaMessage(message, type, timestamp = null) {
const chatMessages = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.className = `message-bubble message-${type}`;
let mediaHtml = '';
const mediaUrl = message.media_url || message.content;
switch (message.media_type) {
case 'image':
mediaHtml = `<img src="${mediaUrl}" alt="Imagen" style="max-width: 100%; border-radius: 8px;">`;
break;
case 'video':
mediaHtml = `<video controls style="max-width: 100%; border-radius: 8px;"><source src="${mediaUrl}"></video>`;
break;
case 'audio':
mediaHtml = `<audio controls style="width: 100%;"><source src="${mediaUrl}"></audio>`;
break;
case 'document':
const filename = message.filename || 'Documento';
mediaHtml = `<a href="${mediaUrl}" target="_blank" class="message-document">
<i class="fas fa-file-alt"></i>
<span>${filename}</span>
</a>`;
break;
}
let html = `<div class="message-media">${mediaHtml}</div>`;
if (message.caption) {
html += `<div style="margin-top: 5px;">${escapeHtml(message.caption)}</div>`;
}
if (timestamp) {
html += `<div class="message-time">${formatTimestamp(timestamp)}</div>`;
}
messageDiv.innerHTML = html;
chatMessages.appendChild(messageDiv);
scrollToBottom();
}
// Escape HTML
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Formatear timestamp
function formatTimestamp(timestamp) {
if (!timestamp) return '';
const date = new Date(timestamp);
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${hours}:${minutes}`;
}
// Inicializar cuando la página se carga
document.addEventListener('DOMContentLoaded', function() {
loadUserData();
// Event listeners para multimedia
document.getElementById('attachBtn').addEventListener('click', function() {
document.getElementById('fileInput').click();
});
document.getElementById('fileInput').addEventListener('change', handleFileSelect);
// Event listener para micrófono
document.getElementById('micBtn').addEventListener('click', function() {
if (mediaRecorder && mediaRecorder.state === 'recording') {
stopRecording();
} else {
startRecording();
}
});
// Auto-refresh cada 30 segundos para nuevos mensajes
setInterval(refreshChat, 30000);
});
+332 -2
View File
@@ -223,7 +223,7 @@
gap: 10px;
}
.chat-input input {
.chat-input input[type="text"] {
flex: 1;
padding: 10px 15px;
border: 1px solid #ddd;
@@ -252,6 +252,92 @@
background: var(--whatsapp-green-dark);
}
#attach-btn {
background: #075E54;
}
#attach-btn:hover {
background: #128C7E;
}
/* Estilos para mensajes multimedia */
.message-media {
max-width: 300px;
border-radius: 8px;
overflow: hidden;
margin-bottom: 5px;
}
.message-media img,
.message-media video {
width: 100%;
display: block;
cursor: pointer;
}
.message-media audio {
width: 100%;
}
.message-document {
background: rgba(0,0,0,0.05);
padding: 10px;
border-radius: 8px;
display: flex;
align-items: center;
gap: 10px;
cursor: pointer;
}
.message-document:hover {
background: rgba(0,0,0,0.1);
}
.message-document i {
font-size: 24px;
color: var(--whatsapp-green);
}
.document-info {
flex: 1;
}
.document-name {
font-weight: 500;
font-size: 14px;
}
.document-size {
font-size: 12px;
color: #666;
}
#media-preview {
animation: slideUp 0.3s ease;
}
@keyframes slideUp {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.upload-progress {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 3px;
background: var(--whatsapp-green);
transform-origin: left;
transition: transform 0.3s;
}
.no-conversation {
display: flex;
flex-direction: column;
@@ -369,7 +455,28 @@
<!-- Los mensajes se cargan aquí -->
</div>
<!-- Preview de archivo multimedia -->
<div id="media-preview" style="display: none; padding: 10px; background: #f0f0f0; border-top: 1px solid #ddd;">
<div style="display: flex; align-items: center; justify-content: space-between;">
<div style="display: flex; align-items: center; gap: 10px;">
<img id="preview-thumbnail" style="max-width: 60px; max-height: 60px; border-radius: 5px; display: none;">
<div>
<div id="preview-filename" style="font-weight: bold; font-size: 14px;"></div>
<div id="preview-filesize" style="font-size: 12px; color: #666;"></div>
</div>
</div>
<button class="btn btn-sm btn-danger" onclick="cancelMediaUpload()">
<i class="fas fa-times"></i>
</button>
</div>
<input type="text" id="media-caption" class="form-control mt-2" placeholder="Agregar un comentario (opcional)" maxlength="1024">
</div>
<div class="chat-input">
<input type="file" id="file-input" accept="image/*,video/*,audio/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx" style="display: none;">
<button class="btn" id="attach-btn" title="Adjuntar archivo">
<i class="fas fa-paperclip"></i>
</button>
<input type="text" placeholder="Escribe un mensaje..." id="message-input" maxlength="4096">
<button class="btn" id="send-btn">
<i class="fas fa-paper-plane"></i>
@@ -413,6 +520,15 @@
this.sendMessage();
}
});
// Adjuntar archivos
document.getElementById('attach-btn').addEventListener('click', () => {
document.getElementById('file-input').click();
});
document.getElementById('file-input').addEventListener('change', (e) => {
this.handleFileSelect(e);
});
}
setupAutoRefresh() {
@@ -623,10 +739,15 @@
const statusIcon = this.getStatusIcon(msg.status);
// Renderizar contenido (texto o multimedia)
const content = msg.media_url
? this.renderMediaMessage(msg)
: (msg.content || msg.message_text || '[Mensaje vacío]');
return `
<div class="message ${msg.direction}">
<div class="message-bubble">
${msg.content || msg.message_text || '[Mensaje vacío]'}
${content}
<div class="message-time">
${time}
${msg.direction === 'outgoing' ? `<span class="message-status">${statusIcon}</span>` : ''}
@@ -705,12 +826,221 @@
item.style.display = matches ? 'flex' : 'none';
});
}
// ========== FUNCIONES MULTIMEDIA ==========
handleFileSelect(event) {
const file = event.target.files[0];
if (!file) return;
// Validar tamaño
const maxSize = this.getMaxFileSize(file.type);
if (file.size > maxSize) {
alert(`El archivo es demasiado grande. Máximo: ${(maxSize / 1024 / 1024).toFixed(0)}MB`);
return;
}
// Mostrar preview
this.showMediaPreview(file);
}
getMaxFileSize(fileType) {
if (fileType.startsWith('image/')) return 5 * 1024 * 1024; // 5MB
if (fileType.startsWith('application/')) return 100 * 1024 * 1024; // 100MB
return 16 * 1024 * 1024; // 16MB para video/audio
}
showMediaPreview(file) {
const preview = document.getElementById('media-preview');
const thumbnail = document.getElementById('preview-thumbnail');
const filename = document.getElementById('preview-filename');
const filesize = document.getElementById('preview-filesize');
// Establecer información del archivo
filename.textContent = file.name;
filesize.textContent = this.formatFileSize(file.size);
// Mostrar thumbnail para imágenes
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = (e) => {
thumbnail.src = e.target.result;
thumbnail.style.display = 'block';
};
reader.readAsDataURL(file);
} else {
thumbnail.style.display = 'none';
}
// Guardar archivo temporalmente
this.selectedFile = file;
// Mostrar preview
preview.style.display = 'block';
// Cambiar comportamiento del botón enviar
const sendBtn = document.getElementById('send-btn');
const originalHandler = sendBtn.onclick;
sendBtn.onclick = () => this.sendMediaMessage();
}
formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}
async sendMediaMessage() {
if (!this.selectedFile || !this.currentUserId) return;
const caption = document.getElementById('media-caption').value.trim();
const sendBtn = document.getElementById('send-btn');
const attachBtn = document.getElementById('attach-btn');
// Deshabilitar botones
sendBtn.disabled = true;
attachBtn.disabled = true;
sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
try {
// 1. Subir archivo
const formData = new FormData();
formData.append('file', this.selectedFile);
const uploadResponse = await fetch('api/upload_media.php', {
method: 'POST',
body: formData
});
const uploadResult = await uploadResponse.json();
if (!uploadResult.success) {
throw new Error(uploadResult.error || 'Error subiendo archivo');
}
// 2. Enviar mensaje con el archivo
const user = this.conversations.find(c => c.user_id === this.currentUserId);
const phone = user ? user.phone_number : null;
if (!phone) {
throw new Error('No se encontró el número de teléfono');
}
const sendResponse = await fetch('api/send_media_message.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
recipient: phone,
media_url: uploadResult.data.url,
media_type: uploadResult.data.type,
caption: caption || null,
filename: this.selectedFile.name
})
});
const sendResult = await sendResponse.json();
if (!sendResult.success) {
throw new Error(sendResult.error || 'Error enviando mensaje');
}
// Éxito
this.cancelMediaUpload();
await this.loadMessages(this.currentUserId, false);
this.loadConversations();
} catch (error) {
console.error('Error sending media:', error);
alert('Error al enviar archivo: ' + error.message);
} finally {
sendBtn.disabled = false;
attachBtn.disabled = false;
sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i>';
}
}
cancelMediaUpload() {
document.getElementById('media-preview').style.display = 'none';
document.getElementById('media-caption').value = '';
document.getElementById('file-input').value = '';
this.selectedFile = null;
// Restaurar botón enviar
const sendBtn = document.getElementById('send-btn');
sendBtn.onclick = null;
}
renderMediaMessage(message) {
if (!message.media_url) return '';
const mediaType = message.message_type;
const mediaUrl = message.media_url;
const caption = message.content;
switch (mediaType) {
case 'image':
return `
<div class="message-media">
<img src="${mediaUrl}" alt="Imagen" onclick="window.open('${mediaUrl}', '_blank')">
</div>
${caption ? `<div>${caption}</div>` : ''}
`;
case 'video':
return `
<div class="message-media">
<video controls>
<source src="${mediaUrl}" type="video/mp4">
Tu navegador no soporta video.
</video>
</div>
${caption ? `<div>${caption}</div>` : ''}
`;
case 'audio':
return `
<div class="message-media">
<audio controls>
<source src="${mediaUrl}" type="audio/mpeg">
Tu navegador no soporta audio.
</audio>
</div>
`;
case 'document':
return `
<div class="message-document" onclick="window.open('${mediaUrl}', '_blank')">
<i class="fas fa-file-pdf"></i>
<div class="document-info">
<div class="document-name">${caption || 'Documento'}</div>
<div class="document-size">Haz clic para descargar</div>
</div>
<i class="fas fa-download"></i>
</div>
`;
default:
return caption || '';
}
}
}
// Función global para cancelar
function cancelMediaUpload() {
if (window.chatApp) {
window.chatApp.cancelMediaUpload();
}
}
// Inicializar cuando la página cargue
let chat;
document.addEventListener('DOMContentLoaded', () => {
chat = new WhatsAppChat();
window.chatApp = chat; // Exponer globalmente para funciones auxiliares
});
</script>
</body>
+16
View File
@@ -0,0 +1,16 @@
-- Tabla para almacenar archivos multimedia subidos
CREATE TABLE IF NOT EXISTS media_files (
id INT AUTO_INCREMENT PRIMARY KEY,
filename VARCHAR(255) NOT NULL,
unique_name VARCHAR(255) NOT NULL UNIQUE,
file_type VARCHAR(100) NOT NULL,
file_size INT NOT NULL,
media_type ENUM('image', 'video', 'audio', 'document') NOT NULL,
file_path TEXT NOT NULL,
public_url TEXT NOT NULL,
uploaded_by INT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_media_type (media_type),
INDEX idx_uploaded_by (uploaded_by),
INDEX idx_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+62
View File
@@ -0,0 +1,62 @@
<?php
require_once 'config/config.php';
require_once 'classes/Database.php';
try {
$db = Database::getInstance();
$conn = $db->getConnection();
// Leer el archivo SQL
$sqlFile = __DIR__ . '/create_media_table.sql';
if (!file_exists($sqlFile)) {
throw new Exception("Archivo SQL no encontrado: $sqlFile");
}
$sql = file_get_contents($sqlFile);
if (empty($sql)) {
throw new Exception("El archivo SQL está vacío");
}
// Ejecutar el SQL
$result = $conn->query($sql);
if ($result === false) {
throw new Exception("Error al ejecutar SQL: " . $conn->error);
}
echo "✅ Tabla 'media_files' creada exitosamente\n\n";
// Verificar que la tabla existe
$check = $conn->query("SHOW TABLES LIKE 'media_files'");
if ($check && $check->num_rows > 0) {
echo "✅ Tabla verificada en la base de datos\n\n";
// Mostrar estructura de la tabla
$structure = $conn->query("DESCRIBE media_files");
if ($structure) {
echo "📋 Estructura de la tabla:\n";
echo str_repeat("-", 80) . "\n";
printf("%-20s %-20s %-10s %-10s %-20s\n", "Campo", "Tipo", "Null", "Key", "Extra");
echo str_repeat("-", 80) . "\n";
while ($row = $structure->fetch_assoc()) {
printf("%-20s %-20s %-10s %-10s %-20s\n",
$row['Field'],
$row['Type'],
$row['Null'],
$row['Key'],
$row['Extra']
);
}
echo str_repeat("-", 80) . "\n";
}
} else {
echo "⚠️ La tabla no se pudo verificar\n";
}
} catch (Exception $e) {
echo "❌ Error: " . $e->getMessage() . "\n";
exit(1);
}
+131
View File
@@ -181,6 +181,137 @@ class WhatsAppService
return $this->makeRequest('POST', $url, $data);
}
/**
* Enviar imagen
*/
public function sendImageMessage($to, $imageUrl, $caption = null)
{
$image = ['link' => $imageUrl];
if ($caption) {
$image['caption'] = $caption;
}
$data = [
'messaging_product' => 'whatsapp',
'to' => $this->formatPhoneNumber($to),
'type' => 'image',
'image' => $image
];
return $this->sendMessage($data);
}
/**
* Enviar video
*/
public function sendVideoMessage($to, $videoUrl, $caption = null)
{
$video = ['link' => $videoUrl];
if ($caption) {
$video['caption'] = $caption;
}
$data = [
'messaging_product' => 'whatsapp',
'to' => $this->formatPhoneNumber($to),
'type' => 'video',
'video' => $video
];
return $this->sendMessage($data);
}
/**
* Enviar audio
*/
public function sendAudioMessage($to, $audioUrl)
{
$data = [
'messaging_product' => 'whatsapp',
'to' => $this->formatPhoneNumber($to),
'type' => 'audio',
'audio' => [
'link' => $audioUrl
]
];
return $this->sendMessage($data);
}
/**
* Enviar documento
*/
public function sendDocumentMessage($to, $documentUrl, $filename = null, $caption = null)
{
$document = ['link' => $documentUrl];
if ($filename) {
$document['filename'] = $filename;
}
if ($caption) {
$document['caption'] = $caption;
}
$data = [
'messaging_product' => 'whatsapp',
'to' => $this->formatPhoneNumber($to),
'type' => 'document',
'document' => $document
];
return $this->sendMessage($data);
}
/**
* Subir archivo multimedia a WhatsApp
*/
public function uploadMedia($filePath, $mimeType)
{
if (!file_exists($filePath)) {
throw new Exception("Archivo no encontrado: $filePath");
}
$url = $this->apiUrl . $this->phoneNumberId . '/media';
$ch = curl_init();
$postFields = [
'messaging_product' => 'whatsapp',
'file' => new CURLFile($filePath, $mimeType),
'type' => $mimeType
];
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $this->token
],
CURLOPT_TIMEOUT => 120
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200 && $httpCode !== 201) {
throw new Exception("Error subiendo archivo: " . $response);
}
$result = json_decode($response, true);
if (!isset($result['id'])) {
throw new Exception("No se obtuvo ID del archivo subido");
}
return $result['id']; // Retorna el media_id
}
/**
* Enviar mensaje principal
*/
+30
View File
@@ -0,0 +1,30 @@
<?php
require_once 'config/config.php';
require_once 'classes/Database.php';
$db = Database::getInstance();
$result = $db->getConnection()->query('DESCRIBE media_files');
echo "📋 Tabla media_files creada exitosamente\n\n";
echo "Estructura de la tabla:\n";
echo str_repeat('-', 90) . "\n";
printf("%-20s %-30s %-10s %-10s %-15s\n", 'Campo', 'Tipo', 'Null', 'Key', 'Extra');
echo str_repeat('-', 90) . "\n";
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
printf("%-20s %-30s %-10s %-10s %-15s\n",
$row['Field'],
$row['Type'],
$row['Null'],
$row['Key'],
$row['Extra']
);
}
echo str_repeat('-', 90) . "\n";
echo "\n✅ Sistema multimedia listo para usar\n";
echo "\n📝 Puedes ahora:\n";
echo " 1. Abrir conversations.php\n";
echo " 2. Seleccionar una conversación\n";
echo " 3. Hacer clic en el botón 📎 para adjuntar archivos\n";
echo " 4. Enviar imágenes, videos, audios o documentos\n\n";