full
This commit is contained in:
+555
-2
@@ -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);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user