TKK_E32230273/registrasi_foto_backup.php

893 lines
37 KiB
PHP

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="theme-color" content="#0f172a">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="mobile-web-app-capable" content="yes">
<title>Verifikasi Wajah Identia</title>
<link rel="manifest" href="manifest_foto.json">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@7.4.47/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
:root {
--accent: #6366f1;
--accent2: #818cf8;
--green: #22c55e;
--green-glow: rgba(34,197,94,0.35);
--red: #ef4444;
--amber: #f59e0b;
--dark: #0f172a;
--darker: #070b14;
--card: rgba(15,23,42,0.85);
}
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body {
height: 100%; width: 100%;
background: var(--darker);
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
overflow: hidden;
display: flex; align-items: center; justify-content: center;
-webkit-font-smoothing: antialiased;
}
/* ═══ PHONE FRAME ═══ */
.phone {
width: 100%; max-width: 430px;
height: 100vh; max-height: 100vh;
background: var(--darker);
display: flex; flex-direction: column;
position: relative; overflow: hidden;
}
@media (min-width: 500px) {
body { background: #030712; }
.phone {
height: 93vh; max-height: 850px;
border-radius: 36px;
border: 3px solid rgba(99,102,241,0.15);
box-shadow:
0 0 0 1px rgba(99,102,241,0.08),
0 25px 80px rgba(0,0,0,0.7),
inset 0 1px 0 rgba(255,255,255,0.03);
}
}
/* ═══ HEADER ═══ */
.header {
display: flex; justify-content: space-between; align-items: center;
padding: 16px 20px;
background: linear-gradient(180deg, rgba(15,23,42,0.98), rgba(15,23,42,0.9));
backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
z-index: 30; position: absolute; top: 0; left: 0; right: 0;
border-bottom: 1px solid rgba(99,102,241,0.08);
}
.header-left {
display: flex; align-items: center; gap: 10px;
}
.header-logo {
width: 36px; height: 36px; border-radius: 10px;
background: linear-gradient(135deg, var(--accent), #7c3aed);
display: flex; align-items: center; justify-content: center;
box-shadow: 0 2px 12px rgba(99,102,241,0.3);
}
.header-logo i { color: #fff; font-size: 18px; }
.header-text h1 { font-size: 14px; font-weight: 800; color: #fff; letter-spacing: 0.2px; line-height: 1.2; }
.header-text span { font-size: 10px; font-weight: 600; color: rgba(255,255,255,0.35); text-transform: uppercase; letter-spacing: 1.2px; }
.header-badge {
font-size: 10px; font-weight: 700;
color: var(--accent2); background: rgba(99,102,241,0.1);
padding: 5px 12px; border-radius: 8px;
border: 1px solid rgba(99,102,241,0.15);
max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
/* ═══ PAGES ═══ */
.page { flex: 1; display: flex; flex-direction: column; }
.page-hidden { display: none !important; }
/* ═══ VALIDATING ═══ */
.page-validating {
align-items: center; justify-content: center; gap: 20px; color: #fff;
}
.val-ring {
width: 64px; height: 64px; border-radius: 50%;
border: 3px solid rgba(99,102,241,0.12);
border-top-color: var(--accent);
animation: spin 0.8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.page-validating p { font-size: 13px; color: rgba(255,255,255,0.4); font-weight: 500; }
/* ═══ ERROR ═══ */
.page-error {
align-items: center; justify-content: center;
padding: 40px 30px; text-align: center; gap: 8px; color: #fff;
}
.err-icon {
width: 88px; height: 88px; border-radius: 24px;
display: flex; align-items: center; justify-content: center;
margin-bottom: 12px;
}
.err-icon.expired {
background: linear-gradient(135deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04));
border: 2px solid rgba(245,158,11,0.15);
}
.err-icon.expired i { font-size: 42px; color: var(--amber); }
.err-icon.invalid {
background: linear-gradient(135deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04));
border: 2px solid rgba(239,68,68,0.15);
}
.err-icon.invalid i { font-size: 42px; color: var(--red); }
.page-error h2 { font-size: 22px; font-weight: 800; }
.page-error p { font-size: 13px; color: rgba(255,255,255,0.4); line-height: 1.7; max-width: 300px; }
/* ═══ CAMERA ═══ */
.cam-area {
flex: 1; position: relative; overflow: hidden; background: #1e2223;
}
.cam-area video {
width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1);
}
.cam-area canvas.overlay-cv {
position: absolute; top: 0; left: 0;
width: 100%; height: 100%; pointer-events: none;
}
/* Oval */
.face-oval {
position: absolute; top: 0; left: 0; width: 100%; height: 100%;
pointer-events: none; display: flex; align-items: center; justify-content: center;
}
.face-oval svg { width: 68%; max-width: 250px; height: auto; transition: 0.5s ease; }
.face-oval.ok #ovalRing {
stroke: var(--green); stroke-width: 3.5; stroke-dasharray: none;
filter: drop-shadow(0 0 18px var(--green-glow));
}
/* Corners */
.corners {
position: absolute; top: 50%; left: 50%;
width: 210px; height: 270px; transform: translate(-50%,-50%);
pointer-events: none;
}
.corners::before, .corners::after, .corners .c::before, .corners .c::after {
content:''; position: absolute;
width: 30px; height: 30px;
border-color: rgba(255,255,255,0.3); border-style: solid; border-width: 0;
transition: all 0.4s ease;
}
.corners::before { top:0;left:0; border-top-width:3px;border-left-width:3px; border-radius:10px 0 0 0; }
.corners::after { top:0;right:0; border-top-width:3px;border-right-width:3px; border-radius:0 10px 0 0; }
.corners .c::before { bottom:0;left:0; border-bottom-width:3px;border-left-width:3px; border-radius:0 0 0 10px; }
.corners .c::after { bottom:0;right:0; border-bottom-width:3px;border-right-width:3px; border-radius:0 0 10px 0; }
.corners.ok::before,.corners.ok::after,.corners.ok .c::before,.corners.ok .c::after {
border-color: var(--green);
box-shadow: 0 0 12px var(--green-glow);
}
/* Scan line */
.scanbar {
position: absolute; left: 50%; width: 190px; height: 2px;
transform: translateX(-50%);
background: linear-gradient(90deg, transparent, rgba(99,102,241,0.6), transparent);
animation: scanY 2.8s ease-in-out infinite;
pointer-events: none; opacity: 0.6;
}
.scanbar.ok { background: linear-gradient(90deg, transparent, rgba(34,197,94,0.7), transparent); }
@keyframes scanY {
0%,100% { top: calc(50% - 130px); }
50% { top: calc(50% + 130px); }
}
/* Loading cam overlay */
.cam-loading {
position: absolute; inset: 0;
background: rgba(7,11,20,0.94);
display: flex; flex-direction: column;
align-items: center; justify-content: center;
z-index: 15; gap: 18px; color: #fff;
backdrop-filter: blur(10px);
}
.cam-loading .ldring {
width: 52px; height: 52px; border-radius: 50%;
border: 3px solid rgba(255,255,255,0.06);
border-top-color: var(--accent2);
animation: spin 0.7s linear infinite;
}
.cam-loading p { font-size: 12px; color: rgba(255,255,255,0.45); font-weight: 500; }
/* ── Instructions Panel ── */
.instructions {
position: absolute; top: 68px; left: 50%;
transform: translateX(-50%);
background: rgba(7,11,20,0.88);
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(99,102,241,0.1);
border-radius: 14px; padding: 10px 16px;
z-index: 12; max-width: 320px; width: 90%;
}
.instr-title {
font-size: 10px; font-weight: 800; color: var(--accent2);
text-transform: uppercase; letter-spacing: 1.5px; margin-bottom: 6px;
}
.instr-list {
list-style: none; display: flex; flex-direction: column; gap: 4px;
}
.instr-list li {
font-size: 10.5px; color: rgba(255,255,255,0.55); font-weight: 500;
display: flex; align-items: center; gap: 6px;
}
.instr-list li i { font-size: 12px; color: var(--accent); flex-shrink: 0; }
/* Status pill */
.st-pill {
position: absolute; bottom: 16px; left: 50%; transform: translateX(-50%);
display: flex; align-items: center; gap: 8px;
padding: 10px 22px; border-radius: 28px;
font-size: 12px; font-weight: 700; color: #fff;
z-index: 12; white-space: nowrap;
backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
transition: all 0.4s ease;
}
.st-pill i { font-size: 18px; }
.st-pill.searching {
background: rgba(15,23,42,0.85);
border: 1px solid rgba(99,102,241,0.15);
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}
.st-pill.found {
background: rgba(22,163,74,0.88);
border: 1px solid rgba(74,222,128,0.3);
box-shadow: 0 4px 28px rgba(22,163,74,0.35);
}
.st-pill.warn {
background: rgba(220,38,38,0.88);
border: 1px solid rgba(248,113,113,0.25);
box-shadow: 0 4px 20px rgba(220,38,38,0.25);
}
/* ═══ BOTTOM BAR ═══ */
.bar-capture {
padding: 22px 24px 30px;
background: linear-gradient(0deg, rgba(7,11,20,0.99), rgba(7,11,20,0.75));
display: flex; align-items: center; justify-content: center;
position: relative; z-index: 20;
}
.shutter {
width: 74px; height: 74px; border-radius: 50%;
border: 4px solid rgba(255,255,255,0.3);
background: transparent; cursor: pointer;
display: flex; align-items: center; justify-content: center;
transition: all 0.25s ease; position: relative;
}
.shutter::after {
content:''; width: 58px; height: 58px; border-radius: 50%;
background: linear-gradient(135deg, #fff, #e2e8f0);
transition: 0.2s;
}
.shutter:hover::after { transform: scale(0.93); }
.shutter:active::after { transform: scale(0.86); background: #cbd5e1; }
.shutter:disabled { opacity: 0.25; cursor: not-allowed; pointer-events: none; }
.shutter-lbl {
font-size: 9px; color: rgba(255,255,255,0.35);
text-align: center; margin-top: 8px;
font-weight: 800; letter-spacing: 1px; text-transform: uppercase;
}
/* After capture bar */
.bar-after {
padding: 22px 24px 30px;
background: linear-gradient(0deg, rgba(7,11,20,0.99), rgba(7,11,20,0.75));
align-items: center; justify-content: center; gap: 28px; z-index: 20;
display: none;
}
.act-btn {
display: flex; flex-direction: column; align-items: center;
gap: 6px; border: none; background: none; cursor: pointer; transition: 0.2s;
}
.act-btn .ring {
width: 60px; height: 60px; border-radius: 50%;
display: flex; align-items: center; justify-content: center;
font-size: 24px; transition: all 0.25s ease;
}
.act-btn span { font-size: 9px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.8px; }
.act-btn.retry .ring { background: rgba(255,255,255,0.08); color: #fff; border: 1px solid rgba(255,255,255,0.08); }
.act-btn.retry span { color: rgba(255,255,255,0.4); }
.act-btn.retry:hover .ring { background: rgba(255,255,255,0.14); }
.act-btn.save .ring {
background: linear-gradient(135deg, #22c55e, #16a34a);
color: #052e16;
box-shadow: 0 4px 24px rgba(34,197,94,0.35);
}
.act-btn.save span { color: var(--green); }
.act-btn.save:hover .ring { transform: scale(1.06); box-shadow: 0 6px 32px rgba(34,197,94,0.45); }
/* Preview */
.preview {
flex: 1; position: relative; background: #1e2223;
overflow: hidden;
}
.preview canvas { width: 100%; height: 100%; object-fit: cover; }
.preview-tag {
position: absolute; top: 74px; left: 50%; transform: translateX(-50%);
background: rgba(22,163,74,0.92); color: #fff;
padding: 8px 22px; border-radius: 28px;
font-size: 11px; font-weight: 700;
display: flex; align-items: center; gap: 7px;
backdrop-filter: blur(12px); z-index: 5;
box-shadow: 0 4px 20px rgba(22,163,74,0.3);
text-transform: uppercase; letter-spacing: 0.5px;
}
.preview-tag i { font-size: 16px; }
/* Toast */
.toast {
position: absolute; bottom: 96px; left: 50%; transform: translateX(-50%);
padding: 12px 24px; border-radius: 16px;
font-size: 12px; font-weight: 700;
display: none; align-items: center; gap: 8px;
z-index: 25; white-space: nowrap;
animation: slideUp 0.3s ease;
}
.toast i { font-size: 17px; }
.toast.ok { background: #065f46; color: #a7f3d0; border: 1px solid #34d399; }
.toast.err { background: #7f1d1d; color: #fca5a5; border: 1px solid #f87171; }
@keyframes slideUp {
from { opacity:0; transform: translateX(-50%) translateY(12px); }
to { opacity:1; transform: translateX(-50%) translateY(0); }
}
/* ═══ SUCCESS PAGE ═══ */
.page-success {
align-items: center; justify-content: center;
padding: 40px 30px; text-align: center; color: #fff; gap: 10px;
}
.suc-ring {
width: 100px; height: 100px; border-radius: 50%;
background: linear-gradient(135deg, rgba(34,197,94,0.12), rgba(34,197,94,0.04));
border: 2px solid rgba(34,197,94,0.2);
display: flex; align-items: center; justify-content: center;
animation: pulseGreen 2.5s ease-in-out infinite;
margin-bottom: 8px;
}
.suc-ring i { font-size: 48px; color: var(--green); }
@keyframes pulseGreen {
0%,100% { box-shadow: 0 0 0 0 rgba(34,197,94,0.15); }
50% { box-shadow: 0 0 0 20px rgba(34,197,94,0); }
}
.page-success h2 { font-size: 22px; font-weight: 900; color: var(--green); }
.page-success p { font-size: 13px; color: rgba(255,255,255,0.4); line-height: 1.7; max-width: 280px; }
.suc-foto {
width: 110px; height: 110px; border-radius: 50%;
object-fit: cover; border: 3px solid var(--green);
box-shadow: 0 4px 28px rgba(34,197,94,0.3);
margin-top: 12px;
}
.suc-check {
display: flex; align-items: center; gap: 6px;
font-size: 11px; color: rgba(255,255,255,0.3); font-weight: 600;
margin-top: 8px;
}
.suc-check i { color: var(--green); font-size: 14px; }
/* ═══ BRIGHTNESS METER ═══ */
.brightness-meter {
position: absolute; top: 172px; right: 16px;
display: flex; flex-direction: column; align-items: center; gap: 4px;
z-index: 12;
}
.bm-bar {
width: 4px; height: 60px; border-radius: 4px;
background: rgba(255,255,255,0.1);
position: relative; overflow: hidden;
}
.bm-fill {
position: absolute; bottom: 0; left: 0; width: 100%;
border-radius: 4px; transition: height 0.5s ease, background 0.5s ease;
}
.bm-label {
font-size: 8px; font-weight: 800; text-transform: uppercase;
letter-spacing: 1px; writing-mode: vertical-rl;
text-orientation: mixed; color: rgba(255,255,255,0.3);
}
.bm-icon { font-size: 14px; transition: color 0.3s; }
</style>
</head>
<body>
<?php
$tokenParam = isset($_GET['token']) ? trim($_GET['token']) : '';
?>
<div class="phone">
<?php if ($tokenParam === ''): ?>
<script>window.location.href = '404.php';</script>
<?php exit; ?>
<?php else: ?>
<!-- PAGE: Validating -->
<div class="page page-validating" id="pgValidating">
<div class="val-ring"></div>
<p>Memvalidasi token...</p>
</div>
<!-- PAGE: Error -->
<div class="page page-error page-hidden" id="pgError">
<div class="err-icon expired" id="errIconWrap"><i class="mdi mdi-clock-alert-outline" id="errIcon"></i></div>
<h2 id="errTitle">Token Kadaluwarsa</h2>
<p id="errMsg">Token QR code ini sudah pernah digunakan dan tidak bisa dipakai lagi.</p>
</div>
<!-- PAGE: Camera -->
<div class="page page-hidden" id="pgCamera">
<div class="header">
<div class="header-left">
<div class="header-logo"><i class="mdi mdi-shield-check"></i></div>
<div class="header-text">
<span>Identity Verification</span>
<h1>Verifikasi Wajah</h1>
</div>
</div>
<div class="header-badge" id="nameTag"></div>
</div>
<!-- Camera -->
<div class="cam-area" id="camArea">
<video id="vid" autoplay playsinline muted></video>
<canvas class="overlay-cv" id="ovCanvas"></canvas>
<div class="face-oval" id="oval">
<svg viewBox="0 0 300 380" xmlns="http://www.w3.org/2000/svg">
<defs><mask id="om"><rect width="100%" height="100%" fill="white"/><ellipse cx="150" cy="185" rx="105" ry="140" fill="black"/></mask></defs>
<rect width="100%" height="100%" fill="rgba(0,0,0,0.55)" mask="url(#om)"/>
<ellipse cx="150" cy="185" rx="105" ry="140" fill="none" stroke="rgba(255,255,255,0.3)" stroke-width="2.5" stroke-dasharray="8 5" id="ovalRing"/>
</svg>
</div>
<div class="corners" id="corners"><div class="c"></div></div>
<div class="scanbar" id="scanbar"></div>
<!-- Instructions -->
<div class="instructions" id="instrPanel">
<div class="instr-title">Panduan Verifikasi</div>
<ul class="instr-list">
<li><i class="mdi mdi-lightbulb-on"></i> Pastikan pencahayaan cukup terang</li>
<li><i class="mdi mdi-face-man"></i> Posisikan wajah dalam bingkai oval</li>
<li><i class="mdi mdi-account-remove"></i> Hanya 1 wajah yang boleh terdeteksi</li>
<li><i class="mdi mdi-sunglasses"></i> Lepas kacamata hitam / masker</li>
</ul>
</div>
<!-- Brightness Meter -->
<div class="brightness-meter" id="brightMeter">
<i class="mdi mdi-white-balance-sunny bm-icon" id="bmIcon"></i>
<div class="bm-bar"><div class="bm-fill" id="bmFill" style="height:50%;background:#f59e0b;"></div></div>
<span class="bm-label">Cahaya</span>
</div>
<!-- Loading -->
<div class="cam-loading" id="camLoading">
<div class="ldring"></div>
<p>Memuat kamera & model deteksi wajah...</p>
</div>
<!-- Status -->
<div class="st-pill searching" id="stPill">
<i class="mdi mdi-face-recognition" id="stIcon"></i>
<span id="stText">Mempersiapkan...</span>
</div>
</div>
<!-- Preview -->
<div class="preview page-hidden" id="previewWrap">
<canvas id="capCanvas"></canvas>
<div class="preview-tag"><i class="mdi mdi-check-circle"></i> Foto Berhasil Diambil</div>
</div>
<!-- Bottom: Capture -->
<div class="bar-capture" id="barCapture">
<div style="text-align:center;">
<button class="shutter" id="btnShutter" disabled></button>
<div class="shutter-lbl">Ambil Foto</div>
</div>
</div>
<!-- Bottom: After -->
<div class="bar-after" id="barAfter">
<button class="act-btn retry" id="btnRetake">
<div class="ring"><i class="mdi mdi-refresh"></i></div>
<span>Ulangi</span>
</button>
<button class="act-btn save" id="btnSave">
<div class="ring"><i class="mdi mdi-check-bold"></i></div>
<span>Simpan</span>
</button>
</div>
<div class="toast" id="toast"></div>
</div>
<!-- PAGE: Success -->
<div class="page page-success page-hidden" id="pgSuccess">
<div class="suc-ring"><i class="mdi mdi-check-circle"></i></div>
<h2>Verifikasi Berhasil!</h2>
<p>Foto wajah Anda telah berhasil tersimpan. Anda dapat menutup halaman ini.</p>
<img id="sucFoto" class="suc-foto" src="" alt="" style="display:none;">
<div class="suc-check"><i class="mdi mdi-check-circle"></i> Data terverifikasi dan tersimpan</div>
</div>
<?php endif; ?>
</div>
<?php if ($tokenParam !== ''): ?>
<script src="https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/dist/face_api.min.js"></script>
<script>
(function() {
var TOKEN = '<?= htmlspecialchars($tokenParam, ENT_QUOTES); ?>';
var MODEL_URL = 'https://cdn.jsdelivr.net/npm/@vladmandic/face-api/model';
var stream = null, detectLoop = null, faceOk = false, dataURL = null, occupantId = null;
var brightInterval = null;
/* ── Pages ────────────────────── */
var pgValidating = document.getElementById('pgValidating');
var pgError = document.getElementById('pgError');
var pgCamera = document.getElementById('pgCamera');
var pgSuccess = document.getElementById('pgSuccess');
function showPage(pg) {
[pgValidating, pgError, pgCamera, pgSuccess].forEach(function(p) {
if (p) p.classList.add('page-hidden');
});
if (pg) pg.classList.remove('page-hidden');
}
/* ── Camera DOM ──────────────── */
var vid = document.getElementById('vid');
var ovCanvas = document.getElementById('ovCanvas');
var oval = document.getElementById('oval');
var corners = document.getElementById('corners');
var scanbar = document.getElementById('scanbar');
var camLoading = document.getElementById('camLoading');
var instrPanel = document.getElementById('instrPanel');
var stPill = document.getElementById('stPill');
var stIcon = document.getElementById('stIcon');
var stText = document.getElementById('stText');
var btnShutter = document.getElementById('btnShutter');
var camArea = document.getElementById('camArea');
var previewWrap= document.getElementById('previewWrap');
var capCanvas = document.getElementById('capCanvas');
var barCapture = document.getElementById('barCapture');
var barAfter = document.getElementById('barAfter');
var btnRetake = document.getElementById('btnRetake');
var btnSave = document.getElementById('btnSave');
var toast = document.getElementById('toast');
var bmFill = document.getElementById('bmFill');
var bmIcon = document.getElementById('bmIcon');
function setStatus(type, txt) {
stPill.className = 'st-pill';
if (type === 'search') { stPill.classList.add('searching'); stIcon.className = 'mdi mdi-face-recognition'; }
if (type === 'ok') { stPill.classList.add('found'); stIcon.className = 'mdi mdi-check-circle'; }
if (type === 'err') { stPill.classList.add('warn'); stIcon.className = 'mdi mdi-alert-circle'; }
stText.textContent = txt;
}
function showToast(type, msg) {
toast.className = 'toast ' + type;
toast.innerHTML = '<i class="mdi mdi-' + (type==='ok' ? 'check-circle' : 'alert-circle') + '"></i> ' + msg;
toast.style.display = 'flex';
}
/* ── Step 1: Validate Token ──── */
function validateToken() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'validate_foto_token.php?token=' + encodeURIComponent(TOKEN), true);
xhr.onload = function() {
try {
var d = JSON.parse(xhr.responseText);
if (d.valid) {
occupantId = d.id_occupant;
document.getElementById('nameTag').textContent = d.name;
showPage(pgCamera);
initCamera();
} else {
window.location.href = '404.php';
}
} catch(e) {
document.getElementById('errTitle').textContent = 'Kesalahan';
document.getElementById('errMsg').textContent = 'Format respons tidak valid.';
showPage(pgError);
}
};
xhr.onerror = function() {
window.location.href = '404.php';
};
xhr.send();
}
/* ── Step 2: Load models + camera ─ */
var modelLoaded = false;
var cameraStarted = false;
function initCamera() {
// Wait for face-api.js library to be available, then start everything
function waitAndInit() {
if (typeof faceapi === 'undefined') {
// face-api.js not loaded yet, wait
setTimeout(waitAndInit, 200);
return;
}
// Start camera immediately while models load in parallel
var cameraReady = startCamera();
// Load face detection model
faceapi.nets.tinyFaceDetector.loadFromUri(MODEL_URL).then(function() {
modelLoaded = true;
onReadyCheck();
}).catch(function(e) {
console.error('Model load error:', e);
// Try alternate model URL as fallback
faceapi.nets.tinyFaceDetector.loadFromUri('https://cdn.jsdelivr.net/gh/justadudewhohacks/face-api.js@master/weights').then(function() {
modelLoaded = true;
onReadyCheck();
}).catch(function(e2) {
console.error('Fallback model load error:', e2);
camLoading.style.display = 'none';
setStatus('err', 'Gagal memuat model deteksi wajah');
});
});
cameraReady.then(function(ok) {
cameraStarted = ok;
if (!ok) {
camLoading.style.display = 'none';
setStatus('err', 'Kamera tidak tersedia');
return;
}
onReadyCheck();
});
}
// Called when either camera or model finishes - starts detection when both ready
function onReadyCheck() {
if (cameraStarted && modelLoaded) {
camLoading.style.display = 'none';
setStatus('search', 'Posisikan wajah Anda...');
startDetection();
startBrightnessCheck();
setTimeout(function() {
if (instrPanel) instrPanel.style.opacity = '0';
setTimeout(function() { if (instrPanel) instrPanel.style.display = 'none'; }, 500);
}, 6000);
}
}
// Set a timeout - if everything takes too long, show error
setTimeout(function() {
if (!modelLoaded || !cameraStarted) {
if (typeof faceapi === 'undefined') {
camLoading.style.display = 'none';
setStatus('err', 'Gagal memuat library deteksi wajah');
} else if (!cameraStarted) {
camLoading.style.display = 'none';
setStatus('err', 'Kamera tidak dapat dimulai');
}
}
}, 20000);
waitAndInit();
}
function startCamera() {
var isMobile = window.innerWidth <= 768;
var videoConstraints = {
facingMode: 'user'
};
if (!isMobile) {
videoConstraints.width = { ideal: 720 };
videoConstraints.height = { ideal: 960 };
}
return navigator.mediaDevices.getUserMedia({
video: videoConstraints,
audio: false
}).then(function(s) {
stream = s;
vid.srcObject = s;
return new Promise(function(resolve) {
vid.onloadedmetadata = function() {
vid.play().then(function() {
resolve(true);
}).catch(function(e) {
console.error('Video play error:', e);
resolve(false);
});
};
// Safety timeout if onloadedmetadata never fires
setTimeout(function() { resolve(false); }, 10000);
});
}).catch(function(e) {
console.error('Camera error:', e);
return false;
});
}
/* ── Face Detection ──────────── */
function startDetection() {
var opts = new faceapi.TinyFaceDetectorOptions({ inputSize: 224, scoreThreshold: 0.45 });
detectLoop = setInterval(function() {
if (vid.paused || vid.ended) return;
faceapi.detectAllFaces(vid, opts).then(function(dets) {
var vw = vid.videoWidth, vh = vid.videoHeight;
ovCanvas.width = vw; ovCanvas.height = vh;
var ctx = ovCanvas.getContext('2d');
ctx.clearRect(0, 0, vw, vh);
if (dets.length === 1) {
faceOk = true;
oval.classList.add('ok');
corners.classList.add('ok');
scanbar.classList.add('ok');
setStatus('ok', 'Wajah terdeteksi — Siap!');
btnShutter.disabled = false;
} else if (dets.length > 1) {
faceOk = false;
oval.classList.remove('ok');
corners.classList.remove('ok');
scanbar.classList.remove('ok');
setStatus('err', 'Terdeteksi lebih dari 1 wajah');
btnShutter.disabled = true;
} else {
faceOk = false;
oval.classList.remove('ok');
corners.classList.remove('ok');
scanbar.classList.remove('ok');
setStatus('search', 'Posisikan wajah Anda...');
btnShutter.disabled = true;
}
});
}, 280);
}
/* ── Brightness Check ────────── */
function startBrightnessCheck() {
var tmpCanvas = document.createElement('canvas');
var tmpCtx = tmpCanvas.getContext('2d');
brightInterval = setInterval(function() {
if (vid.paused || vid.ended || !vid.videoWidth) return;
tmpCanvas.width = 80; tmpCanvas.height = 60;
tmpCtx.drawImage(vid, 0, 0, 80, 60);
var data = tmpCtx.getImageData(0, 0, 80, 60).data;
var sum = 0, count = data.length / 4;
for (var i = 0; i < data.length; i += 4) {
sum += (data[i] * 0.299 + data[i+1] * 0.587 + data[i+2] * 0.114);
}
var avg = sum / count; // 0-255
var pct = Math.min(100, Math.max(5, (avg / 255) * 100));
bmFill.style.height = pct + '%';
if (pct < 30) {
bmFill.style.background = '#ef4444';
bmIcon.style.color = '#ef4444';
} else if (pct < 55) {
bmFill.style.background = '#f59e0b';
bmIcon.style.color = '#f59e0b';
} else {
bmFill.style.background = '#22c55e';
bmIcon.style.color = '#22c55e';
}
}, 800);
}
/* ── Capture ─────────────────── */
function capture() {
if (!faceOk) return;
clearInterval(detectLoop);
clearInterval(brightInterval);
var vw = vid.videoWidth, vh = vid.videoHeight;
capCanvas.width = vw; capCanvas.height = vh;
var ctx = capCanvas.getContext('2d');
ctx.save(); ctx.translate(vw, 0); ctx.scale(-1, 1);
ctx.drawImage(vid, 0, 0, vw, vh);
ctx.restore();
dataURL = capCanvas.toDataURL('image/png');
if (stream) stream.getTracks().forEach(function(t) { t.stop(); });
camArea.style.display = 'none';
previewWrap.classList.remove('page-hidden');
previewWrap.style.display = 'block';
barCapture.style.display = 'none';
barAfter.style.display = 'flex';
}
/* ── Retake ──────────────────── */
function retake() {
dataURL = null;
previewWrap.classList.add('page-hidden');
previewWrap.style.display = '';
camArea.style.display = 'block';
barAfter.style.display = 'none';
barCapture.style.display = 'flex';
toast.style.display = 'none';
camLoading.style.display = 'flex';
startCamera().then(function(ok) {
if (ok) {
camLoading.style.display = 'none';
setStatus('search', 'Posisikan wajah Anda...');
startDetection();
startBrightnessCheck();
}
});
}
/* ── Save ────────────────────── */
function save() {
if (!dataURL) return;
btnSave.querySelector('.ring').innerHTML = '<i class="mdi mdi-loading mdi-spin"></i>';
btnSave.disabled = true;
var fd = new FormData();
fd.append('token', TOKEN);
fd.append('foto', dataURL);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'save_foto.php', true);
xhr.onload = function() {
try {
var d = JSON.parse(xhr.responseText);
if (d.status === 'success') {
showPage(pgSuccess);
if (d.foto) {
document.getElementById('sucFoto').src = d.foto;
document.getElementById('sucFoto').style.display = 'block';
}
} else {
showToast('err', d.message || 'Gagal menyimpan');
btnSave.disabled = false;
btnSave.querySelector('.ring').innerHTML = '<i class="mdi mdi-check-bold"></i>';
}
} catch(e) {
showToast('err', 'Respons tidak valid');
btnSave.disabled = false;
btnSave.querySelector('.ring').innerHTML = '<i class="mdi mdi-check-bold"></i>';
}
};
xhr.onerror = function() {
showToast('err', 'Koneksi gagal');
btnSave.disabled = false;
btnSave.querySelector('.ring').innerHTML = '<i class="mdi mdi-check-bold"></i>';
};
xhr.send(fd);
}
/* ── Events ──────────────────── */
if (btnShutter) btnShutter.addEventListener('click', capture);
if (btnRetake) btnRetake.addEventListener('click', retake);
if (btnSave) btnSave.addEventListener('click', save);
/* ── Init ────────────────────── */
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', validateToken);
} else {
validateToken();
}
/* ── PWA Service Worker ──────── */
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw_foto.js').catch(function() {});
}
/* ── Smooth instruction fade ── */
var ip = document.getElementById('instrPanel');
if (ip) ip.style.transition = 'opacity 0.5s ease';
})();
</script>
<?php endif; ?>
</body>
</html>