El archivo grabado por el browser es WebM (no soportado por WhatsApp). conversations.php usa ffmpeg para convertirlo; chat_upload_media.php solo cambiaba el string del MIME pero enviaba el archivo WebM real, causando que el audio no llegara al destinatario. Ahora se convierte con los mismos parámetros que upload_media.php (libopus 32k mono 48kHz). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
95 lines
3.6 KiB
PHP
95 lines
3.6 KiB
PHP
<?php
|
|
/**
|
|
* POST multipart — sube un archivo y lo envía por WhatsApp desde el número turnero.
|
|
* Campos: user_id, file (multipart), caption (opcional)
|
|
*/
|
|
require_once __DIR__ . '/../../../config/config.php';
|
|
require_once __DIR__ . '/../../../services/WhatsAppService.php';
|
|
requireAuthentication();
|
|
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success'=>false,'error'=>'Método no permitido']); exit; }
|
|
|
|
function tmErr($msg, $code=400) { http_response_code($code); echo json_encode(['success'=>false,'error'=>$msg]); exit; }
|
|
|
|
$userId = intval($_POST['user_id'] ?? 0);
|
|
if (!$userId) tmErr('user_id requerido');
|
|
if (empty($_FILES['file'])) tmErr('Archivo requerido');
|
|
|
|
$file = $_FILES['file'];
|
|
if ($file['error'] !== UPLOAD_ERR_OK) tmErr('Error al subir archivo: código ' . $file['error']);
|
|
|
|
$maxBytes = 64 * 1024 * 1024; // 64 MB
|
|
if ($file['size'] > $maxBytes) tmErr('El archivo supera el límite de 64 MB');
|
|
|
|
$detectedMime = mime_content_type($file['tmp_name']) ?: $file['type'];
|
|
$browserMime = $file['type'] ?: '';
|
|
$caption = trim($_POST['caption'] ?? '');
|
|
$isVoice = !empty($_POST['is_voice']);
|
|
|
|
// mime_content_type() returns video/webm for browser-recorded audio (same WebM container).
|
|
// WhatsApp only accepts OGG Opus, not WebM. Convert with ffmpeg when available.
|
|
$isWebm = str_contains($detectedMime, 'webm') || str_contains($browserMime, 'webm');
|
|
$mime = $isWebm ? 'audio/ogg' : $detectedMime;
|
|
|
|
$uploadFilePath = $file['tmp_name'];
|
|
if ($isWebm && function_exists('shell_exec')) {
|
|
$ffmpeg = trim((string)@shell_exec('which ffmpeg 2>/dev/null'));
|
|
if ($ffmpeg) {
|
|
$convertedPath = sys_get_temp_dir() . '/wa_audio_' . uniqid() . '.ogg';
|
|
$cmd = escapeshellcmd($ffmpeg)
|
|
. ' -y -i ' . escapeshellarg($file['tmp_name'])
|
|
. ' -map 0:a:0 -c:a libopus -b:a 32k -vbr on -ar 48000 -ac 1 -f ogg '
|
|
. escapeshellarg($convertedPath) . ' 2>/dev/null';
|
|
@shell_exec($cmd);
|
|
if (file_exists($convertedPath) && filesize($convertedPath) > 0) {
|
|
$uploadFilePath = $convertedPath;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Determinar tipo de media
|
|
if (str_starts_with($mime, 'image/')) $mediaType = 'image';
|
|
elseif (str_starts_with($mime, 'video/')) $mediaType = 'video';
|
|
elseif (str_starts_with($mime, 'audio/')) $mediaType = 'audio';
|
|
else $mediaType = 'document';
|
|
|
|
try {
|
|
$db = Database::getInstance();
|
|
$user = $db->fetch("SELECT phone_number FROM users WHERE id = ?", [$userId]);
|
|
if (!$user) tmErr('Usuario no encontrado', 404);
|
|
|
|
$phoneId = getConfigFromDB('whatsapp_phone_number_id_turnero', '');
|
|
if (!$phoneId) tmErr('Número turnero no configurado', 503);
|
|
|
|
$wa = new WhatsAppService('turnero');
|
|
|
|
// Subir a WhatsApp Media API
|
|
$uploadResult = $wa->uploadMedia($uploadFilePath, $mime);
|
|
if (!$uploadResult || !isset($uploadResult['id'])) {
|
|
tmErr('No se pudo subir el archivo a WhatsApp', 502);
|
|
}
|
|
$mediaId = $uploadResult['id'];
|
|
|
|
$opId = $_SESSION['admin_id'] ?? $_SESSION['user_id'] ?? null;
|
|
$extra = ['canal' => 'turnero'];
|
|
if ($opId) $extra['operator_id'] = $opId;
|
|
|
|
$resp = $wa->sendMediaById(
|
|
$user['phone_number'],
|
|
$mediaId,
|
|
$mediaType,
|
|
$caption ?: null,
|
|
$file['name'],
|
|
false,
|
|
$isVoice,
|
|
$extra
|
|
);
|
|
|
|
echo json_encode(['success' => true, 'media_type' => $mediaType, 'response' => $resp]);
|
|
|
|
} catch (Exception $e) {
|
|
error_log('chat_upload_media: ' . $e->getMessage());
|
|
tmErr($e->getMessage(), 500);
|
|
}
|