-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
487 lines (372 loc) · 12.9 KB
/
script.js
File metadata and controls
487 lines (372 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
let sessionId = "";
let candidateName = "";
let candidateEmail = "";
let isRecovering = false;
let isWaitingForReconnect = false;
let disconnectTimer = null;
document.getElementById("candidateForm").addEventListener("submit", async (e) => {
e.preventDefault();
candidateName = document.getElementById("name").value.trim();
candidateEmail = document.getElementById("email").value.trim();
if (!candidateName || !candidateEmail) {
alert("Please enter both name and email.");
return;
}
sessionId = `${candidateName}_${Date.now()}`.replace(/\s+/g, "_");
localStorage.setItem("candidateName", candidateName);
localStorage.setItem("candidateEmail", candidateEmail);
localStorage.setItem("sessionId", sessionId);
document.getElementById("candidateForm").style.display = "none";
document.getElementById("startBtn").style.display = "inline-block";
console.log("Calling startInterview with:", candidateName, candidateEmail, sessionId);
setTimeout(() => {
startInterview(candidateName, candidateEmail, sessionId);
}, 1000);
});
async function startInterview(name, email, sessionId) {
if (!name || !email || !sessionId) {
alert("Missing candidate details. Please fill the form again.");
return;
}
const formData = new FormData();
formData.append("name", name);
formData.append("email", email);
formData.append("sessionId", sessionId);
try {
const response = await fetch(`${SERVER_URL}/start-session`, {
method: "POST",
body: formData
});
if (!response.ok) {
const errorData = await response.text();
console.error("Backend Error:", errorData);
alert("Failed to start session. Please try again.");
return;
}
const data = await response.json();
console.log(" Session started:", data);
} catch (error) {
console.error("Error starting interview:", error);
alert("Error connecting to server.");
}
}
const SERVER_URL = "https://ai-interview-backend-bzpz.onrender.com";
let recognitionTimeout = null;
//const urlParams = new URLSearchParams(window.location.search);
//const sessionId = urlParams.get("sessionId") || "anonymous_" + Date.now();
function appendMessage(sender, text) {
const chat = document.getElementById("chatContainer");
const msgDiv = document.createElement("div");
msgDiv.classList.add("message", sender === "ai" ? "ai" : "user");
msgDiv.textContent = text;
chat.appendChild(msgDiv);
chat.scrollTop = chat.scrollHeight;
}
let questions = [];
let db;
let currentQuestionIndex = 0;
window.addEventListener("load", () => {
candidateName = localStorage.getItem("candidateName") || "";
candidateEmail = localStorage.getItem("candidateEmail") || "";
sessionId = localStorage.getItem("sessionId") || "";
fetch(`${SERVER_URL}/questions`)
.then(res => res.json())
.then(data => {
questions = data;
})
.catch(err => {
console.error("Failed to load questions:", err);
alert("Could not load questions from server.");
});
const openRequest = indexedDB.open("RecordingDB", 1);
openRequest.onupgradeneeded = (e) => {
db = e.target.result;
if (!db.objectStoreNames.contains("chunks")) {
db.createObjectStore("chunks", { autoIncrement: true });
}
};
openRequest.onsuccess = (e) => {
db = e.target.result;
const tx = db.transaction("chunks", "readonly");
const store = tx.objectStore("chunks");
const getAll = store.getAll();
getAll.onsuccess = () => {
if (getAll.result.length > 0) {
if (confirm("Previous interview session was interrupted. Recover?")) {
recoverPreviousRecording();
}
}
};
};
});
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.continuous = false;
recognition.interimResults = true;
recognition.lang = 'en-US';
let mediaRecorder;
let recordedChunks = [];
let conversation = "";
let audioCtx;
let destinationStream;
let interimElement = null;
const startButton = document.getElementById("startBtn");
const preview = document.getElementById("preview");
window.addEventListener('offline', () => {
console.warn(" Internet disconnected");
handleInternetLoss();
});
window.addEventListener('online', () => {
console.log(" Internet reconnected");
if (isWaitingForReconnect) {
clearTimeout(disconnectTimer);
resumeInterviewAfterReconnect();
}
});
startButton.addEventListener("click", async () => {
if (!candidateName || !candidateEmail || !sessionId) {
alert("Missing candidate details.");
return;
}
if (!db) {
alert("IndexedDB not initialized yet. Please wait a moment and try again.");
return;
}
if (questions.length === 0) {
alert("Interview questions not loaded yet.");
return;
}
const micStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
preview.srcObject = micStream;
audioCtx = new AudioContext();
const destination = audioCtx.createMediaStreamDestination();
destinationStream = destination.stream;
const micSource = audioCtx.createMediaStreamSource(micStream);
micSource.connect(destination);
const combinedStream = new MediaStream([
...micStream.getVideoTracks(),
...destinationStream.getAudioTracks()
]);
recordedChunks = [];
mediaRecorder = new MediaRecorder(combinedStream);
mediaRecorder.ondataavailable = (e) => {
if (e.data.size > 0) {
const chunk = e.data;
recordedChunks.push(chunk);
if (!db) {
alert("IndexedDB not ready. Cannot recover previous session.");
return;
}
const tx = db.transaction("chunks", "readwrite");
const store = tx.objectStore("chunks");
store.add(chunk);
uploadChunkToServer(chunk);
}
};
mediaRecorder.onstop = async () => {
if (isRecovering) return;
notifyInterviewComplete();
const tx = db.transaction("chunks", "readonly");
const store = tx.objectStore("chunks");
const allChunks = [];
store.openCursor().onsuccess = async (event) => {
const cursor = event.target.result;
if (cursor) {
allChunks.push(cursor.value);
cursor.continue();
} else {
const blob = new Blob(allChunks, { type: 'video/webm' });
const textBlob = new Blob([conversation], { type: 'text/plain' });
try {
await uploadToServer(blob, textBlob);
} catch (err) {
console.error("Upload failed:", err);
alert("Upload to server failed.");
return;
}
const clearTx = db.transaction("chunks", "readwrite");
const clearStore = clearTx.objectStore("chunks");
clearStore.clear();
}
};
};
currentQuestionIndex = 0;
try {
mediaRecorder.start(5000);
} catch (err) {
console.error("MediaRecorder start failed:", err);
alert("Recording could not start. Please try again.");
return;
}
askQuestionAndListen(currentQuestionIndex);
});
function askQuestionAndListen(index) {
if (isWaitingForReconnect) {
console.warn("⏸ Waiting for internet reconnect. Pausing question...");
return;
}
if (index >= questions.length) {
mediaRecorder.stop();
return;
}
currentQuestionIndex = index;
const question = questions[index];
conversation += `AI: ${question}\n`;
appendMessage("ai", question);
const utterance = new SpeechSynthesisUtterance(question);
utterance.onend = () => {
if (isWaitingForReconnect) return;
recognition.start();
recognitionTimeout = setTimeout(() => {
recognition.stop();
handleNoResponseFallback();
}, 6000);
};
speechSynthesis.speak(utterance);
}
recognition.onresult = (event) => {
clearTimeout(recognitionTimeout);
let finalTranscript = "";
let interimTranscript = "";
for (let i = event.resultIndex; i < event.results.length; ++i) {
const transcript = event.results[i][0].transcript;
if (event.results[i].isFinal) {
finalTranscript += transcript + " ";
conversation += `Candidate: ${transcript}\n\n`;
appendMessage("user", transcript);
if (interimElement) {
interimElement.remove();
interimElement = null;
}
recognition.stop();
setTimeout(() => askQuestionAndListen(currentQuestionIndex + 1), 1500);
} else {
interimTranscript += transcript;
}
}
if (interimTranscript) {
if (!interimElement) {
interimElement = document.createElement("div");
interimElement.classList.add("message", "user");
interimElement.style.opacity = "0.6";
document.getElementById("chatContainer").appendChild(interimElement);
}
interimElement.textContent = interimTranscript;
}
};
function handleNoResponseFallback() {
conversation += `Candidate: [No response]\n\n`;
appendMessage("user", "[No response]");
setTimeout(() => askQuestionAndListen(currentQuestionIndex + 1), 1500);
}
recognition.onerror = () => {
clearTimeout(recognitionTimeout);
handleNoResponseFallback();
};
function recoverPreviousRecording() {
if (!db) {
alert("IndexedDB not ready. Cannot recover previous session.");
return;
}
const tx = db.transaction("chunks", "readonly");
const store = tx.objectStore("chunks");
const allChunks = [];
store.openCursor().onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
allChunks.push(cursor.value);
cursor.continue();
} else {
if (allChunks.length > 0) {
const recoveredBlob = new Blob(allChunks, { type: 'video/webm' });
const recoveredURL = URL.createObjectURL(recoveredBlob);
isRecovering = true;
candidateName = localStorage.getItem("candidateName") || "Unknown";
candidateEmail = localStorage.getItem("candidateEmail") || "Unknown";
sessionId = localStorage.getItem("sessionId") || `unknown_${Date.now()}`;
uploadToServer(recoveredBlob, new Blob(["Recovered session"], { type: 'text/plain' }), candidateName, candidateEmail, sessionId);
const clearTx = db.transaction("chunks", "readwrite");
const clearStore = clearTx.objectStore("chunks");
clearStore.clear();
}
}
};
}
function uploadChunkToServer(chunk) {
const sid = localStorage.getItem("sessionId");
const name = localStorage.getItem("candidateName");
const email = localStorage.getItem("candidateEmail");
if (!sid || !name || !email) {
console.warn(" Skipping chunk: Missing session or candidate info");
return;
}
const formData = new FormData();
formData.append("chunk", chunk, "chunk.webm");
formData.append("sessionId", sid);
formData.append("name", name);
formData.append("email", email);
fetch(`${SERVER_URL}/upload-chunk`, {
method: "POST",
body: formData,
})
.then(res => res.text())
.then(data => console.log(" Chunk uploaded"))
.catch(err => console.error(" Chunk upload failed:", err));
}
function notifyInterviewComplete() {
fetch(`${SERVER_URL}/mark-complete`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sessionId }),
})
.then(res => res.text())
.then(data => console.log("Interview marked complete."))
.catch(err => console.error("Error marking complete:", err));
}
function handleInternetLoss() {
if (!mediaRecorder || mediaRecorder.state !== "recording" || isWaitingForReconnect) return;
mediaRecorder.pause();
alert(" Internet disconnected! You have 2 minutes to reconnect before your interview ends.");
isWaitingForReconnect = true;
disconnectTimer = setTimeout(() => {
alert(" Internet not restored in time. Uploading partial interview...");
mediaRecorder.stop();
isWaitingForReconnect = false;
}, 2 * 60 * 1000);
}
function resumeInterviewAfterReconnect() {
alert(" Internet reconnected. Resuming interview.");
isWaitingForReconnect = false;
if (mediaRecorder && mediaRecorder.state === "paused") {
mediaRecorder.resume();
}
setTimeout(() => {
askQuestionAndListen(currentQuestionIndex);
}, 1000);
}
async function uploadToServer(videoBlob, transcriptBlob, customName = candidateName, customEmail = candidateEmail, customSessionId = sessionId) {
const formData = new FormData();
formData.append("video", videoBlob, "interview.webm");
formData.append("transcript", transcriptBlob, "transcript.txt");
formData.append("sessionId", customSessionId);
formData.append("name", customName);
formData.append("email", customEmail);
try {
const response = await fetch(`${SERVER_URL}/upload`, {
method: "POST",
body: formData,
});
const resultText = await response.text();
console.log(" Server response:", resultText);
if (!response.ok) {
console.error(" Upload failed with status", response.status);
alert("Upload failed. Server said: " + resultText);
return;
}
console.log(" Final video and transcript uploaded.");
alert(" Interview uploaded successfully!");
} catch (err) {
console.error(" Upload failed due to network or crash:", err);
alert("Upload to server failed due to error: " + err.message);
}
}