fix: soporte universal de camara y escaneo QR con jsQR y fallbacks de lente

This commit is contained in:
unknown
2026-10-04 17:24:48 -06:00
parent eec1b93270
commit 02bf67e0ff
7 changed files with 10342 additions and 61 deletions
+7
View File
@@ -12,6 +12,7 @@
"better-sqlite3": "^13.0.3",
"cors": "^2.8.6",
"express": "^5.2.1",
"jsqr": "^1.4.0",
"qrcode": "^1.5.4"
}
},
@@ -607,6 +608,12 @@
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
"license": "MIT"
},
"node_modules/jsqr": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/jsqr/-/jsqr-1.4.0.tgz",
"integrity": "sha512-dxLob7q65Xg2DvstYkRpkYtmKm2sPJ9oFhrhmudT1dZvNFFTlroai3AWSpLey/w5vMcLBXRgOJsbXpdN9HzU/A==",
"license": "Apache-2.0"
},
"node_modules/locate-path": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
+1
View File
@@ -24,6 +24,7 @@
"better-sqlite3": "^13.0.3",
"cors": "^2.8.6",
"express": "^5.2.1",
"jsqr": "^1.4.0",
"qrcode": "^1.5.4"
}
}
+18 -4
View File
@@ -260,11 +260,24 @@
<!-- PASO 1: ESCANEAR CÁMARA O ELEGIR COMPAÑERO DE PRUEBA -->
<div id="transferStepScan">
<div style="position: relative; border-radius: 12px; overflow: hidden; background: #000; height: 160px; margin-bottom: 12px;">
<video id="transferVideo" style="width: 100%; height: 100%; object-fit: cover;" autoplay playsinline muted></video>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
<span style="font-size: 0.75rem; color: #64748b; font-weight: 700;" id="transferCameraStatus">Iniciando cámara...</span>
<div style="display: flex; gap: 6px;">
<button id="btnFlipTransferCamera" type="button" onclick="flipTransferCamera()" style="display:none; padding: 3px 8px; background: #334155; color: white; border: none; border-radius: 6px; font-size: 0.72rem; font-weight: 700; cursor: pointer;">🔄 Girar</button>
<button id="btnRetryTransferCamera" type="button" onclick="startTransferCamera(true)" style="display:none; padding: 3px 8px; background: #0284c7; color: white; border: none; border-radius: 6px; font-size: 0.72rem; font-weight: 700; cursor: pointer;">📷 Activar</button>
</div>
</div>
<div style="position: relative; border-radius: 12px; overflow: hidden; background: #000; min-height: 160px; margin-bottom: 12px; display: flex; align-items: center; justify-content: center;">
<video id="transferVideo" style="width: 100%; height: 160px; object-fit: cover;" autoplay playsinline muted></video>
<div class="laser-scan-line"></div>
<div style="position: absolute; bottom: 8px; left: 0; right: 0; text-align: center; color: white; font-size: 0.72rem; text-shadow: 0 1px 3px black;">
Apunta al QR del carné o celular de tu amigo
<div id="transferCameraHelp" style="display: none; position: absolute; inset: 0; background: rgba(15, 23, 42, 0.9); padding: 14px; text-align: center; flex-direction: column; justify-content: center; align-items: center; gap: 8px; z-index: 10;">
<span style="font-size: 1.8rem;">📷</span>
<p id="transferCameraHelpText" style="font-size: 0.76rem; color: #f8fafc; line-height: 1.3;">Toca el botón para permitir la cámara</p>
<button type="button" onclick="startTransferCamera(true)" style="padding: 6px 14px; background: #0284c7; color: white; border: none; border-radius: 8px; font-weight: 800; font-size: 0.8rem; cursor: pointer;">
Permitir Cámara
</button>
</div>
</div>
@@ -326,6 +339,7 @@
</div>
<script src="/js/sounds.js"></script>
<script src="/js/jsQR.js"></script>
<script src="/js/app.js"></script>
</body>
</html>
+106 -31
View File
@@ -542,56 +542,131 @@ function setTransferAmount(val, btn) {
if (window.sounds) window.sounds.playCoin();
}
async function startTransferCamera() {
let transferFacingMode = 'environment';
let transferScanAnimationId = null;
let transferCanvas = null;
let transferCanvasCtx = null;
async function startTransferCamera(isUserAction = false) {
const video = document.getElementById('transferVideo');
const status = document.getElementById('transferCameraStatus');
const helpOverlay = document.getElementById('transferCameraHelp');
const retryBtn = document.getElementById('btnRetryTransferCamera');
const flipBtn = document.getElementById('btnFlipTransferCamera');
if (!video) return;
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
stopTransferCamera();
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
if (status) status.textContent = '⚠️ Cámara requiere HTTPS';
if (helpOverlay) {
helpOverlay.style.display = 'flex';
document.getElementById('transferCameraHelpText').textContent = '⚠️ Los navegadores bloquean la cámara si no es HTTPS. Usa el enlace seguro o toca directamente a tu amigo abajo.';
}
return;
}
try {
if (status) status.textContent = 'Conectando cámara...';
try {
transferVideoStream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment', width: { ideal: 480 } }
video: { facingMode: { ideal: transferFacingMode }, width: { ideal: 720 } },
audio: false
});
video.srcObject = transferVideoStream;
isTransferScanning = true;
scanQrFromCamera(video);
} catch (err) {
console.log('Cámara de transferencia no disponible:', err);
} catch (err1) {
// Fallback a cualquier lente disponible
transferVideoStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
}
video.setAttribute('playsinline', 'true');
video.setAttribute('autoplay', 'true');
video.muted = true;
video.srcObject = transferVideoStream;
await video.play();
if (status) status.textContent = '🟢 Escaneando QR...';
if (helpOverlay) helpOverlay.style.display = 'none';
if (retryBtn) retryBtn.style.display = 'none';
if (flipBtn) flipBtn.style.display = 'inline-block';
isTransferScanning = true;
startTransferQrDetection(video);
} catch (err) {
console.warn('Error iniciando cámara de transferencia:', err);
if (status) status.textContent = '⚪ Cámara inactiva';
if (helpOverlay) {
helpOverlay.style.display = 'flex';
document.getElementById('transferCameraHelpText').textContent = 'Toca Permitir Cámara o activa los permisos en la barra del navegador.';
}
if (retryBtn) retryBtn.style.display = 'inline-block';
}
}
function flipTransferCamera() {
transferFacingMode = transferFacingMode === 'environment' ? 'user' : 'environment';
startTransferCamera(true);
}
function stopTransferCamera() {
isTransferScanning = false;
if (transferScanAnimationId) {
cancelAnimationFrame(transferScanAnimationId);
transferScanAnimationId = null;
}
if (transferVideoStream) {
transferVideoStream.getTracks().forEach(t => t.stop());
transferVideoStream = null;
}
}
function scanQrFromCamera(video) {
if ('BarcodeDetector' in window) {
const detector = new window.BarcodeDetector({ formats: ['qr_code'] });
const interval = setInterval(async () => {
if (!isTransferScanning || selectedTransferTarget !== null) {
clearInterval(interval);
return;
}
try {
const barcodes = await detector.detect(video);
if (barcodes.length > 0) {
const rawValue = barcodes[0].rawValue;
const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(rawValue)}`);
if (res.ok) {
const found = await res.json();
if (found.id !== currentStudent.id) {
clearInterval(interval);
onTransferTargetIdentified(found);
}
}
}
} catch (e) {}
}, 400);
function startTransferQrDetection(video) {
if (!transferCanvas) {
transferCanvas = document.createElement('canvas');
transferCanvasCtx = transferCanvas.getContext('2d', { willReadFrequently: true });
}
function scanFrame() {
if (isTransferScanning && selectedTransferTarget === null && video.readyState === video.HAVE_ENOUGH_DATA) {
transferCanvas.width = video.videoWidth;
transferCanvas.height = video.videoHeight;
transferCanvasCtx.drawImage(video, 0, 0, transferCanvas.width, transferCanvas.height);
const imageData = transferCanvasCtx.getImageData(0, 0, transferCanvas.width, transferCanvas.height);
if (window.jsQR) {
const code = window.jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: 'dontInvert'
});
if (code && code.data) {
fetchStudentByScannedQr(code.data);
return;
}
}
}
if (isTransferScanning && selectedTransferTarget === null) {
transferScanAnimationId = requestAnimationFrame(scanFrame);
}
}
transferScanAnimationId = requestAnimationFrame(scanFrame);
}
async function fetchStudentByScannedQr(rawValue) {
try {
const res = await fetch(`/api/estudiantes/qr/${encodeURIComponent(rawValue)}`);
if (res.ok) {
const found = await res.json();
if (found.id !== currentStudent.id) {
stopTransferCamera();
onTransferTargetIdentified(found);
} else {
alert('⚠️ Este es tu propio código QR. Escanea el carné o QR de tu compañero.');
}
}
} catch (e) {}
}
async function executeP2PTransfer() {
+10102
View File
File diff suppressed because it is too large Load Diff
+94 -24
View File
@@ -136,41 +136,111 @@ function clearPosCart() {
// ESCÁNER Y LECTURA DE QR
// ==========================================
async function initCamera() {
let posFacingMode = 'environment';
let posQrScanningInterval = null;
let posCanvas = null;
let posCanvasCtx = null;
let lastScannedToken = null;
let lastScannedTime = 0;
async function initCamera(isUserAction = false) {
const video = document.getElementById('scannerVideo');
const status = document.getElementById('cameraStatus');
const overlay = document.getElementById('cameraHelpOverlay');
const retryBtn = document.getElementById('btnRetryPosCamera');
const flipBtn = document.getElementById('btnFlipPosCamera');
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
if (videoStream) {
videoStream.getTracks().forEach(t => t.stop());
videoStream = null;
}
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
status.textContent = '⚠️ Requiere HTTPS';
if (overlay) {
overlay.style.display = 'flex';
document.getElementById('cameraHelpText').textContent = '⚠️ Para usar la cámara en dispositivos remotos se requiere conexión segura HTTPS. Puedes usar los botones de prueba abajo.';
}
return;
}
try {
status.textContent = 'Conectando lente...';
try {
videoStream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment', width: { ideal: 640 } }
video: { facingMode: { ideal: posFacingMode }, width: { ideal: 1280 } },
audio: false
});
video.srcObject = videoStream;
status.textContent = '🟢 Cámara conectada';
startQrDetection(video);
} catch (err) {
status.textContent = '⚪ Modo simulación QR activo';
} catch (err1) {
// Fallback a cualquier cámara disponible
videoStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
}
} else {
status.textContent = '⚪ Modo simulación QR activo';
video.setAttribute('playsinline', 'true');
video.setAttribute('autoplay', 'true');
video.muted = true;
video.srcObject = videoStream;
await video.play();
status.textContent = '🟢 Escáner activo';
if (overlay) overlay.style.display = 'none';
if (retryBtn) retryBtn.style.display = 'none';
if (flipBtn) flipBtn.style.display = 'inline-block';
startUniversalQrDetection(video);
} catch (err) {
console.warn('Error accediendo a cámara:', err);
status.textContent = '⚪ Cámara inactiva';
if (overlay) {
overlay.style.display = 'flex';
document.getElementById('cameraHelpText').textContent = 'Toca Permitir Cámara o habilita los permisos en la barra de direcciones.';
}
if (retryBtn) retryBtn.style.display = 'inline-block';
}
}
// Detección nativa por BarcodeDetector si el navegador lo soporta (Chrome/Edge Android)
function startQrDetection(video) {
if ('BarcodeDetector' in window) {
const detector = new window.BarcodeDetector({ formats: ['qr_code'] });
const interval = setInterval(async () => {
if (!isScanningActive) return;
try {
const barcodes = await detector.detect(video);
if (barcodes.length > 0) {
const rawValue = barcodes[0].rawValue;
onQrCodeDetected(rawValue);
}
} catch (e) {}
}, 400);
function flipPosCamera() {
posFacingMode = posFacingMode === 'environment' ? 'user' : 'environment';
initCamera(true);
}
function startUniversalQrDetection(video) {
if (!posCanvas) {
posCanvas = document.createElement('canvas');
posCanvasCtx = posCanvas.getContext('2d', { willReadFrequently: true });
}
if (posQrScanningInterval) {
cancelAnimationFrame(posQrScanningInterval);
}
function scanFrame() {
if (isScanningActive && video.readyState === video.HAVE_ENOUGH_DATA) {
posCanvas.width = video.videoWidth;
posCanvas.height = video.videoHeight;
posCanvasCtx.drawImage(video, 0, 0, posCanvas.width, posCanvas.height);
const imageData = posCanvasCtx.getImageData(0, 0, posCanvas.width, posCanvas.height);
if (window.jsQR) {
const code = window.jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: 'dontInvert'
});
if (code && code.data) {
const now = Date.now();
// Evitar lecturas duplicadas en menos de 2 segundos
if (code.data !== lastScannedToken || (now - lastScannedTime) > 2000) {
lastScannedToken = code.data;
lastScannedTime = now;
onQrCodeDetected(code.data);
}
}
}
}
posQrScanningInterval = requestAnimationFrame(scanFrame);
}
posQrScanningInterval = requestAnimationFrame(scanFrame);
}
function simulateScan(qrToken) {
+14 -2
View File
@@ -101,12 +101,23 @@
<div class="scanner-feed-card">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
<span style="font-size: 0.85rem; font-weight: 800; color: #38bdf8;">📷 Escáner QR de Alumnos</span>
<span style="font-size: 0.72rem; color: #94a3b8;" id="cameraStatus">Cámara lista</span>
<div style="display: flex; gap: 6px; align-items: center;">
<button id="btnFlipPosCamera" onclick="flipPosCamera()" style="display:none; padding: 3px 8px; background: #334155; color: white; border: none; border-radius: 6px; font-size: 0.72rem; font-weight: 700; cursor: pointer;">🔄 Girar</button>
<button id="btnRetryPosCamera" onclick="initCamera(true)" style="display:none; padding: 3px 8px; background: #0284c7; color: white; border: none; border-radius: 6px; font-size: 0.72rem; font-weight: 700; cursor: pointer;">📷 Activar</button>
<span style="font-size: 0.72rem; color: #94a3b8;" id="cameraStatus">Iniciando cámara...</span>
</div>
</div>
<div style="position: relative; border-radius: 10px; overflow: hidden; background: #000;">
<div style="position: relative; border-radius: 10px; overflow: hidden; background: #000; min-height: 180px; display: flex; align-items: center; justify-content: center;">
<video id="scannerVideo" class="camera-preview" autoplay playsinline muted></video>
<div class="laser-scan-line"></div>
<div id="cameraHelpOverlay" style="display: none; position: absolute; inset: 0; background: rgba(15, 23, 42, 0.9); padding: 14px; text-align: center; flex-direction: column; justify-content: center; align-items: center; gap: 8px; z-index: 10;">
<span style="font-size: 1.8rem;">📷</span>
<p id="cameraHelpText" style="font-size: 0.78rem; color: #f8fafc; line-height: 1.3;">Haz clic en Activar Cámara para escanear</p>
<button onclick="initCamera(true)" style="padding: 6px 14px; background: #0284c7; color: white; border: none; border-radius: 8px; font-weight: 800; font-size: 0.8rem; cursor: pointer;">
Permitir Cámara
</button>
</div>
</div>
<!-- BOTONES DE PRUEBA RÁPIDA DE QR (SIMULACIÓN DE ESCANEO DE CARNÉ O CELULAR) -->
@@ -164,6 +175,7 @@
</div>
<script src="/js/sounds.js"></script>
<script src="/js/jsQR.js"></script>
<script src="/js/pos.js"></script>
</body>
</html>