2169 lines
101 KiB
PHP
2169 lines
101 KiB
PHP
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Live Assessment Room - {{ $interview->candidate_name }} | SingleLogin</title>
|
|
@vite(['resources/css/app.css', 'resources/js/app.js'])
|
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
<link href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600&family=Instrument+Sans:wght@400;500;600;700&family=Outfit:wght@500;600;700&display=swap" rel="stylesheet">
|
|
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
|
|
|
|
<!-- PeerJS, Metered SDK, SweetAlert2 & html2canvas -->
|
|
<script src="https://unpkg.com/peerjs@1.5.2/dist/peerjs.min.js"></script>
|
|
<script src="//cdn.metered.ca/sdk/video/1.4.6/sdk.min.js"></script>
|
|
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
|
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
|
|
|
|
<!-- Monaco Code Editor Loader (loaded after UMD libraries to prevent define.amd conflicts) -->
|
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs/loader.min.js"></script>
|
|
|
|
|
|
<style>
|
|
:root {
|
|
--bg-color: #080c14;
|
|
--card-bg: #0f172a;
|
|
--card-border: rgba(255, 255, 255, 0.15);
|
|
--accent-primary: #6366f1;
|
|
}
|
|
|
|
/* Modern Custom Scrollbars */
|
|
html, body, *, ::-webkit-scrollbar {
|
|
scrollbar-width: thin;
|
|
scrollbar-color: rgba(255, 255, 255, 0.4) rgba(15, 23, 42, 0.35);
|
|
}
|
|
|
|
::-webkit-scrollbar {
|
|
width: 5px;
|
|
height: 5px;
|
|
}
|
|
|
|
::-webkit-scrollbar-track {
|
|
background: rgba(15, 23, 42, 0.35);
|
|
}
|
|
|
|
::-webkit-scrollbar-thumb {
|
|
background: rgba(255, 255, 255, 0.4);
|
|
border-radius: 10px;
|
|
}
|
|
|
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
|
|
body {
|
|
font-family: 'Instrument Sans', sans-serif;
|
|
background-color: var(--bg-color);
|
|
color: white;
|
|
height: 100vh;
|
|
display: flex;
|
|
flex-direction: column;
|
|
overflow: hidden;
|
|
}
|
|
|
|
.ide-header {
|
|
height: 60px;
|
|
background: #0d1322;
|
|
border-bottom: 1px solid var(--card-border);
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: space-between;
|
|
padding: 0 20px;
|
|
}
|
|
|
|
.ide-layout {
|
|
display: grid;
|
|
grid-template-columns: 1fr 340px;
|
|
height: calc(100vh - 60px);
|
|
width: 100%;
|
|
}
|
|
|
|
.editor-section {
|
|
display: flex;
|
|
flex-direction: column;
|
|
border-right: 1px solid var(--card-border);
|
|
height: 100%;
|
|
}
|
|
|
|
#monaco-editor-container {
|
|
flex: 1;
|
|
width: 100%;
|
|
height: 100%;
|
|
}
|
|
|
|
.terminal-section {
|
|
height: 220px;
|
|
background: #050811;
|
|
border-top: 1px solid var(--card-border);
|
|
display: flex;
|
|
flex-direction: column;
|
|
}
|
|
|
|
.terminal-header {
|
|
height: 36px;
|
|
background: #090e1a;
|
|
border-bottom: 1px solid rgba(255,255,255,0.08);
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: space-between;
|
|
padding: 0 16px;
|
|
font-size: 0.75rem;
|
|
color: #94a3b8;
|
|
font-weight: 600;
|
|
}
|
|
|
|
#terminal-output {
|
|
flex: 1;
|
|
padding: 12px 16px;
|
|
font-family: 'Fira Code', monospace;
|
|
font-size: 0.8rem;
|
|
color: #34d399;
|
|
overflow-y: auto;
|
|
white-space: pre-wrap;
|
|
}
|
|
|
|
.proctor-sidebar {
|
|
background: #0d1322;
|
|
padding: 16px;
|
|
display: flex;
|
|
flex-direction: column;
|
|
gap: 16px;
|
|
overflow-y: auto;
|
|
}
|
|
|
|
.webcam-box {
|
|
width: 100%;
|
|
height: 180px;
|
|
min-height: 180px;
|
|
flex-shrink: 0;
|
|
background: #000;
|
|
border-radius: 12px;
|
|
border: 2px solid var(--card-border);
|
|
overflow: hidden;
|
|
position: relative;
|
|
}
|
|
|
|
#webcam {
|
|
width: 100%;
|
|
height: 100%;
|
|
object-fit: cover;
|
|
}
|
|
|
|
.btn-ide {
|
|
padding: 8px 16px;
|
|
border-radius: 8px;
|
|
font-weight: 600;
|
|
font-size: 0.8rem;
|
|
cursor: pointer;
|
|
border: 1px solid var(--card-border);
|
|
background: rgba(255,255,255,0.05);
|
|
color: white;
|
|
transition: all 0.2s ease;
|
|
}
|
|
|
|
.btn-ide-primary {
|
|
background: #10b981;
|
|
border-color: #10b981;
|
|
color: white;
|
|
}
|
|
|
|
.btn-ide-run {
|
|
background: #6366f1;
|
|
border-color: #6366f1;
|
|
color: white;
|
|
}
|
|
|
|
/* Warning Popup Overlay */
|
|
#warning-banner {
|
|
position: fixed;
|
|
top: 70px;
|
|
left: 50%;
|
|
transform: translateX(-50%);
|
|
background: rgba(239, 68, 68, 0.95);
|
|
color: white;
|
|
padding: 12px 24px;
|
|
border-radius: 12px;
|
|
font-weight: 700;
|
|
font-size: 0.9rem;
|
|
box-shadow: 0 10px 30px rgba(239, 68, 68, 0.5);
|
|
z-index: 9999;
|
|
display: none;
|
|
backdrop-filter: blur(10px);
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
|
|
<!-- IDE Header Bar -->
|
|
<header class="ide-header">
|
|
<div style="display: flex; align-items: center; gap: 12px;">
|
|
<div style="font-weight: 700; font-family: 'Outfit', sans-serif; font-size: 1.05rem; color: white;">
|
|
Candidate Assessment Room
|
|
</div>
|
|
<code style="background: rgba(255,255,255,0.06); padding: 4px 10px; border-radius: 6px; color: #38bdf8; font-size: 0.75rem;">
|
|
ID: {{ $interview->submission_unique_id }}
|
|
</code>
|
|
</div>
|
|
|
|
<div style="display: flex; align-items: center; gap: 14px;">
|
|
<button onclick="toggleNotepadModal()" class="btn-ide" style="background: rgba(99,102,241,0.2); border-color: #6366f1;">
|
|
📝 Open Notepad
|
|
</button>
|
|
|
|
<button onclick="toggleDrawingModal()" class="btn-ide" style="background: rgba(6,182,212,0.2); border-color: #06b6d4;">
|
|
🎨 Open Drawing
|
|
</button>
|
|
|
|
<div style="display: flex; align-items: center; gap: 8px;">
|
|
<label style="font-size: 0.75rem; color: #94a3b8; font-weight: 500;">Language:</label>
|
|
<select id="language-select" class="btn-ide" style="background: #151b2c;">
|
|
<option value="python" {{ strtolower($interview->language) === 'python' ? 'selected' : '' }}>Python 3</option>
|
|
<option value="cpp" {{ strtolower($interview->language) === 'cpp' ? 'selected' : '' }}>C++ (GCC)</option>
|
|
<option value="c" {{ strtolower($interview->language) === 'c' ? 'selected' : '' }}>C (GCC)</option>
|
|
<option value="java" {{ strtolower($interview->language) === 'java' ? 'selected' : '' }}>Java 15</option>
|
|
<option value="php" {{ strtolower($interview->language) === 'php' ? 'selected' : '' }}>PHP 8.2 / Laravel</option>
|
|
<option value="javascript" {{ strtolower($interview->language) === 'javascript' ? 'selected' : '' }}>JavaScript (Node.js)</option>
|
|
</select>
|
|
</div>
|
|
|
|
<button onclick="runCode()" class="btn-ide btn-ide-run">
|
|
▶ Run Code
|
|
</button>
|
|
|
|
<button onclick="submitSolution()" class="btn-ide btn-ide-primary">
|
|
✓ Submit Final Solution
|
|
</button>
|
|
|
|
<button onclick="candidateLogoutAction()" class="btn-ide" style="background: rgba(239,68,68,0.2); border-color: #ef4444; color: #fca5a5; font-weight: 700;">
|
|
🚪 Logout
|
|
</button>
|
|
</div>
|
|
</header>
|
|
|
|
<!-- Candidate Notepad Modal -->
|
|
<div id="notepad-modal" style="position: fixed; top: 70px; right: 360px; width: 420px; height: 350px; background: #0f172a; border: 1.5px solid #6366f1; border-radius: 16px; box-shadow: 0 20px 40px rgba(0,0,0,0.6); display: none; flex-direction: column; z-index: 1000; overflow: hidden;">
|
|
<div style="background: #1e293b; padding: 10px 16px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(255,255,255,0.1);">
|
|
<div style="font-weight: 700; font-size: 0.85rem; color: white;">📝 Candidate Notepad (Synced)</div>
|
|
<button onclick="toggleNotepadModal()" style="background: none; border: none; color: #94a3b8; font-size: 1.2rem; cursor: pointer;">×</button>
|
|
</div>
|
|
<textarea id="notepad-textarea" oninput="saveNotepadContent()" placeholder="Type rough notes, pseudo-code, or thoughts here..." style="flex: 1; width: 100%; padding: 14px; background: #0b0f19; color: #e2e8f0; border: none; outline: none; font-family: 'Fira Code', monospace; font-size: 0.85rem; resize: none;">{{ $interview->candidate_notes }}</textarea>
|
|
<div style="padding: 6px 12px; background: #0d1322; font-size: 0.65rem; color: #34d399; text-align: right;">
|
|
✓ Auto-saved to interviewer portal
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Candidate Canvas Drawing Modal -->
|
|
<div id="drawing-modal" style="position: fixed; top: 70px; right: 360px; width: 550px; height: 420px; background: #0f172a; border: 1.5px solid #06b6d4; border-radius: 16px; box-shadow: 0 20px 40px rgba(0,0,0,0.6); display: none; flex-direction: column; z-index: 1000; overflow: hidden;">
|
|
<div style="background: #1e293b; padding: 10px 16px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(255,255,255,0.1);">
|
|
<div style="font-weight: 700; font-size: 0.85rem; color: white;">🎨 Candidate Live Drawing Board</div>
|
|
<div style="display: flex; gap: 8px; align-items: center;">
|
|
<input type="color" id="draw-color" value="#38bdf8" style="width: 26px; height: 26px; border: none; border-radius: 50%; cursor: pointer;">
|
|
<button onclick="clearCanvasDraw()" class="btn-ide" style="padding: 2px 8px; font-size: 0.7rem;">Clear</button>
|
|
<button onclick="toggleDrawingModal()" style="background: none; border: none; color: #94a3b8; font-size: 1.2rem; cursor: pointer;">×</button>
|
|
</div>
|
|
</div>
|
|
<div style="flex: 1; background: #050811; position: relative;">
|
|
<canvas id="drawing-canvas" width="550" height="340" style="cursor: crosshair; display: block; width: 100%; height: 100%;"></canvas>
|
|
</div>
|
|
<div style="padding: 6px 12px; background: #0d1322; font-size: 0.65rem; color: #38bdf8; text-align: right;">
|
|
🎨 Draw architecture / logic diagrams (Auto-synced to Interviewer)
|
|
</div>
|
|
</div>
|
|
|
|
<!-- IDE Room Layout -->
|
|
<div class="ide-layout">
|
|
<!-- Main Editor & Terminal Area -->
|
|
<div class="editor-section">
|
|
<div id="monaco-editor-container"></div>
|
|
|
|
<div class="terminal-section">
|
|
<div class="terminal-header">
|
|
<span>EXECUTION OUTPUT TERMINAL (STDOUT / STDERR)</span>
|
|
<span id="run-status" style="color: #94a3b8;">Ready</span>
|
|
</div>
|
|
<div id="terminal-output">// Press 'Run Code' to execute candidate solution live...</div>
|
|
</div>
|
|
</div>
|
|
|
|
@php
|
|
$words = preg_split('/\s+/', trim($interview->candidate_name));
|
|
if (count($words) >= 2) {
|
|
$candInitials = strtoupper(substr($words[0], 0, 1) . substr(end($words), 0, 1));
|
|
} else {
|
|
$nameStr = trim($interview->candidate_name);
|
|
$candInitials = strtoupper(substr($nameStr, 0, 1) . (strlen($nameStr) > 1 ? substr($nameStr, -1) : ''));
|
|
}
|
|
@endphp
|
|
|
|
<!-- Sidebar: Real-Time 2-Way Interview Call & Screen Share -->
|
|
<div class="proctor-sidebar">
|
|
<!-- Candidate Camera Feed -->
|
|
<div class="webcam-box" style="position: relative;">
|
|
<video id="webcam" autoplay muted playsinline style="width: 100%; height: 100%; object-fit: cover;"></video>
|
|
<div id="webcam-avatar-placeholder" style="position: absolute; inset: 0; display: none; flex-direction: column; align-items: center; justify-content: center; background: #0f172a; color: white; z-index: 5;">
|
|
<div style="width: 60px; height: 60px; border-radius: 50%; background: linear-gradient(135deg, #6366f1 0%, #0078d4 100%); display: flex; align-items: center; justify-content: center; font-size: 1.5rem; font-weight: 800; font-family: 'Outfit', sans-serif; box-shadow: 0 0 15px rgba(99,102,241,0.4);">
|
|
{{ $candInitials }}
|
|
</div>
|
|
<div style="font-size: 0.7rem; color: #94a3b8; margin-top: 6px;">Camera Disabled</div>
|
|
</div>
|
|
<div style="position: absolute; bottom: 8px; left: 8px; background: rgba(0,0,0,0.6); padding: 2px 8px; border-radius: 4px; font-size: 0.65rem; color: #34d399; font-weight: 600; z-index: 10;">
|
|
📷 Candidate Camera
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Remote Interviewer Panelist Video Grid (Multi-Party WebRTC Mesh) -->
|
|
<div id="interviewer-mesh-grid" style="display: flex; flex-direction: column; gap: 10px; width: 100%;">
|
|
<div id="interviewer-placeholder-box" class="webcam-box" style="position: relative; border-color: #6366f1;">
|
|
<video id="interviewer-video-default" autoplay playsinline style="width: 100%; height: 100%; object-fit: cover; background: #050811; display: none;"></video>
|
|
<div id="interviewer-video-placeholder" style="position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; background: rgba(15,23,42,0.95); color: #94a3b8; font-size: 0.75rem; text-align: center; padding: 10px; z-index: 5;">
|
|
<div id="interviewer-avatar-circle" style="width: 60px; height: 60px; border-radius: 50%; background: linear-gradient(135deg, #38bdf8 0%, #6366f1 100%); display: flex; align-items: center; justify-content: center; font-size: 1.5rem; font-weight: 800; font-family: 'Outfit', sans-serif; color: white; margin-bottom: 6px; box-shadow: 0 0 15px rgba(56,189,248,0.4);">
|
|
IV
|
|
</div>
|
|
<div id="call-status-sub" style="font-size: 0.7rem; color: #e2e8f0; font-weight: 600;">Interviewer Panel</div>
|
|
<div style="font-size: 0.65rem; color: #38bdf8; margin-top: 2px;">Waiting for interviewer panelist to join call...</div>
|
|
</div>
|
|
<div style="position: absolute; bottom: 8px; left: 8px; background: rgba(99,102,241,0.8); padding: 2px 8px; border-radius: 4px; font-size: 0.65rem; color: white; font-weight: 600; z-index: 10;">
|
|
🎙️ Interviewer / Panelist
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<canvas id="proctor-canvas" style="display: none;" width="320" height="240"></canvas>
|
|
|
|
<!-- Candidate Profile Info -->
|
|
<div style="background: rgba(255,255,255,0.03); border: 1px solid var(--card-border); border-radius: 12px; padding: 14px; font-size: 0.8rem;">
|
|
<div style="font-weight: 700; color: white; margin-bottom: 6px;">Candidate Profile</div>
|
|
<div style="color: #94a3b8;">Name: <strong style="color: white;">{{ $interview->candidate_name }}</strong></div>
|
|
<div style="color: #94a3b8;">Email: <span style="color: white;">{{ $interview->candidate_email }}</span></div>
|
|
<div style="color: #94a3b8; margin-top: 6px;">Access Expires: <span style="color: #fca5a5;">{{ $interview->expires_at->format('H:i:s T') }}</span></div>
|
|
</div>
|
|
|
|
<!-- Real-Time Call Controls (Mic, Camera, Screen Sharing) -->
|
|
<div style="background: rgba(99,102,241,0.1); border: 1px solid rgba(99,102,241,0.3); border-radius: 14px; padding: 14px;">
|
|
<div style="font-size: 0.8rem; font-weight: 700; color: white; margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between;">
|
|
<span>📞 Real-Time Interview Call</span>
|
|
<span id="call-status-badge" style="font-size: 0.65rem; background: rgba(16,185,129,0.2); color: #34d399; padding: 2px 8px; border-radius: 999px;">READY</span>
|
|
</div>
|
|
|
|
<button id="candidate-join-active-call-btn" onclick="acceptCandidateCall()" class="btn-ide" style="display: none; width: 100%; padding: 10px; margin-bottom: 10px; font-size: 0.8rem; font-weight: 700; background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border: none; box-shadow: 0 0 15px rgba(16,185,129,0.4); cursor: pointer; animation: acceptGlow 1.5s infinite alternate;">
|
|
🟢 📞 Call in Progress • Join Call Now
|
|
</button>
|
|
|
|
<div style="display: flex; gap: 8px; margin-bottom: 10px;">
|
|
<button id="toggle-mic-btn" onclick="toggleMic()" class="btn-ide" style="flex: 1; padding: 8px; font-size: 0.75rem; background: rgba(16,185,129,0.2); border-color: #10b981;">
|
|
🎤 Mic On
|
|
</button>
|
|
<button id="toggle-cam-btn" onclick="toggleCam()" class="btn-ide" style="flex: 1; padding: 8px; font-size: 0.75rem; background: rgba(16,185,129,0.2); border-color: #10b981;">
|
|
📷 Cam On
|
|
</button>
|
|
<button id="leave-call-btn" onclick="candidateLeaveCall()" class="btn-ide" style="padding: 8px; font-size: 0.75rem; background: rgba(239,68,68,0.2); border-color: #ef4444; color: #fca5a5;" title="Leave 2-Way Call">
|
|
🚪 Leave Call
|
|
</button>
|
|
</div>
|
|
|
|
<button id="share-screen-btn" onclick="startScreenShare()" class="btn-ide btn-ide-run" style="width: 100%; padding: 10px; font-size: 0.8rem; background: linear-gradient(135deg, #6366f1 0%, #0078d4 100%);">
|
|
🖥️ Share Screen with Interviewer
|
|
</button>
|
|
</div>
|
|
|
|
<!-- 2-Way Real-Time Chat Container with Interviewer/Panelist -->
|
|
<div style="background: rgba(15,23,42,0.8); border: 1px solid var(--card-border); border-radius: 14px; padding: 12px; margin-top: 10px;">
|
|
<div style="font-size: 0.8rem; font-weight: 700; color: white; margin-bottom: 8px; display: flex; align-items: center; gap: 6px;">
|
|
💬 Live Chat with Interviewer
|
|
</div>
|
|
<div id="candidate-chat-history" style="background: #050811; border: 1px solid var(--card-border); border-radius: 10px; padding: 8px; height: 130px; overflow-y: auto; font-size: 0.72rem; margin-bottom: 8px;">
|
|
<div style="color: #94a3b8; font-style: italic; text-align: center; padding-top: 40px;">No messages yet. Send a message below.</div>
|
|
</div>
|
|
<div style="display: flex; gap: 6px;">
|
|
<input type="text" id="candidate-chat-input" placeholder="Type message to panelist..." onkeydown="if(event.key==='Enter') sendCandidateMessage()" class="form-input" style="font-size: 0.75rem; background: #0b0f19; color: #ffffff !important; border: 1px solid var(--card-border); padding: 6px 10px; flex: 1;">
|
|
<button onclick="sendCandidateMessage()" class="btn-ide" style="padding: 6px 10px; font-size: 0.75rem; background: #6366f1; border: none; font-weight: 600;">
|
|
Send
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- CANDIDATE INCOMING CALL MODAL / RINGING OVERLAY (DISABLED: Auto-connect enabled) -->
|
|
<div id="candidate-incoming-modal" style="display: none !important; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(5, 8, 17, 0.85); backdrop-filter: blur(16px); align-items: center; justify-content: center; z-index: 10000; opacity: 0; pointer-events: none; transition: opacity 0.3s ease;">
|
|
|
|
<div style="max-width: 440px; width: 90%; background: linear-gradient(145deg, #0f172a 0%, #1e1b4b 100%); border: 2px solid #10b981; border-radius: 24px; padding: 32px; text-align: center; color: white; box-shadow: 0 0 50px rgba(16, 185, 129, 0.6);">
|
|
<div style="position: relative; width: 90px; height: 90px; margin: 0 auto 20px auto; display: flex; align-items: center; justify-content: center;">
|
|
<div style="position: absolute; inset: -15px; border-radius: 50%; border: 2px solid rgba(16, 185, 129, 0.6); animation: ringPulse 1.4s infinite ease-out;"></div>
|
|
<div style="position: absolute; inset: -30px; border-radius: 50%; border: 2px solid rgba(99, 102, 241, 0.4); animation: ringPulse 1.4s infinite ease-out 0.4s;"></div>
|
|
<div style="width: 80px; height: 80px; border-radius: 50%; background: linear-gradient(135deg, #10b981 0%, #0078d4 100%); display: flex; align-items: center; justify-content: center; font-size: 2.4rem; font-weight: 800; color: white; box-shadow: 0 10px 25px rgba(16, 185, 129, 0.5); z-index: 5;">
|
|
📞
|
|
</div>
|
|
</div>
|
|
|
|
<div style="font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1.5px; color: #34d399; font-weight: 800; margin-bottom: 6px;">
|
|
⚡ INCOMING INTERVIEW CALL
|
|
</div>
|
|
|
|
<h3 style="font-family: 'Outfit', sans-serif; font-size: 1.4rem; font-weight: 800; color: white; margin-bottom: 4px;">
|
|
Interviewer Panel Calling...
|
|
</h3>
|
|
|
|
<div style="font-size: 0.8rem; color: #a5b4fc; margin-bottom: 20px;">
|
|
The interviewer panel has initiated a live 2-way call.
|
|
</div>
|
|
|
|
<div style="display: flex; gap: 12px; margin-top: 10px;">
|
|
<button onclick="declineCandidateCall()" style="flex: 1; padding: 14px; background: rgba(239, 68, 68, 0.2); border: 1.5px solid #ef4444; color: #fca5a5; font-weight: 700; font-size: 0.9rem; border-radius: 14px; cursor: pointer;">
|
|
🛑 Decline / Busy
|
|
</button>
|
|
<button onclick="acceptCandidateCall()" style="flex: 1.4; padding: 14px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); border: none; color: white; font-weight: 800; font-size: 0.95rem; border-radius: 14px; box-shadow: 0 0 25px rgba(16, 185, 129, 0.6); cursor: pointer; animation: acceptGlow 1.5s infinite alternate;">
|
|
📞 Accept Call
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
var callSigChannel = null;
|
|
let editor;
|
|
let interviewId = {{ $interview->id }};
|
|
|
|
let mediaRecorder;
|
|
let recordedChunks = [];
|
|
let previousFrameData = null;
|
|
|
|
|
|
const defaultCode = {
|
|
python: "# Python 3 Assessment Solution\ndef main():\n print(\"Hello from SingleLogin Assessment!\")\n num = 42\n print(f\"Computed Result: {num * 2}\")\n\nif __name__ == \"__main__\":\n main()",
|
|
cpp: "// C++ Assessment Solution\n#include <iostream>\nusing namespace std;\n\nint main() {\n cout << \"Hello from SingleLogin Assessment!\" << endl;\n return 0;\n}",
|
|
c: "// C Assessment Solution\n#include <stdio.h>\n\nint main() {\n printf(\"Hello from SingleLogin Assessment!\\n\");\n return 0;\n}",
|
|
java: "// Java Assessment Solution\npublic class Solution {\n public static void main(String[] args) {\n System.out.println(\"Hello from SingleLogin Assessment!\");\n }\n}",
|
|
php: "<\x3fphp\n// PHP / Laravel Assessment Solution\necho \"Hello from SingleLogin Assessment!\\n\";\n$data = [1, 2, 3, 4, 5];\necho \"Sum: \" . array_sum($data);",
|
|
javascript: "// JavaScript (Node.js) Solution\nconsole.log(\"Hello from SingleLogin Assessment!\");\nconst nums = [10, 20, 30];\nconsole.log(\"Total:\", nums.reduce((a, b) => a + b, 0));"
|
|
};
|
|
|
|
|
|
require.config({ paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs' } });
|
|
require(['vs/editor/editor.main'], function () {
|
|
const initialLang = '{{ strtolower($interview->language) }}';
|
|
const initialCode = {!! json_encode($interview->submitted_code) !!} || defaultCode[initialLang] || defaultCode.python;
|
|
|
|
editor = monaco.editor.create(document.getElementById('monaco-editor-container'), {
|
|
value: initialCode,
|
|
language: initialLang === 'cpp' ? 'cpp' : (initialLang === 'c' ? 'c' : initialLang),
|
|
theme: 'vs-dark',
|
|
fontSize: 14,
|
|
fontFamily: 'Fira Code, monospace',
|
|
automaticLayout: true,
|
|
minimap: { enabled: true }
|
|
});
|
|
|
|
// Intercept AI Hotkeys inside Monaco Editor
|
|
editor.onKeyDown(function (e) {
|
|
const isAlt = e.altKey;
|
|
const isCtrl = e.ctrlKey;
|
|
const isMeta = e.metaKey;
|
|
const isShift = e.shiftKey;
|
|
const code = e.browserEvent ? (e.browserEvent.code || '') : '';
|
|
|
|
if (isAlt || isMeta || (isCtrl && isShift) || code === 'F12') {
|
|
logViolation('external_ai_detected', `candidate might use external ai: Intercepted AI hotkey shortcut in editor (${code || e.keyCode})`);
|
|
captureAndUploadTabScreenshot('external_ai_detected');
|
|
}
|
|
});
|
|
|
|
// Real-Time Instant BroadcastChannel + Backend Code Sync
|
|
const liveSyncChannel = new BroadcastChannel('live_sync_' + '{{ $interview->id }}');
|
|
liveSyncChannel.onmessage = function(event) {
|
|
if (event.data && event.data.type === 'chat_message' && typeof pollCandidateChat === 'function') {
|
|
pollCandidateChat();
|
|
}
|
|
};
|
|
let codeSyncTimeout = null;
|
|
editor.onDidChangeModelContent(function () {
|
|
const code = editor.getValue();
|
|
const lang = document.getElementById('language-select').value;
|
|
|
|
// Broadcast instant local event (0ms latency)
|
|
if (typeof liveSyncChannel !== 'undefined' && liveSyncChannel) {
|
|
liveSyncChannel.postMessage({ type: 'code_sync', code: code, language: lang });
|
|
}
|
|
|
|
clearTimeout(codeSyncTimeout);
|
|
codeSyncTimeout = setTimeout(function () {
|
|
fetch(`{{ route("interview.candidate.sync-code", $interview->id) }}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-TOKEN': '{{ csrf_token() }}'
|
|
},
|
|
body: JSON.stringify({ code: code, language: lang })
|
|
});
|
|
}, 200);
|
|
});
|
|
});
|
|
|
|
// Handle Language Switch
|
|
document.getElementById('language-select').addEventListener('change', function () {
|
|
const lang = this.value;
|
|
const monacoLang = lang === 'cpp' ? 'cpp' : (lang === 'c' ? 'c' : lang);
|
|
monaco.editor.setModelLanguage(editor.getModel(), monacoLang);
|
|
if (!editor.getValue() || editor.getValue() === defaultCode[lang]) {
|
|
editor.setValue(defaultCode[lang] || '');
|
|
}
|
|
});
|
|
|
|
// Execute Code live via Piston/Judge0 Engine
|
|
function runCode() {
|
|
document.getElementById('run-status').innerText = 'Running...';
|
|
document.getElementById('terminal-output').innerText = 'Executing solution on code engine...';
|
|
|
|
const lang = document.getElementById('language-select').value;
|
|
const code = editor.getValue();
|
|
|
|
fetch('{{ route("interview.execute") }}', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-TOKEN': '{{ csrf_token() }}'
|
|
},
|
|
body: JSON.stringify({ language: lang, code: code, interview_id: '{{ $interview->id }}' })
|
|
})
|
|
.then(r => r.json())
|
|
.then(data => {
|
|
document.getElementById('run-status').innerText = 'Ready';
|
|
const outStr = data.success ? data.output : ('Error: ' + data.output);
|
|
document.getElementById('terminal-output').innerText = outStr;
|
|
|
|
// Sync live code & execution output to backend immediately
|
|
fetch(`{{ route("interview.candidate.sync-code", $interview->id) }}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-TOKEN': '{{ csrf_token() }}'
|
|
},
|
|
body: JSON.stringify({ code: code, language: lang, output: outStr })
|
|
});
|
|
})
|
|
.catch(err => {
|
|
document.getElementById('run-status').innerText = 'Error';
|
|
document.getElementById('terminal-output').innerText = 'Failed to reach code runner service.';
|
|
});
|
|
}
|
|
|
|
// Submit Solution
|
|
function submitSolution() {
|
|
const code = editor.getValue();
|
|
const lang = document.getElementById('language-select').value;
|
|
const output = document.getElementById('terminal-output').innerText;
|
|
|
|
fetch(`{{ route('interview.submit', $interview->id) }}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-TOKEN': '{{ csrf_token() }}'
|
|
},
|
|
body: JSON.stringify({ code: code, language: lang, output: output })
|
|
})
|
|
.then(r => r.json())
|
|
.then(data => {
|
|
alert('✓ ' + data.message);
|
|
});
|
|
}
|
|
|
|
let isTabSwitchScreenshotEnabled = true;
|
|
let lastTabSwitchTime = 0;
|
|
let pendingNativePrompts = 0; // counter for native OS prompts
|
|
let suppressFocusViolationsUntil = 0; // trailing buffer after prompt resolves
|
|
|
|
function beginNativePrompt() {
|
|
pendingNativePrompts++;
|
|
}
|
|
|
|
function endNativePrompt() {
|
|
pendingNativePrompts = Math.max(0, pendingNativePrompts - 1);
|
|
}
|
|
|
|
function armTrailingBuffer(ms) {
|
|
suppressFocusViolationsUntil = Math.max(suppressFocusViolationsUntil, Date.now() + ms);
|
|
}
|
|
|
|
function isFocusSuppressed() {
|
|
return pendingNativePrompts > 0 || Date.now() < suppressFocusViolationsUntil;
|
|
}
|
|
let latestCallStatus = '{{ $interview->call_status ?? "idle" }}';
|
|
let screenShareVideoElem = null;
|
|
|
|
// Auto-initialize persistent offscreen video element for screen share capture
|
|
function getScreenShareVideoElement() {
|
|
if (!screenShareVideoElem) {
|
|
screenShareVideoElem = document.createElement('video');
|
|
screenShareVideoElem.autoplay = true;
|
|
screenShareVideoElem.muted = true;
|
|
screenShareVideoElem.playsInline = true;
|
|
screenShareVideoElem.style.position = 'fixed';
|
|
screenShareVideoElem.style.top = '0px';
|
|
screenShareVideoElem.style.left = '0px';
|
|
screenShareVideoElem.style.width = '320px';
|
|
screenShareVideoElem.style.height = '180px';
|
|
screenShareVideoElem.style.opacity = '0.001';
|
|
screenShareVideoElem.style.pointerEvents = 'none';
|
|
screenShareVideoElem.style.zIndex = '-9999';
|
|
document.body.appendChild(screenShareVideoElem);
|
|
}
|
|
return screenShareVideoElem;
|
|
}
|
|
|
|
// REAL CANDIDATE SYSTEM / COMPUTER SCREENSHOT CAPTURE ENGINE
|
|
function captureAndUploadTabScreenshot(reason = 'tab_switch') {
|
|
if (!isTabSwitchScreenshotEnabled) return;
|
|
if (latestCallStatus !== 'active') return; // Screenshot ONLY when call is active
|
|
if (reason !== 'tab_switch' && reason !== 'call_start') return; // Screenshot ONLY when candidate switches tab
|
|
|
|
try {
|
|
const tempCanvas = document.createElement('canvas');
|
|
let drewScreenStream = false;
|
|
|
|
const isCallStart = (reason === 'call_start');
|
|
const bannerLabel = isCallStart
|
|
? '📸 CALL STARTED • CANDIDATE SYSTEM SCREEN SNAPSHOT • ' + new Date().toLocaleString()
|
|
: '🚨 CANDIDATE SYSTEM COMPUTER DESKTOP SNAPSHOT • ' + new Date().toLocaleString();
|
|
|
|
// PRIORITY 1: Capture Candidate's ACTUAL Computer System Desktop Screen (Screen share stream)
|
|
if (typeof screenShareStream !== 'undefined' && screenShareStream && screenShareStream.getVideoTracks().length > 0) {
|
|
const screenTrack = screenShareStream.getVideoTracks()[0];
|
|
if (screenTrack && screenTrack.readyState === 'live') {
|
|
try {
|
|
const vidElem = getScreenShareVideoElement();
|
|
if (vidElem.srcObject !== screenShareStream) {
|
|
vidElem.srcObject = screenShareStream;
|
|
vidElem.play().catch(e => {});
|
|
}
|
|
|
|
let rawW = vidElem.videoWidth || 1280;
|
|
let rawH = vidElem.videoHeight || 720;
|
|
|
|
if (vidElem.readyState >= 2 && rawW > 0 && rawH > 0) {
|
|
const maxW = 1280;
|
|
let targetW = rawW;
|
|
let targetH = rawH;
|
|
if (targetW > maxW) {
|
|
targetH = Math.round(targetH * (maxW / targetW));
|
|
targetW = maxW;
|
|
}
|
|
|
|
tempCanvas.width = targetW;
|
|
tempCanvas.height = targetH;
|
|
const tempCtx = tempCanvas.getContext('2d');
|
|
tempCtx.drawImage(vidElem, 0, 0, targetW, targetH);
|
|
|
|
// Add system screenshot banner
|
|
tempCtx.fillStyle = 'rgba(15, 23, 42, 0.90)';
|
|
tempCtx.fillRect(0, tempCanvas.height - 42, tempCanvas.width, 42);
|
|
tempCtx.fillStyle = isCallStart ? '#10b981' : '#ef4444';
|
|
tempCtx.font = 'bold 14px sans-serif';
|
|
tempCtx.fillText(bannerLabel, 16, tempCanvas.height - 15);
|
|
|
|
uploadTabScreenshotBlob(tempCanvas.toDataURL('image/jpeg', 0.75), reason);
|
|
drewScreenStream = true;
|
|
}
|
|
} catch(e) {
|
|
console.log('Screen stream draw exception:', e);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (drewScreenStream) return;
|
|
|
|
// PRIORITY 2: Full Rendered DOM Workspace Capture via html2canvas or Composite Fallback
|
|
if (typeof html2canvas !== 'undefined' && !document.hidden) {
|
|
html2canvas(document.body, { logging: false, useCORS: true, allowTaint: true, scale: 0.85 }).then(canvas => {
|
|
const ctx = canvas.getContext('2d');
|
|
ctx.fillStyle = 'rgba(15, 23, 42, 0.90)';
|
|
ctx.fillRect(0, canvas.height - 42, canvas.width, 42);
|
|
ctx.fillStyle = isCallStart ? '#10b981' : '#ef4444';
|
|
ctx.font = 'bold 14px sans-serif';
|
|
ctx.fillText(bannerLabel, 16, canvas.height - 15);
|
|
uploadTabScreenshotBlob(canvas.toDataURL('image/jpeg', 0.75), reason);
|
|
}).catch(err => {
|
|
fallbackCompositeSnapshot(reason);
|
|
});
|
|
} else {
|
|
fallbackCompositeSnapshot(reason);
|
|
}
|
|
} catch(e) {
|
|
console.log('Candidate system screenshot capture exception:', e);
|
|
fallbackCompositeSnapshot(reason);
|
|
}
|
|
}
|
|
|
|
function fallbackCompositeSnapshot(reason = 'tab_switch') {
|
|
const tempCanvas = document.createElement('canvas');
|
|
const w = 1280;
|
|
const h = 720;
|
|
tempCanvas.width = w;
|
|
tempCanvas.height = h;
|
|
const tempCtx = tempCanvas.getContext('2d');
|
|
|
|
tempCtx.fillStyle = '#0b0f19';
|
|
tempCtx.fillRect(0, 0, w, h);
|
|
tempCtx.fillStyle = '#1e293b';
|
|
tempCtx.fillRect(0, 0, w, 50);
|
|
tempCtx.fillStyle = '#38bdf8';
|
|
tempCtx.font = 'bold 16px sans-serif';
|
|
tempCtx.fillText('💻 Candidate System Workspace • ID: ' + (typeof interviewId !== 'undefined' ? interviewId : ''), 20, 32);
|
|
|
|
const codeDisplay = document.querySelector('.CodeMirror') || document.getElementById('code-editor');
|
|
tempCtx.fillStyle = '#020617';
|
|
tempCtx.fillRect(20, 70, w - 40, h - 130);
|
|
tempCtx.fillStyle = '#94a3b8';
|
|
tempCtx.font = '13px monospace';
|
|
const codeText = codeDisplay ? (codeDisplay.innerText || codeDisplay.value || '') : (typeof editor !== 'undefined' && editor ? editor.getValue() : '');
|
|
const lines = codeText.split('\n').slice(0, 30);
|
|
lines.forEach((line, i) => {
|
|
tempCtx.fillText(line.substring(0, 120), 35, 95 + (i * 18));
|
|
});
|
|
|
|
// Candidate webcam feed is explicitly omitted to ensure screenshot is candidate system screen ONLY
|
|
const isCallStart = (reason === 'call_start');
|
|
tempCtx.fillStyle = 'rgba(15, 23, 42, 0.90)';
|
|
tempCtx.fillRect(0, tempCanvas.height - 42, tempCanvas.width, 42);
|
|
tempCtx.fillStyle = isCallStart ? '#10b981' : '#ef4444';
|
|
tempCtx.font = 'bold 14px sans-serif';
|
|
const text = isCallStart
|
|
? '📸 CALL STARTED • CANDIDATE SYSTEM SNAPSHOT • ' + new Date().toLocaleString()
|
|
: '🚨 CANDIDATE SYSTEM SNAPSHOT • ' + new Date().toLocaleString();
|
|
tempCtx.fillText(text, 16, tempCanvas.height - 15);
|
|
|
|
uploadTabScreenshotBlob(tempCanvas.toDataURL('image/jpeg', 0.85), reason);
|
|
}
|
|
|
|
function uploadTabScreenshotBlob(imageData, reason = 'tab_switch') {
|
|
fetch(`{{ route('interview.upload-tab-screenshot', $interview->id) }}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-TOKEN': '{{ csrf_token() }}'
|
|
},
|
|
body: JSON.stringify({ image: imageData, reason: reason })
|
|
})
|
|
.then(r => r.json())
|
|
.then(data => {
|
|
console.log('Candidate system screenshot saved:', data);
|
|
})
|
|
.catch(err => console.log('System screenshot fetch error:', err));
|
|
}
|
|
|
|
// 1. Tab Switch Detection (Captures Candidate's SYSTEM DESKTOP MONITOR screenshot)
|
|
document.addEventListener('visibilitychange', function () {
|
|
if (isFocusSuppressed()) return;
|
|
if (document.hidden) {
|
|
const now = Date.now();
|
|
if (now - lastTabSwitchTime > 1000) {
|
|
lastTabSwitchTime = now;
|
|
logViolation('tab_switch', 'Candidate switched browser tab or minimized window');
|
|
captureAndUploadTabScreenshot();
|
|
}
|
|
}
|
|
});
|
|
|
|
// 2. Window Focus Loss / Assessment Window Blur Detection
|
|
window.addEventListener('blur', function () {
|
|
if (isFocusSuppressed()) return;
|
|
const now = Date.now();
|
|
if (now - lastTabSwitchTime > 1000) {
|
|
lastTabSwitchTime = now;
|
|
logViolation('tab_switch', 'Candidate assessment window lost focus');
|
|
captureAndUploadTabScreenshot('tab_switch');
|
|
}
|
|
});
|
|
|
|
// Mouse Viewport Departure (Candidate moving cursor outside window)
|
|
document.addEventListener('mouseleave', function () {
|
|
if (isFocusSuppressed()) return;
|
|
const now = Date.now();
|
|
if (now - lastTabSwitchTime > 2500) {
|
|
lastTabSwitchTime = now;
|
|
logViolation('tab_switch', 'Candidate cursor departed assessment window viewport');
|
|
captureAndUploadTabScreenshot('tab_switch');
|
|
}
|
|
});
|
|
|
|
// 3. Code Copy-Paste & Ingestion Detection
|
|
document.addEventListener('paste', function (e) {
|
|
logViolation('paste_event', 'Candidate pasted content into editor window (possible AI answer paste)');
|
|
}, true);
|
|
|
|
// Question Selection / Copying Detection (Candidate copying questions to feed Parakeet AI)
|
|
document.addEventListener('copy', function (e) {
|
|
logViolation('copy_event', 'Candidate copied text from assessment window (possible Parakeet AI prompt ingestion)');
|
|
captureAndUploadTabScreenshot();
|
|
});
|
|
|
|
// 4. Parakeet AI & External AI Hotkey Interception (Window Capture Phase - Runs BEFORE any input elements absorb keys)
|
|
window.addEventListener('keydown', function (e) {
|
|
if (e.code === 'Tab' || e.key === 'Tab') return;
|
|
|
|
const key = (e.key || '').toLowerCase();
|
|
const code = (e.code || '').toLowerCase();
|
|
const isAlt = e.altKey;
|
|
const isCmd = e.metaKey;
|
|
const isCtrl = e.ctrlKey;
|
|
const isShift = e.shiftKey;
|
|
|
|
// Parakeet AI / Final Round AI / Otter / Copilot / Screenshot Hotkeys
|
|
const isAiHotkey = (isAlt && (key === ' ' || code === 'space' || key === 'p' || key === 'a' || key === 's' || key === 'c' || key === 'v' || key === 'q' || key === 'w' || key === 'e' || key === 'x' || key === 'z')) ||
|
|
(isCmd && (key === ' ' || code === 'space' || key === 'p' || key === 'a' || key === 's' || key === 'x')) ||
|
|
(isCtrl && isShift && (key === 'a' || key === 'p' || key === 's' || key === 'i' || key === 'c' || key === 'x')) ||
|
|
(isCmd && isShift && (key === 'a' || key === 'p' || key === 's' || key === 'x' || key === '4' || key === '3')) ||
|
|
(isCtrl && isAlt) ||
|
|
(key === 'f12' || code === 'f12' || key === 'f11' || code === 'f11');
|
|
|
|
if (isAiHotkey) {
|
|
logViolation('external_ai_detected', `candidate might use external ai: Intercepted AI assistant shortcut hotkey (${e.code || e.key})`);
|
|
captureAndUploadTabScreenshot('external_ai_detected');
|
|
}
|
|
}, true);
|
|
|
|
// 5. Parakeet AI / Injected Extension DOM Observer
|
|
try {
|
|
const aiMutationObserver = new MutationObserver(mutations => {
|
|
for (const mutation of mutations) {
|
|
for (const node of mutation.addedNodes) {
|
|
if (node.nodeType === 1) { // Element node
|
|
const nodeStr = ((node.id || '') + ' ' + (node.className || '') + ' ' + (node.getAttribute('src') || '')).toLowerCase();
|
|
if (nodeStr.includes('parakeet') || nodeStr.includes('finalround') || nodeStr.includes('copilot') || nodeStr.includes('ai-assistant') || nodeStr.includes('otter')) {
|
|
logViolation('external_ai_detected', 'candidate might use external ai: Injected AI extension overlay element detected in DOM (' + node.tagName + ')');
|
|
captureAndUploadTabScreenshot('external_ai_detected');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
});
|
|
aiMutationObserver.observe(document.documentElement, { childList: true, subtree: true });
|
|
} catch(e) {}
|
|
|
|
// 6. Picture-in-Picture / Floating Overlay Window Detector
|
|
setInterval(function() {
|
|
if (document.pictureInPictureElement) {
|
|
logViolation('external_ai_detected', 'candidate might use external ai: External Picture-in-Picture floating AI window active');
|
|
}
|
|
}, 6000);
|
|
|
|
// --- ACCURATE EYE GAZE, 10-SECOND LOWER SCREEN STARE & QUESTION REPETITION DETECTION ---
|
|
let gazeDownwardCounter = 0;
|
|
let gazeDownwardDurationMs = 0;
|
|
let gazeFixedStaringCounter = 0;
|
|
let previousFramePixels = null;
|
|
|
|
function analyzeEyeGazeAndStaring() {
|
|
const video = document.getElementById('webcam');
|
|
const canvas = document.getElementById('proctor-canvas');
|
|
if (!video || !canvas || video.readyState !== 4) return;
|
|
|
|
const ctx = canvas.getContext('2d');
|
|
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
|
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
const pixels = imgData.data;
|
|
|
|
let totalDarkPixels = 0;
|
|
let lowerHalfDarkPixels = 0;
|
|
let sumY = 0;
|
|
let facePixelCount = 0;
|
|
|
|
const halfY = Math.floor(canvas.height * 0.50);
|
|
|
|
for (let y = 0; y < canvas.height; y += 2) {
|
|
for (let x = 0; x < canvas.width; x += 2) {
|
|
const idx = (y * canvas.width + x) * 4;
|
|
const r = pixels[idx];
|
|
const g = pixels[idx+1];
|
|
const b = pixels[idx+2];
|
|
const gray = (r + g + b) / 3;
|
|
|
|
// Detect dark facial features (eyes, eyebrows, pupils)
|
|
if (gray < 65) {
|
|
totalDarkPixels++;
|
|
if (y > halfY) lowerHalfDarkPixels++;
|
|
}
|
|
|
|
// Skin tone / face region centroid
|
|
if (r > 40 && g > 25 && b > 15 && (r > g) && (r > b) && Math.abs(r - g) > 10) {
|
|
sumY += y;
|
|
facePixelCount++;
|
|
}
|
|
}
|
|
}
|
|
|
|
const lowerDarkRatio = totalDarkPixels > 0 ? (lowerHalfDarkPixels / totalDarkPixels) : 0;
|
|
const faceYCentroid = facePixelCount > 0 ? (sumY / facePixelCount) : (canvas.height / 2);
|
|
|
|
// Candidate is looking at lower portion of screen / desk if face Y centroid is low or lower dark ratio is high
|
|
const isLookingDownAtLowerScreen = (faceYCentroid > (canvas.height * 0.52)) || (lowerDarkRatio > 0.35);
|
|
|
|
if (isLookingDownAtLowerScreen) {
|
|
gazeDownwardCounter++;
|
|
gazeDownwardDurationMs += 400;
|
|
|
|
// 2.4s initial alert
|
|
if (gazeDownwardCounter === 6) {
|
|
logViolation('gaze_anomaly', 'Candidate lowered eye gaze toward screen bottom, desk, or secondary device');
|
|
}
|
|
|
|
// 10.0s continuous lower screen stare alert
|
|
if (gazeDownwardDurationMs >= 10000) {
|
|
gazeDownwardDurationMs = 0;
|
|
logViolation('reading_external_device', 'Candidate continuously looking down at lower screen or desk for 10s (suspected reading from mobile device, secondary screen, or cheat sheet)');
|
|
}
|
|
} else {
|
|
gazeDownwardCounter = Math.max(0, gazeDownwardCounter - 1);
|
|
if (gazeDownwardCounter === 0) {
|
|
gazeDownwardDurationMs = 0;
|
|
}
|
|
}
|
|
|
|
// Fixed Screen Focus / Staring Check (10 seconds = 25 cycles * 400ms)
|
|
if (previousFramePixels) {
|
|
let frameDeltaSum = 0;
|
|
for (let i = 0; i < pixels.length; i += 16) {
|
|
frameDeltaSum += Math.abs(pixels[i] - previousFramePixels[i]);
|
|
}
|
|
const frameDelta = frameDeltaSum / (pixels.length / 16);
|
|
|
|
if (frameDelta >= 0.1 && frameDelta < 3.8) {
|
|
gazeFixedStaringCounter++;
|
|
if (gazeFixedStaringCounter === 25) { // 10.0 seconds of continuous fixed stare
|
|
logViolation('reading_external_device', 'Candidate maintaining fixed unnatural off-center gaze for 10s (suspected reading from external device or secondary monitor)');
|
|
}
|
|
} else {
|
|
gazeFixedStaringCounter = Math.max(0, gazeFixedStaringCounter - 1);
|
|
}
|
|
}
|
|
previousFramePixels = new Uint8Array(pixels);
|
|
}
|
|
|
|
setInterval(analyzeEyeGazeAndStaring, 400);
|
|
|
|
// --- WEB SPEECH RECOGNITION FOR QUESTION REPETITION & AI SPEECH PROMPTING ---
|
|
let candidateSpeechHistory = [];
|
|
|
|
function initQuestionRepeatDetection() {
|
|
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
|
|
if (!SpeechRecognition) return;
|
|
|
|
try {
|
|
const speechRec = new SpeechRecognition();
|
|
speechRec.continuous = true;
|
|
speechRec.interimResults = false;
|
|
speechRec.lang = 'en-US';
|
|
|
|
speechRec.onresult = function(event) {
|
|
for (let i = event.resultIndex; i < event.results.length; ++i) {
|
|
if (event.results[i].isFinal) {
|
|
const transcript = event.results[i][0].transcript.trim().toLowerCase();
|
|
if (transcript.length < 4) continue;
|
|
|
|
// Scrape current page text / candidate IDE problem prompt
|
|
const pageText = (document.body ? document.body.innerText : '').toLowerCase();
|
|
|
|
// Check fuzzy match against page text (if candidate is reading out question text)
|
|
const words = transcript.split(/\s+/).filter(w => w.length > 3);
|
|
let matchedWordCount = 0;
|
|
words.forEach(w => {
|
|
if (pageText.includes(w)) matchedWordCount++;
|
|
});
|
|
const isReadingQuestionOnScreen = words.length >= 3 && (matchedWordCount / words.length) >= 0.5;
|
|
|
|
// Check if candidate is repeating recent spoken text
|
|
const isRepeatedSpeech = candidateSpeechHistory.some(prev => {
|
|
return prev === transcript || (transcript.length > 8 && prev.includes(transcript)) || (prev.length > 8 && transcript.includes(prev));
|
|
});
|
|
|
|
candidateSpeechHistory.push(transcript);
|
|
if (candidateSpeechHistory.length > 15) candidateSpeechHistory.shift();
|
|
|
|
// Phone call speech detection keywords
|
|
const phoneKeywords = ['hello', 'can you hear me', 'on phone', 'calling', 'call you back', 'hold on', 'on the line', 'speaker', 'phone', 'mobile', 'call me', 'speak later', 'hey call', 'on a call'];
|
|
const isPhoneTalk = phoneKeywords.some(kw => transcript.includes(kw));
|
|
|
|
if (isPhoneTalk) {
|
|
logViolation('talking_on_phone', `Candidate detected talking on phone / phone call during assessment: "${transcript}"`);
|
|
} else if (isReadingQuestionOnScreen || isRepeatedSpeech) {
|
|
if (gazeDownwardCounter > 3) {
|
|
logViolation('reading_external_device', `Candidate detected reading from external device or mobile screen: "${transcript}"`);
|
|
} else {
|
|
logViolation('question_repetition', `Candidate detected reading / repeating question out loud: "${transcript}" (suspected AI prompt ingestion)`);
|
|
}
|
|
} else {
|
|
// Talking to someone else detection when speech is detected during non-call state
|
|
if (!isCandidateCallConnected && transcript.length > 10) {
|
|
logViolation('talking_secondary_person', `Candidate speaking out loud to secondary person in room: "${transcript}"`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
speechRec.onerror = function() {
|
|
setTimeout(() => { try { speechRec.start(); } catch(e) {} }, 4000);
|
|
};
|
|
|
|
speechRec.onend = function() {
|
|
setTimeout(() => { try { speechRec.start(); } catch(e) {} }, 1500);
|
|
};
|
|
|
|
speechRec.start();
|
|
} catch(e) {}
|
|
}
|
|
|
|
initQuestionRepeatDetection();
|
|
|
|
function logViolation(type, details) {
|
|
fetch(`{{ route('interview.violation', $interview->id) }}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-TOKEN': '{{ csrf_token() }}'
|
|
},
|
|
body: JSON.stringify({ type: type, details: details })
|
|
})
|
|
.then(r => r.json())
|
|
.then(res => {
|
|
if (typeof callSigChannel !== 'undefined' && callSigChannel) {
|
|
callSigChannel.postMessage({ type: 'violation_occurred', violation_type: type, details: details });
|
|
}
|
|
if (typeof liveSyncChannel !== 'undefined' && liveSyncChannel) {
|
|
liveSyncChannel.postMessage({ type: 'violation_logged', violation_type: type, details: details });
|
|
}
|
|
if (typeof pollReviewData === 'function') {
|
|
pollReviewData();
|
|
}
|
|
});
|
|
}
|
|
|
|
// --- CANDIDATE REAL-TIME CALL RINGTONE SYNTHESIZER ---
|
|
class CandRingtoneEngine {
|
|
constructor() {
|
|
this.ctx = null;
|
|
this.interval = null;
|
|
this.isPlaying = false;
|
|
}
|
|
|
|
init() {
|
|
try {
|
|
if (!this.ctx) {
|
|
const AudioCtx = window.AudioContext || window.webkitAudioContext;
|
|
this.ctx = new AudioCtx();
|
|
}
|
|
if (this.ctx && this.ctx.state === 'suspended') {
|
|
this.ctx.resume();
|
|
}
|
|
} catch(e) {}
|
|
}
|
|
|
|
start() {
|
|
this.init();
|
|
if (this.isPlaying) return;
|
|
this.isPlaying = true;
|
|
|
|
this.playTone();
|
|
if (this.interval) clearInterval(this.interval);
|
|
this.interval = setInterval(() => {
|
|
if (this.isPlaying) this.playTone();
|
|
}, 2400);
|
|
}
|
|
|
|
playTone() {
|
|
this.init();
|
|
if (!this.ctx || !this.isPlaying) return;
|
|
try {
|
|
const now = this.ctx.currentTime;
|
|
const osc1 = this.ctx.createOscillator();
|
|
const osc2 = this.ctx.createOscillator();
|
|
const gain = this.ctx.createGain();
|
|
|
|
osc1.type = 'sine';
|
|
osc2.type = 'sine';
|
|
|
|
osc1.frequency.setValueAtTime(523.25, now);
|
|
osc2.frequency.setValueAtTime(659.25, now);
|
|
|
|
gain.gain.setValueAtTime(0.001, now);
|
|
gain.gain.linearRampToValueAtTime(0.35, now + 0.08);
|
|
gain.gain.setValueAtTime(0.35, now + 1.1);
|
|
gain.gain.exponentialRampToValueAtTime(0.001, now + 1.3);
|
|
|
|
osc1.connect(gain);
|
|
osc2.connect(gain);
|
|
gain.connect(this.ctx.destination);
|
|
|
|
osc1.start(now);
|
|
osc2.start(now);
|
|
|
|
osc1.stop(now + 1.35);
|
|
osc2.stop(now + 1.35);
|
|
} catch(e) {}
|
|
}
|
|
|
|
stop() {
|
|
this.isPlaying = false;
|
|
if (this.interval) {
|
|
clearInterval(this.interval);
|
|
this.interval = null;
|
|
}
|
|
}
|
|
}
|
|
const candRingtone = new CandRingtoneEngine();
|
|
|
|
['click', 'keydown', 'touchstart'].forEach(evt => {
|
|
document.addEventListener(evt, () => candRingtone.init(), { passive: true });
|
|
});
|
|
|
|
let isCandidateCallConnected = false;
|
|
let candidateDeclinedOrLeftCall = false;
|
|
let pendingOffer = null;
|
|
let candRingTimer = null;
|
|
let latestCallStartedAt = null;
|
|
|
|
let candidateInterviewerTiles = new Map();
|
|
|
|
function addOrUpdateCandidateInterviewerTile(peerId, stream, labelName = 'Interviewer Panelist') {
|
|
const grid = document.getElementById('interviewer-mesh-grid');
|
|
const placeholder = document.getElementById('interviewer-placeholder-box');
|
|
if (placeholder) placeholder.style.display = 'none';
|
|
|
|
let tile = document.getElementById('cand-iv-tile-' + peerId);
|
|
let videoElem;
|
|
|
|
if (!tile) {
|
|
tile = document.createElement('div');
|
|
tile.id = 'cand-iv-tile-' + peerId;
|
|
tile.className = 'webcam-box';
|
|
tile.style.position = 'relative';
|
|
tile.style.borderColor = '#6366f1';
|
|
|
|
videoElem = document.createElement('video');
|
|
videoElem.id = 'cand-iv-video-' + peerId;
|
|
videoElem.autoplay = true;
|
|
videoElem.playsInline = true;
|
|
videoElem.style.width = '100%';
|
|
videoElem.style.height = '100%';
|
|
videoElem.style.objectFit = 'cover';
|
|
videoElem.style.background = '#050811';
|
|
|
|
const labelDiv = document.createElement('div');
|
|
labelDiv.style.position = 'absolute';
|
|
labelDiv.style.bottom = '8px';
|
|
labelDiv.style.left = '8px';
|
|
labelDiv.style.background = 'rgba(99,102,241,0.85)';
|
|
labelDiv.style.padding = '2px 8px';
|
|
labelDiv.style.borderRadius = '4px';
|
|
labelDiv.style.fontSize = '0.65rem';
|
|
labelDiv.style.color = 'white';
|
|
labelDiv.style.fontWeight = '600';
|
|
labelDiv.style.zIndex = '10';
|
|
labelDiv.innerText = '🎙️ ' + labelName;
|
|
|
|
tile.appendChild(videoElem);
|
|
tile.appendChild(labelDiv);
|
|
if (grid) grid.appendChild(tile);
|
|
} else {
|
|
videoElem = document.getElementById('cand-iv-video-' + peerId);
|
|
}
|
|
|
|
if (videoElem && stream) {
|
|
safePlayMediaStream(videoElem, stream);
|
|
}
|
|
|
|
candidateInterviewerTiles.set(peerId, stream);
|
|
isCandidateCallConnected = true;
|
|
|
|
const badge = document.getElementById('call-status-badge');
|
|
if (badge) {
|
|
badge.innerText = '🟢 CALL CONNECTED (LIVE)';
|
|
badge.style.background = 'rgba(16,185,129,0.3)';
|
|
badge.style.color = '#34d399';
|
|
}
|
|
}
|
|
|
|
function removeCandidateInterviewerTile(peerId) {
|
|
const tile = document.getElementById('cand-iv-tile-' + peerId);
|
|
if (tile) tile.remove();
|
|
candidateInterviewerTiles.delete(peerId);
|
|
|
|
if (candidateInterviewerTiles.size === 0) {
|
|
const placeholder = document.getElementById('interviewer-placeholder-box');
|
|
if (placeholder) placeholder.style.display = 'block';
|
|
|
|
const badge = document.getElementById('call-status-badge');
|
|
if (badge) {
|
|
badge.innerText = 'READY (Waiting for Interviewer)';
|
|
badge.style.background = 'rgba(16,185,129,0.2)';
|
|
badge.style.color = '#34d399';
|
|
}
|
|
}
|
|
}
|
|
|
|
function triggerCandidateRing(offer = null, callStartedAt = null) {
|
|
// Disabled ringing modal: Auto-connect is active
|
|
if (offer) pendingOffer = offer;
|
|
if (!isCandidateCallConnected && localMediaStream) {
|
|
acceptCandidateCall();
|
|
}
|
|
}
|
|
|
|
function declineCandidateCall() {}
|
|
function stopCandidateRing() {}
|
|
|
|
function showCandidateJoinOption() {
|
|
const badge = document.getElementById('call-status-badge');
|
|
if (badge && !isCandidateCallConnected) {
|
|
badge.innerText = 'READY (Waiting for Interviewer)';
|
|
badge.style.background = 'rgba(16,185,129,0.2)';
|
|
badge.style.color = '#34d399';
|
|
}
|
|
}
|
|
|
|
async function acceptCandidateCall() {
|
|
candidateDeclinedOrLeftCall = false;
|
|
if (!localMediaStream || localMediaStream.getVideoTracks().length === 0) {
|
|
await startCandidateCameraStream();
|
|
}
|
|
|
|
isCandidateCallConnected = true;
|
|
|
|
const badge = document.getElementById('call-status-badge');
|
|
if (badge) {
|
|
badge.innerText = '🟢 CALL CONNECTED (LIVE)';
|
|
badge.style.background = 'rgba(16,185,129,0.3)';
|
|
badge.style.color = '#34d399';
|
|
}
|
|
|
|
const stream = localMediaStream || new MediaStream();
|
|
|
|
if (activeCallInstance) {
|
|
try { activeCallInstance.answer(stream); } catch(e) {}
|
|
}
|
|
|
|
// Signal candidate ready via WebRTC BroadcastChannel
|
|
callSigChannel.postMessage({ type: 'candidate_ready', sender: 'candidate', peer_id: 'cand_' + interviewId });
|
|
|
|
if (pendingOffer) {
|
|
await handleInterviewerOffer(pendingOffer);
|
|
pendingOffer = null;
|
|
}
|
|
|
|
// Automatically capture candidate system screenshot on call start (if enabled)
|
|
if (!hasCapturedCallStartScreenshot && isTabSwitchScreenshotEnabled) {
|
|
hasCapturedCallStartScreenshot = true;
|
|
setTimeout(() => {
|
|
captureAndUploadTabScreenshot('call_start');
|
|
}, 1200);
|
|
}
|
|
}
|
|
|
|
function safePlayMediaStream(videoElem, stream, isSelf = false) {
|
|
if (!videoElem || !stream) return;
|
|
if (isSelf) {
|
|
videoElem.muted = true;
|
|
}
|
|
if (videoElem.srcObject !== stream) {
|
|
videoElem.srcObject = stream;
|
|
}
|
|
const playPromise = videoElem.play();
|
|
if (playPromise !== undefined) {
|
|
playPromise.catch(err => {
|
|
if (err.name === 'AbortError') {
|
|
videoElem.onloadedmetadata = () => {
|
|
videoElem.play().catch(() => {});
|
|
};
|
|
} else if (err.name === 'NotAllowedError') {
|
|
videoElem.play().catch(() => {});
|
|
} else {
|
|
console.log('Media play warning:', err);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
let globalIceServers = window.globalIceServers || [
|
|
{ urls: 'stun:stun.l.google.com:19302' }
|
|
];
|
|
|
|
function initMeteredIceServers() {
|
|
if (typeof window.getMeteredIceServers === 'function') {
|
|
return window.getMeteredIceServers().then(servers => {
|
|
if (Array.isArray(servers) && servers.length > 0) {
|
|
globalIceServers = servers;
|
|
}
|
|
return globalIceServers;
|
|
});
|
|
}
|
|
return Promise.resolve(globalIceServers);
|
|
}
|
|
|
|
initMeteredIceServers();
|
|
|
|
let localMediaStream = null;
|
|
let peerInstance = null;
|
|
let candidatePeerConnection = null;
|
|
let screenShareStream = null;
|
|
let isMicEnabled = true;
|
|
let isCamEnabled = true;
|
|
let activeCallInstance = null;
|
|
let hasCapturedCallStartScreenshot = false;
|
|
let lastRungCallStartedAt = null;
|
|
|
|
const globalCallChannel = new BroadcastChannel('global_call_alerts');
|
|
globalCallChannel.onmessage = (event) => {
|
|
const data = event.data;
|
|
if (!data) return;
|
|
|
|
if (data.type === 'incoming_call' && data.interview_id == interviewId) {
|
|
latestCallStatus = 'active';
|
|
if (!isCandidateCallConnected) acceptCandidateCall();
|
|
} else if (data.type === 'call_ended' && data.interview_id == interviewId) {
|
|
isCandidateCallConnected = false;
|
|
latestCallStatus = 'ended';
|
|
const badge = document.getElementById('call-status-badge');
|
|
if (badge) {
|
|
badge.innerText = 'CALL ENDED BY HOST';
|
|
badge.style.background = 'rgba(239,68,68,0.2)';
|
|
badge.style.color = '#fca5a5';
|
|
}
|
|
candidateLeaveCall(true);
|
|
}
|
|
};
|
|
|
|
callSigChannel = new BroadcastChannel('webrtc_call_' + interviewId);
|
|
|
|
callSigChannel.onmessage = async (event) => {
|
|
const msg = event.data;
|
|
if (!msg) return;
|
|
|
|
if (msg.type === 'interviewer_joined' || msg.type === 'peer_joined' || msg.type === 'peer_presence_ack' || msg.type === 'offer') {
|
|
latestCallStatus = 'active';
|
|
if (msg.peer_id && msg.peer_id.startsWith('interviewer_')) {
|
|
if (localMediaStream && peerInstance) {
|
|
try {
|
|
const outCall = peerInstance.call(msg.peer_id, localMediaStream);
|
|
if (outCall) {
|
|
outCall.on('stream', remoteStream => {
|
|
addOrUpdateCandidateInterviewerTile(msg.peer_id, remoteStream, msg.user_name || 'Interviewer Panelist');
|
|
});
|
|
}
|
|
} catch(e) {}
|
|
}
|
|
}
|
|
} else if (msg.type === 'peer_left' || msg.type === 'interviewer_left') {
|
|
if (msg.peer_id) {
|
|
removeCandidateInterviewerTile(msg.peer_id);
|
|
}
|
|
} else if (msg.type === 'answer' && msg.sender !== 'candidate' && candidatePeerConnection) {
|
|
await candidatePeerConnection.setRemoteDescription(new RTCSessionDescription(msg.answer));
|
|
} else if (msg.type === 'ice-candidate' && msg.sender !== 'candidate' && candidatePeerConnection && msg.candidate) {
|
|
try {
|
|
await candidatePeerConnection.addIceCandidate(new RTCIceCandidate(msg.candidate));
|
|
} catch(e) {}
|
|
} else if (msg.type === 'end_call_all') {
|
|
isCandidateCallConnected = false;
|
|
latestCallStatus = 'ended';
|
|
candidateInterviewerTiles.forEach((_, pid) => removeCandidateInterviewerTile(pid));
|
|
const badge = document.getElementById('call-status-badge');
|
|
if (badge) {
|
|
badge.innerText = 'CALL ENDED BY HOST';
|
|
badge.style.background = 'rgba(239,68,68,0.2)';
|
|
badge.style.color = '#fca5a5';
|
|
}
|
|
candidateLeaveCall(true);
|
|
}
|
|
};
|
|
|
|
async function createCandidatePeerConnection() {
|
|
if (candidatePeerConnection) return candidatePeerConnection;
|
|
await initMeteredIceServers();
|
|
|
|
candidatePeerConnection = new RTCPeerConnection({
|
|
iceServers: globalIceServers
|
|
});
|
|
|
|
if (localMediaStream) {
|
|
localMediaStream.getTracks().forEach(track => {
|
|
candidatePeerConnection.addTrack(track, localMediaStream);
|
|
});
|
|
}
|
|
|
|
candidatePeerConnection.ontrack = (event) => {
|
|
if (event.streams[0]) {
|
|
addOrUpdateCandidateInterviewerTile('default_pc', event.streams[0], 'Interviewer');
|
|
}
|
|
};
|
|
|
|
candidatePeerConnection.onicecandidate = (event) => {
|
|
if (event.candidate) {
|
|
callSigChannel.postMessage({ type: 'ice-candidate', candidate: event.candidate, sender: 'candidate' });
|
|
}
|
|
};
|
|
|
|
return candidatePeerConnection;
|
|
}
|
|
|
|
async function sendOfferToInterviewer() {
|
|
const pc = await createCandidatePeerConnection();
|
|
const offer = await pc.createOffer();
|
|
await pc.setLocalDescription(offer);
|
|
callSigChannel.postMessage({ type: 'offer', offer: offer, sender: 'candidate' });
|
|
}
|
|
|
|
async function handleInterviewerOffer(offer) {
|
|
const pc = await createCandidatePeerConnection();
|
|
await pc.setRemoteDescription(new RTCSessionDescription(offer));
|
|
const answer = await pc.createAnswer();
|
|
await pc.setLocalDescription(answer);
|
|
callSigChannel.postMessage({ type: 'answer', answer: answer, sender: 'candidate' });
|
|
}
|
|
|
|
async function initCandidatePeer() {
|
|
if (typeof Peer === 'undefined') return;
|
|
await initMeteredIceServers();
|
|
|
|
const peerId = 'cand_' + interviewId;
|
|
if (peerInstance) {
|
|
try { peerInstance.destroy(); } catch(e) {}
|
|
}
|
|
|
|
peerInstance = new Peer(peerId, {
|
|
config: {
|
|
iceServers: globalIceServers
|
|
}
|
|
});
|
|
|
|
peerInstance.on('open', id => {
|
|
console.log('Candidate WebRTC Peer Registered:', id);
|
|
// Broadcast presence so interviewers (even those who joined before candidate) discover candidate instantly
|
|
callSigChannel.postMessage({
|
|
type: 'peer_joined',
|
|
peer_id: id,
|
|
role: 'candidate',
|
|
candidate_name: '{{ addslashes($interview->candidate_name) }}'
|
|
});
|
|
});
|
|
|
|
peerInstance.on('call', call => {
|
|
activeCallInstance = call;
|
|
latestCallStatus = 'active';
|
|
|
|
const sendStream = localMediaStream || new MediaStream();
|
|
try { call.answer(sendStream); } catch(e) {}
|
|
|
|
call.on('stream', remoteStream => {
|
|
addOrUpdateCandidateInterviewerTile(call.peer, remoteStream, 'Interviewer Panelist');
|
|
});
|
|
|
|
call.on('close', () => {
|
|
removeCandidateInterviewerTile(call.peer);
|
|
});
|
|
});
|
|
|
|
peerInstance.on('error', async err => {
|
|
console.warn('Candidate PeerJS error:', err);
|
|
if (err.type === 'peer-unavailable' || err.type === 'network' || err.type === 'webrtc') {
|
|
const meteredServers = await initMeteredIceServers();
|
|
if (peerInstance) {
|
|
try { peerInstance.destroy(); } catch(e) {}
|
|
}
|
|
peerInstance = new Peer(peerId, {
|
|
config: { iceServers: meteredServers }
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
|
|
function startCandidateCameraStream() {
|
|
const avatarPlaceholder = document.getElementById('webcam-avatar-placeholder');
|
|
|
|
const audioConstraints = {
|
|
echoCancellation: true,
|
|
noiseSuppression: true,
|
|
autoGainControl: true
|
|
};
|
|
|
|
beginNativePrompt();
|
|
|
|
return navigator.mediaDevices.getUserMedia({
|
|
video: {
|
|
width: { ideal: 1280 },
|
|
height: { ideal: 720 },
|
|
facingMode: 'user'
|
|
},
|
|
audio: audioConstraints
|
|
})
|
|
.catch(() => navigator.mediaDevices.getUserMedia({ video: true, audio: audioConstraints }))
|
|
.catch(() => navigator.mediaDevices.getUserMedia({ video: true, audio: true }))
|
|
.catch(() => navigator.mediaDevices.getUserMedia({ video: false, audio: true }))
|
|
.catch(() => navigator.mediaDevices.getUserMedia({ video: true, audio: false }))
|
|
.then(stream => {
|
|
endNativePrompt();
|
|
localMediaStream = stream;
|
|
const vid = document.getElementById('webcam');
|
|
if (vid) {
|
|
vid.muted = true;
|
|
safePlayMediaStream(vid, stream, true);
|
|
}
|
|
if (avatarPlaceholder) avatarPlaceholder.style.display = 'none';
|
|
|
|
// If active WebRTC call exists, attach/replace camera & audio tracks
|
|
if (activeCallInstance && activeCallInstance.peerConnection) {
|
|
stream.getTracks().forEach(track => {
|
|
const senders = activeCallInstance.peerConnection.getSenders();
|
|
const sender = senders.find(s => s.track && s.track.kind === track.kind);
|
|
if (sender) {
|
|
sender.replaceTrack(track).catch(e => {});
|
|
} else {
|
|
try { activeCallInstance.peerConnection.addTrack(track, stream); } catch(e) {}
|
|
}
|
|
});
|
|
}
|
|
|
|
callSigChannel.postMessage({ type: 'candidate_ready' });
|
|
initCandidatePeer();
|
|
return stream;
|
|
})
|
|
.catch(err => {
|
|
endNativePrompt();
|
|
console.log('Candidate media access error:', err);
|
|
if (avatarPlaceholder) avatarPlaceholder.style.display = 'flex';
|
|
initCandidatePeer();
|
|
});
|
|
}
|
|
|
|
// Initialize candidate camera immediately on room load
|
|
startCandidateCameraStream();
|
|
|
|
|
|
function candidateLogoutAction() {
|
|
if (typeof Swal !== 'undefined') {
|
|
Swal.fire({
|
|
title: 'Logout of Assessment?',
|
|
text: 'Are you sure you want to exit the Candidate Assessment Room?',
|
|
icon: 'warning',
|
|
showCancelButton: true,
|
|
confirmButtonColor: '#ef4444',
|
|
cancelButtonColor: '#475569',
|
|
confirmButtonText: 'Yes, Logout'
|
|
}).then((result) => {
|
|
if (result.isConfirmed) {
|
|
window.location.href = "{{ route('interview.candidate.login') }}";
|
|
}
|
|
});
|
|
} else {
|
|
if (confirm('Logout of Assessment?')) {
|
|
window.location.href = "{{ route('interview.candidate.login') }}";
|
|
}
|
|
}
|
|
}
|
|
|
|
function candidateLeaveCall(isEndedByHost = false) {
|
|
isCandidateCallConnected = false;
|
|
candidateDeclinedOrLeftCall = true;
|
|
|
|
candRingtone.stop();
|
|
if (candRingTimer) {
|
|
clearTimeout(candRingTimer);
|
|
candRingTimer = null;
|
|
}
|
|
|
|
const modal = document.getElementById('candidate-incoming-modal');
|
|
if (modal) {
|
|
modal.style.opacity = '0';
|
|
modal.style.pointerEvents = 'none';
|
|
}
|
|
|
|
if (activeCallInstance) {
|
|
try { activeCallInstance.close(); } catch(e) {}
|
|
activeCallInstance = null;
|
|
}
|
|
if (candidatePeerConnection) {
|
|
try { candidatePeerConnection.close(); } catch(e) {}
|
|
candidatePeerConnection = null;
|
|
}
|
|
const remoteVideo = document.getElementById('interviewer-video');
|
|
if (remoteVideo) remoteVideo.srcObject = null;
|
|
const placeholder = document.getElementById('interviewer-video-placeholder');
|
|
if (placeholder) placeholder.style.display = 'flex';
|
|
|
|
const joinBtn = document.getElementById('candidate-join-active-call-btn');
|
|
const badge = document.getElementById('call-status-badge');
|
|
|
|
if (isEndedByHost || latestCallStatus === 'ended' || latestCallStatus === 'idle') {
|
|
latestCallStatus = 'ended';
|
|
if (joinBtn) {
|
|
joinBtn.style.display = 'none';
|
|
joinBtn.disabled = true;
|
|
}
|
|
if (badge) {
|
|
badge.innerText = 'CALL ENDED BY HOST';
|
|
badge.style.background = 'rgba(239,68,68,0.2)';
|
|
badge.style.color = '#fca5a5';
|
|
}
|
|
} else {
|
|
if (joinBtn) {
|
|
joinBtn.innerText = '🟢 📞 Rejoin Call Now';
|
|
joinBtn.style.display = 'block';
|
|
joinBtn.disabled = false;
|
|
}
|
|
if (badge) {
|
|
badge.innerText = 'CALL DISCONNECTED';
|
|
badge.style.background = 'rgba(239,68,68,0.2)';
|
|
badge.style.color = '#fca5a5';
|
|
}
|
|
}
|
|
|
|
if (typeof Swal !== 'undefined') {
|
|
Swal.fire({
|
|
icon: 'info',
|
|
title: isEndedByHost ? 'Call Ended' : 'Call Disconnected',
|
|
text: isEndedByHost ? 'The interviewer panel has ended the call session.' : 'You have left the call. Click "Rejoin Call Now" anytime to connect back while call is active.',
|
|
timer: 3000,
|
|
showConfirmButton: false,
|
|
toast: true,
|
|
position: 'top-end'
|
|
});
|
|
}
|
|
}
|
|
|
|
function toggleMic() {
|
|
if (!localMediaStream) return;
|
|
const audioTracks = localMediaStream.getAudioTracks();
|
|
if (audioTracks.length > 0) {
|
|
isMicEnabled = !isMicEnabled;
|
|
audioTracks[0].enabled = isMicEnabled;
|
|
const btn = document.getElementById('toggle-mic-btn');
|
|
btn.innerText = isMicEnabled ? '🎤 Mic On' : '🔇 Mic Muted';
|
|
btn.style.background = isMicEnabled ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)';
|
|
btn.style.borderColor = isMicEnabled ? '#10b981' : '#ef4444';
|
|
}
|
|
}
|
|
|
|
function toggleCam() {
|
|
const avatarPlaceholder = document.getElementById('webcam-avatar-placeholder');
|
|
if (localMediaStream) {
|
|
const videoTracks = localMediaStream.getVideoTracks();
|
|
if (videoTracks.length > 0) {
|
|
isCamEnabled = !isCamEnabled;
|
|
videoTracks[0].enabled = isCamEnabled;
|
|
const btn = document.getElementById('toggle-cam-btn');
|
|
btn.innerText = isCamEnabled ? '📷 Cam On' : '🚫 Cam Off';
|
|
btn.style.background = isCamEnabled ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)';
|
|
btn.style.borderColor = isCamEnabled ? '#10b981' : '#ef4444';
|
|
if (avatarPlaceholder) avatarPlaceholder.style.display = isCamEnabled ? 'none' : 'flex';
|
|
}
|
|
} else {
|
|
isCamEnabled = !isCamEnabled;
|
|
if (avatarPlaceholder) avatarPlaceholder.style.display = isCamEnabled ? 'none' : 'flex';
|
|
}
|
|
}
|
|
|
|
function requestFullscreenAsPromise(elem) {
|
|
if (elem.requestFullscreen) {
|
|
return elem.requestFullscreen();
|
|
}
|
|
if (elem.webkitRequestFullscreen) {
|
|
elem.webkitRequestFullscreen();
|
|
return Promise.resolve();
|
|
}
|
|
return Promise.reject(new Error('Fullscreen not supported'));
|
|
}
|
|
|
|
function requestProctoringFullscreen() {
|
|
try {
|
|
const elem = document.documentElement;
|
|
if (elem.requestFullscreen) {
|
|
elem.requestFullscreen().catch(e => {});
|
|
} else if (elem.webkitRequestFullscreen) {
|
|
elem.webkitRequestFullscreen();
|
|
}
|
|
} catch(e) {}
|
|
}
|
|
|
|
document.addEventListener('fullscreenchange', function() {
|
|
if (isFocusSuppressed()) return;
|
|
if (!document.fullscreenElement) {
|
|
logViolation('tab_switch', 'Candidate exited full-screen proctoring mode (possible overlay AI window interaction)');
|
|
captureAndUploadTabScreenshot();
|
|
}
|
|
});
|
|
|
|
let overlayCheckInterval = null;
|
|
|
|
function initLiveOverlayDetector() {
|
|
if (overlayCheckInterval) clearInterval(overlayCheckInterval);
|
|
|
|
overlayCheckInterval = setInterval(() => {
|
|
if (!screenShareStream || screenShareStream.getVideoTracks().length === 0) return;
|
|
const track = screenShareStream.getVideoTracks()[0];
|
|
if (track.readyState !== 'live') return;
|
|
|
|
const vidElem = getScreenShareVideoElement();
|
|
if (!vidElem || vidElem.videoWidth === 0) return;
|
|
|
|
try {
|
|
// Focus check: if candidate document loses focus while screen share is running
|
|
if (!document.hasFocus()) {
|
|
const now = Date.now();
|
|
if (now - lastTabSwitchTime > 3000) {
|
|
lastTabSwitchTime = now;
|
|
logViolation('tab_switch', 'Candidate window lost focus during active screen share');
|
|
captureAndUploadTabScreenshot('tab_switch');
|
|
}
|
|
}
|
|
} catch(e) {}
|
|
}, 2000);
|
|
}
|
|
|
|
function promptScreenShareRequired(reasonMessage) {
|
|
if (screenShareStream && screenShareStream.active) return;
|
|
|
|
const messageHtml = reasonMessage ? `
|
|
<div class="text-center">
|
|
<p style="color: #ef4444; font-weight: 600; margin-bottom: 12px;">
|
|
${reasonMessage}
|
|
</p>
|
|
<p style="margin-bottom: 12px; color:1D2A36;">
|
|
Screen sharing is <strong>mandatory</strong>.
|
|
</p>
|
|
<p style="font-size: 0.85rem; color: #94a3b8;">
|
|
When prompted by your browser, select <strong>Entire Screen</strong> and click <strong>Share</strong>.
|
|
</p>
|
|
</div>
|
|
` : `
|
|
<div class="text-center">
|
|
<p style="margin-bottom: 12px; color: #1D2A36;">
|
|
Before you begin, please share your <strong>entire screen</strong>.
|
|
</p>
|
|
<p style="font-size: 0.85rem; color: #94a3b8;">
|
|
When prompted by your browser, select <strong>Entire Screen</strong> and click <strong>Share</strong>.
|
|
</p>
|
|
</div>
|
|
`;
|
|
|
|
if (typeof Swal !== 'undefined') {
|
|
Swal.fire({
|
|
icon: 'warning',
|
|
title: 'Screen Sharing Required',
|
|
html: messageHtml,
|
|
confirmButtonText: 'Share Entire Screen Now',
|
|
confirmButtonColor: '#6366f1',
|
|
allowOutsideClick: false,
|
|
allowEscapeKey: false
|
|
}).then((res) => {
|
|
if (res.isConfirmed) {
|
|
startScreenShare();
|
|
}
|
|
});
|
|
} else {
|
|
alert((reasonMessage ? (reasonMessage + ' ') : '') + 'Screen sharing is required. Please select Entire Screen when prompted.');
|
|
startScreenShare();
|
|
}
|
|
}
|
|
|
|
function startScreenShare() {
|
|
if (!navigator.mediaDevices.getDisplayMedia) {
|
|
alert('Screen sharing is not supported on your browser.');
|
|
return;
|
|
}
|
|
|
|
beginNativePrompt();
|
|
|
|
navigator.mediaDevices.getDisplayMedia({
|
|
video: {
|
|
displaySurface: 'monitor'
|
|
},
|
|
audio: false
|
|
})
|
|
.then(stream => {
|
|
endNativePrompt();
|
|
const track = stream.getVideoTracks()[0];
|
|
const settings = track.getSettings ? track.getSettings() : {};
|
|
|
|
// Enforce ENTIRE SCREEN share
|
|
if (settings.displaySurface && settings.displaySurface !== 'monitor') {
|
|
if (typeof Swal !== 'undefined') {
|
|
Swal.fire({
|
|
icon: 'warning',
|
|
title: 'Entire Screen Share Required',
|
|
text: 'You selected a single tab or window. You MUST select "Entire Screen".',
|
|
confirmButtonText: 'Reshare Entire Screen',
|
|
confirmButtonColor: '#6366f1',
|
|
allowOutsideClick: false,
|
|
allowEscapeKey: false
|
|
}).then(() => {
|
|
track.stop();
|
|
setTimeout(startScreenShare, 300);
|
|
});
|
|
} else {
|
|
alert('Entire Screen share is required. Please select Entire Screen.');
|
|
track.stop();
|
|
setTimeout(startScreenShare, 300);
|
|
}
|
|
return;
|
|
}
|
|
|
|
screenShareStream = stream;
|
|
const vidElem = getScreenShareVideoElement();
|
|
vidElem.srcObject = stream;
|
|
vidElem.play().catch(e => {});
|
|
|
|
const btn = document.getElementById('share-screen-btn');
|
|
if (btn) {
|
|
btn.innerText = '🟢 Entire Screen Sharing Active';
|
|
btn.style.background = '#10b981';
|
|
}
|
|
|
|
beginNativePrompt();
|
|
requestFullscreenAsPromise(document.documentElement)
|
|
.catch(() => {})
|
|
.finally(() => {
|
|
endNativePrompt();
|
|
armTrailingBuffer(1000);
|
|
});
|
|
|
|
// Connect screen stream to interviewer screen peer
|
|
const screenPeer = new Peer('cand_screen_' + interviewId + '_' + Date.now());
|
|
screenPeer.on('open', () => {
|
|
screenPeer.call('interviewer_screen_' + interviewId, stream);
|
|
});
|
|
|
|
track.onended = () => {
|
|
screenShareStream = null;
|
|
if (btn) {
|
|
btn.innerText = '🖥️ Share Screen with Interviewer';
|
|
btn.style.background = 'linear-gradient(135deg, #6366f1 0%, #0078d4 100%)';
|
|
}
|
|
logViolation('tab_switch', 'Candidate stopped screen sharing');
|
|
};
|
|
|
|
initLiveOverlayDetector();
|
|
})
|
|
.catch(err => {
|
|
endNativePrompt();
|
|
console.log('Screen sharing cancelled/denied:', err);
|
|
screenShareStream = null;
|
|
const btn = document.getElementById('share-screen-btn');
|
|
if (btn) {
|
|
btn.innerText = '🖥️ Share Screen with Interviewer';
|
|
btn.style.background = 'linear-gradient(135deg, #6366f1 0%, #0078d4 100%)';
|
|
}
|
|
});
|
|
}
|
|
|
|
|
|
function analyzeCameraFrame() {
|
|
const video = document.getElementById('webcam');
|
|
const canvas = document.getElementById('proctor-canvas');
|
|
if (!video || !canvas || video.readyState !== 4) return;
|
|
|
|
const ctx = canvas.getContext('2d');
|
|
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
|
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
|
|
|
// Compute brightness / pixel motion difference
|
|
let sum = 0;
|
|
for (let i = 0; i < imgData.data.length; i += 4) {
|
|
sum += (imgData.data[i] + imgData.data[i+1] + imgData.data[i+2]) / 3;
|
|
}
|
|
const avgBrightness = sum / (imgData.data.length / 4);
|
|
|
|
if (avgBrightness < 15) {
|
|
logViolation('gaze_anomaly', 'Camera lens covered or room completely dark');
|
|
}
|
|
}
|
|
|
|
// 5. 2-Way Real-Time Chat Message Polling (No popup alerts!)
|
|
function pollCandidateChat() {
|
|
fetch(`{{ route('interview.candidate.poll', $interview->id) }}`, {
|
|
headers: { 'Accept': 'application/json' }
|
|
})
|
|
.then(r => {
|
|
if (!r.ok) return null;
|
|
const contentType = r.headers.get('content-type');
|
|
if (!contentType || !contentType.includes('application/json')) return null;
|
|
return r.json();
|
|
})
|
|
.then(data => {
|
|
if (!data) return;
|
|
const chatHistory = document.getElementById('candidate-chat-history');
|
|
if (!chatHistory) return;
|
|
|
|
if (data.status === 'blocked' || data.is_expired) {
|
|
window.location.reload();
|
|
return;
|
|
}
|
|
|
|
if (data.warnings && Array.isArray(data.warnings)) {
|
|
if (data.warnings.length === 0) {
|
|
chatHistory.innerHTML = '<div style="color: #94a3b8; font-style: italic; text-align: center; padding-top: 40px;">No messages yet. Send a message below.</div>';
|
|
return;
|
|
}
|
|
|
|
let html = '';
|
|
data.warnings.forEach(w => {
|
|
const isInterviewer = w.sent_by !== null;
|
|
const senderName = isInterviewer ? (w.sender ? w.sender.name : 'Interviewer / Panelist') : 'You (Candidate)';
|
|
const badgeColor = isInterviewer ? '#6366f1' : '#38bdf8';
|
|
const bgColor = isInterviewer ? 'rgba(99,102,241,0.15)' : 'rgba(56,189,248,0.15)';
|
|
|
|
html += `<div style="margin-bottom:8px; background:${bgColor}; padding:8px 10px; border-radius:8px; border-left:3px solid ${badgeColor}; text-align: left;">
|
|
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
|
|
<strong style="color:${badgeColor}; font-size:0.75rem;">${senderName}</strong>
|
|
<span style="font-size:0.65rem; color:#94a3b8;">${new Date(w.created_at || Date.now()).toLocaleTimeString()}</span>
|
|
</div>
|
|
<div style="color: #ffffff !important; font-size:0.85rem; font-weight:500; line-height:1.4; word-break: break-word;">${w.message}</div>
|
|
</div>`;
|
|
});
|
|
chatHistory.innerHTML = html;
|
|
chatHistory.scrollTop = chatHistory.scrollHeight;
|
|
}
|
|
})
|
|
.catch(() => {});
|
|
}
|
|
setInterval(pollCandidateChat, 600);
|
|
pollCandidateChat();
|
|
|
|
function sendCandidateMessage() {
|
|
const input = document.getElementById('candidate-chat-input');
|
|
const msg = input.value.trim();
|
|
if (!msg) return;
|
|
|
|
input.value = '';
|
|
if (typeof liveSyncChannel !== 'undefined' && liveSyncChannel) {
|
|
liveSyncChannel.postMessage({ type: 'chat_message', message: msg, sender: 'candidate' });
|
|
}
|
|
|
|
fetch(`{{ route('interview.candidate.send-message', $interview->id) }}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-TOKEN': '{{ csrf_token() }}'
|
|
},
|
|
body: JSON.stringify({ message: msg })
|
|
})
|
|
.then(r => r.json())
|
|
.then(res => {
|
|
pollCandidateChat();
|
|
});
|
|
}
|
|
|
|
// --- NOTEPAD & CANVAS DRAWING HANDLERS ---
|
|
let notesTimeout = null;
|
|
|
|
function toggleNotepadModal() {
|
|
const modal = document.getElementById('notepad-modal');
|
|
modal.style.display = (modal.style.display === 'flex') ? 'none' : 'flex';
|
|
}
|
|
|
|
function saveNotepadContent() {
|
|
const notes = document.getElementById('notepad-textarea').value;
|
|
if (typeof liveSyncChannel !== 'undefined' && liveSyncChannel) {
|
|
liveSyncChannel.postMessage({ type: 'notes_sync', notes: notes });
|
|
}
|
|
|
|
clearTimeout(notesTimeout);
|
|
notesTimeout = setTimeout(() => {
|
|
fetch(`{{ route('interview.candidate.notes', $interview->id) }}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-TOKEN': '{{ csrf_token() }}'
|
|
},
|
|
body: JSON.stringify({ notes: notes })
|
|
});
|
|
}, 150);
|
|
}
|
|
|
|
// HTML5 Canvas Drawing Logic
|
|
let isDrawing = false;
|
|
let canvas, ctx;
|
|
let drawingSaveTimeout = null;
|
|
let lastDrawingSaveTime = 0;
|
|
|
|
function toggleDrawingModal() {
|
|
const modal = document.getElementById('drawing-modal');
|
|
modal.style.display = (modal.style.display === 'flex') ? 'none' : 'flex';
|
|
if (modal.style.display === 'flex' && !canvas) {
|
|
initCanvasDrawing();
|
|
}
|
|
}
|
|
|
|
function initCanvasDrawing() {
|
|
canvas = document.getElementById('drawing-canvas');
|
|
if (!canvas) return;
|
|
ctx = canvas.getContext('2d');
|
|
ctx.lineWidth = 3;
|
|
ctx.lineCap = 'round';
|
|
ctx.strokeStyle = '#38bdf8';
|
|
|
|
const savedDrawing = {!! json_encode($interview->candidate_drawing) !!};
|
|
if (savedDrawing) {
|
|
const img = new Image();
|
|
img.onload = () => ctx.drawImage(img, 0, 0);
|
|
img.src = savedDrawing;
|
|
}
|
|
|
|
canvas.addEventListener('mousedown', startDraw);
|
|
canvas.addEventListener('mousemove', draw);
|
|
canvas.addEventListener('mouseup', stopDraw);
|
|
canvas.addEventListener('mouseleave', stopDraw);
|
|
}
|
|
|
|
function startDraw(e) {
|
|
isDrawing = true;
|
|
ctx.beginPath();
|
|
ctx.moveTo(e.offsetX, e.offsetY);
|
|
}
|
|
|
|
function draw(e) {
|
|
if (!isDrawing) return;
|
|
ctx.strokeStyle = document.getElementById('draw-color').value;
|
|
ctx.lineTo(e.offsetX, e.offsetY);
|
|
ctx.stroke();
|
|
saveCanvasDrawing(false);
|
|
}
|
|
|
|
function stopDraw() {
|
|
if (isDrawing) {
|
|
isDrawing = false;
|
|
ctx.closePath();
|
|
saveCanvasDrawing(true);
|
|
}
|
|
}
|
|
|
|
function clearCanvasDraw() {
|
|
if (ctx && canvas) {
|
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
saveCanvasDrawing(true);
|
|
}
|
|
}
|
|
|
|
function saveCanvasDrawing(force = false) {
|
|
if (!canvas) return;
|
|
const now = Date.now();
|
|
const drawingData = canvas.toDataURL();
|
|
|
|
// Broadcast instant local event (0ms latency)
|
|
if (typeof liveSyncChannel !== 'undefined' && liveSyncChannel) {
|
|
liveSyncChannel.postMessage({ type: 'drawing_sync', drawing: drawingData });
|
|
}
|
|
|
|
// Throttled HTTP POST save to backend (fires every 250ms while drawing & on mouseup)
|
|
if (force || (now - lastDrawingSaveTime >= 250)) {
|
|
clearTimeout(drawingSaveTimeout);
|
|
lastDrawingSaveTime = now;
|
|
fetch(`{{ route('interview.candidate.drawing', $interview->id) }}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-TOKEN': '{{ csrf_token() }}'
|
|
},
|
|
body: JSON.stringify({ drawing: drawingData })
|
|
});
|
|
} else {
|
|
clearTimeout(drawingSaveTimeout);
|
|
drawingSaveTimeout = setTimeout(() => {
|
|
saveCanvasDrawing(true);
|
|
}, 250);
|
|
}
|
|
}
|
|
|
|
function sendCandidatePeerHeartbeat(action = 'heartbeat') {
|
|
if (!interviewId) return;
|
|
const candPeerId = 'cand_' + interviewId;
|
|
fetch('/candidate/peer-heartbeat/' + interviewId, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRF-TOKEN': '{{ csrf_token() }}'
|
|
},
|
|
body: JSON.stringify({
|
|
peer_id: candPeerId,
|
|
name: '{{ addslashes($interview->candidate_name) }}',
|
|
role: 'candidate',
|
|
action: action
|
|
})
|
|
}).catch(e => {});
|
|
}
|
|
|
|
setInterval(() => {
|
|
if (!interviewId) return;
|
|
sendCandidatePeerHeartbeat('heartbeat');
|
|
|
|
fetch('/candidate/poll/' + interviewId, {
|
|
headers: { 'Accept': 'application/json' }
|
|
})
|
|
.then(r => r.json())
|
|
.then(data => {
|
|
if (!data) return;
|
|
|
|
if (data.active_peers && Array.isArray(data.active_peers)) {
|
|
const activePeerIds = new Set(data.active_peers.map(p => p.peer_id));
|
|
|
|
data.active_peers.forEach(p => {
|
|
if (p.peer_id && p.peer_id.startsWith('interviewer_')) {
|
|
let roleLabel = p.role === 'admin' ? ('Admin ' + (p.name || '')) : ('Interviewer ' + (p.name || ''));
|
|
if (localMediaStream && peerInstance && peerInstance.open) {
|
|
if (!candidateInterviewerTiles.has(p.peer_id)) {
|
|
try {
|
|
const outCall = peerInstance.call(p.peer_id, localMediaStream);
|
|
if (outCall) {
|
|
outCall.on('stream', remoteStream => {
|
|
addOrUpdateCandidateInterviewerTile(p.peer_id, remoteStream, roleLabel);
|
|
});
|
|
}
|
|
} catch(e) {}
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
candidateInterviewerTiles.forEach((_, pid) => {
|
|
if (!activePeerIds.has(pid)) {
|
|
removeCandidateInterviewerTile(pid);
|
|
}
|
|
});
|
|
}
|
|
|
|
if (data.enable_tab_switch_screenshot !== undefined) {
|
|
isTabSwitchScreenshotEnabled = Boolean(data.enable_tab_switch_screenshot);
|
|
}
|
|
|
|
if (data.call_status === 'active') {
|
|
latestCallStatus = 'active';
|
|
if (data.call_started_at) latestCallStartedAt = data.call_started_at;
|
|
|
|
if (!hasCapturedCallStartScreenshot && isTabSwitchScreenshotEnabled) {
|
|
hasCapturedCallStartScreenshot = true;
|
|
setTimeout(() => {
|
|
captureAndUploadTabScreenshot('call_start');
|
|
}, 1200);
|
|
}
|
|
|
|
if (!isCandidateCallConnected && localMediaStream) {
|
|
acceptCandidateCall();
|
|
}
|
|
} else if (data.call_status === 'ended' || data.call_status === 'idle') {
|
|
latestCallStatus = data.call_status;
|
|
hasCapturedCallStartScreenshot = false;
|
|
candidateDeclinedOrLeftCall = false;
|
|
isCandidateCallConnected = false;
|
|
|
|
const badge = document.getElementById('call-status-badge');
|
|
if (badge) {
|
|
badge.innerText = (data.call_status === 'ended') ? 'CALL ENDED BY HOST' : 'READY';
|
|
badge.style.background = (data.call_status === 'ended') ? 'rgba(239,68,68,0.2)' : 'rgba(16,185,129,0.2)';
|
|
badge.style.color = (data.call_status === 'ended') ? '#fca5a5' : '#34d399';
|
|
}
|
|
}
|
|
})
|
|
.catch(() => {});
|
|
}, 6000);
|
|
</script>
|
|
</body>
|
|
</html>
|