diff --git a/client/scripts/background.js b/client/scripts/background.js index 8887799..048566f 100644 --- a/client/scripts/background.js +++ b/client/scripts/background.js @@ -277,6 +277,8 @@ chrome.runtime.onMessage.addListener( logClientAction("listener gotoMediaTab"); // Активируем вкладку media.html (по URL, переданному в message.mediaExtensionUrl) openTab(message.mediaExtensionUrl); + sendResponse({status: "gotoMediaTab_processed"}); + return true; } if (message.action === "closeTabAndOpenTab") { chrome.tabs.query({ url: message.mediaExtensionUrl }, (tabs) => { @@ -289,7 +291,10 @@ chrome.runtime.onMessage.addListener( openTab(message.settingsUrl); } }); + sendResponse({status: "closeTab_processed"}); + return true; } sendResponse(message); + return false; } ); \ No newline at end of file diff --git a/client/scripts/common.js b/client/scripts/common.js index ab9eb2a..408bef0 100644 --- a/client/scripts/common.js +++ b/client/scripts/common.js @@ -19,7 +19,7 @@ export async function deleteFilesFromTempList() { } export async function showModalNotify(messages, title = "Уведомление", showOnActiveTab = false, mediaIntependent=false) { - chrome.runtime.sendMessage({ action: "closePopup" }); + await chrome.runtime.sendMessage({ action: "closePopup" }); logClientAction({ action: "showModalNotify", showOnActiveTab}); @@ -49,7 +49,7 @@ export async function showModalNotify(messages, title = "Уведомление" throw error; } } else { - return new Promise((resolve) => { + return new Promise((resolve, reject) => { chrome.runtime.sendMessage({ action: "gotoMediaTab", mediaExtensionUrl: chrome.runtime.getURL("pages/media.html") }, (response) => { @@ -81,17 +81,19 @@ export async function showModalNotify(messages, title = "Уведомление" `; - modal.querySelector('#modal-close-btn').addEventListener('click', () => { + const closeButton = modal.querySelector('#modal-close-btn'); + const closeModalHandler = () => { + closeButton.removeEventListener('click', closeModalHandler); overlay.remove(); document.body.style.overflow = ''; resolve(); - }); + } + closeButton.addEventListener('click', closeModalHandler); document.body.style.overflow = 'hidden'; overlay.appendChild(modal); document.body.appendChild(overlay); } else { - chrome.runtime.sendMessage({ type: "showModalNotifyOnMedia", messages: messages, diff --git a/client/scripts/index.js b/client/scripts/index.js index d7e0f0c..648e0a8 100644 --- a/client/scripts/index.js +++ b/client/scripts/index.js @@ -8,7 +8,7 @@ const recordTime = document.querySelector('#record-time') let timerInterval = null; let startTime = null; -let server_connection = true; +let server_connection = false; chrome.storage.local.set({'server_connection': server_connection}); const inputElements = { @@ -470,17 +470,12 @@ chrome.runtime.onMessage.addListener((message) => { chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.type === 'stopRecordSignal') { - console.log('Received stopRecordSignal'); - clearInterval(timerInterval); - chrome.storage.local.get(['timeStr'], (result) => { const timeStr = result.timeStr; recordTime.textContent = timeStr; sendResponse({status: 'stopRecordSignalProcessed'}); }); - - sendResponse({status: 'stopRecordSignalProcessed'}); return true; } }); @@ -546,8 +541,6 @@ async function uploadVideo() { const metadata = (await chrome.storage.local.get('metadata'))['metadata'] || {}; formData.append("metadata", metadata); - //logClientAction({ action: "Prepare upload payload", sessionId: session_id, fileNames: [combinedFileName, cameraFileName] }); - if (extension_logs) { let logsToSend; if (typeof extension_logs === "string") { diff --git a/client/scripts/media.js b/client/scripts/media.js index 83011d5..c2b0526 100644 --- a/client/scripts/media.js +++ b/client/scripts/media.js @@ -202,9 +202,9 @@ async function sendButtonsStates(state) { } } -const updateInvalidStopValue = (flag) => { +const updateInvalidStopValue = async (flag) => { invalidStop = flag; - chrome.storage.local.set({ 'invalidStop': flag }); + await chrome.storage.local.set({ 'invalidStop': flag }); } async function getMediaDevices() { @@ -252,7 +252,15 @@ async function getMediaDevices() { throw new Error('Не удалось получить видеопоток с экрана'); } - chrome.runtime.sendMessage({ type: 'screenCaptureStatus', active: true }); + chrome.runtime.sendMessage( + { type: 'screenCaptureStatus', active: true }, + (response) => { + if (chrome.runtime.lastError) { + logClientAction(`Screen capture status sending failed. Error: ${chrome.runtime.lastError.message}`); + return; + } + logClientAction(`Screen capture status sending was successful: ${response}`); + }); let micPermissionDenied = false; let camPermissionDenied = false; @@ -349,6 +357,12 @@ async function getMediaDevices() { action: 'closeTabAndOpenTab', mediaExtensionUrl: mediaExtensionUrl, settingsUrl: settingsUrl + }, (response) => { + if (chrome.runtime.lastError) { + logClientAction(`Close tab and open tab was failed. Error: ${chrome.runtime.lastError.message}`); + return; + } + logClientAction(`Close tab and open tab was successful: ${response}`); }); logClientAction({ action: "Redirect to permission settings" }); @@ -373,13 +387,21 @@ async function getMediaDevices() { stopDuration(); await sendButtonsStates('needPermissions'); await showModalNotify(["Текущие записи завершатся. Чтобы продолжить запись заново, выдайте разрешения во всплывающем окне по кнопке Разрешения и начните запись."], "Доступ к камере потерян!"); - updateInvalidStopValue(true); + await updateInvalidStopValue(true); stopRecord(); } }; streams.screen.getVideoTracks()[0].onended = async function () { - chrome.runtime.sendMessage({ type: 'screenCaptureStatus', active: false }); + chrome.runtime.sendMessage( + { type: 'screenCaptureStatus', active: false }, + (response) => { + if (chrome.runtime.lastError) { + logClientAction(`Screen capture status sending failed. Error: ${chrome.runtime.lastError.message}`); + return; + } + logClientAction(`Screen capture status sending was successful: ${response}`); + }); if (streamLossSource) return; streamLossSource = 'screen'; logClientAction('Screen stream ended'); @@ -393,7 +415,7 @@ async function getMediaDevices() { stopDuration(); await sendButtonsStates('needPermissions'); await showModalNotify(["Текущие записи завершатся. Чтобы продолжить запись заново, выдайте разрешения в расширении во всплывающем окне по кнопке Разрешения и начните запись."], "Доступ к экрану потерян!"); - updateInvalidStopValue(true); + await updateInvalidStopValue(true); stopRecord(); } }; @@ -412,7 +434,7 @@ async function getMediaDevices() { stopDuration(); await sendButtonsStates('needPermissions'); await showModalNotify(["Текущие записи завершатся. Чтобы продолжить запись заново, выдайте разрешения в расширении во всплывающем окне по кнопке Разрешения и начните запись."], "Доступ к микрофону потерян!"); - updateInvalidStopValue(true); + await updateInvalidStopValue(true); stopRecord(); } }; @@ -654,7 +676,7 @@ chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => { window.removeEventListener('beforeunload', beforeUnloadHandler); stopRecord(); await setMetadatasRecordOff(); - chrome.storage.local.set({'metadata': JSON.stringify(metadata)}); + await chrome.storage.local.set({'metadata': JSON.stringify(metadata)}); await sendButtonsStates('readyToUpload'); } } @@ -686,7 +708,7 @@ chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => { }); } else if (message.action === 'startRecording') { - updateInvalidStopValue( + await updateInvalidStopValue( (await chrome.storage.local.get('invalidStop'))['invalidStop'] || false ); if (!invalidStop) await checkAndCleanLogs(); @@ -724,7 +746,7 @@ chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => { logClientAction({ action: "Generate session ID locally", sessionId }); } } - updateInvalidStopValue(false); + await updateInvalidStopValue(false); startRecord() .then(async () => { @@ -793,7 +815,7 @@ async function initSession(formData) { } } -function stopDuration() { +async function stopDuration() { const durationMs = new Date() - startTime; const seconds = Math.floor((durationMs / 1000) % 60); @@ -804,22 +826,30 @@ function stopDuration() { `${minutes.toString().padStart(2, '0')}:` + `${seconds.toString().padStart(2, '0')}`; - chrome.storage.local.set({ - 'timeStr': timeStr - }, function() { - console.log('timeStr saved to storage'); - logClientAction("stopDuration timeStr saved to storage"); - }); + await chrome.storage.local.set({ 'timeStr': timeStr }); + logClientAction("stopDuration timeStr saved to storage"); - chrome.runtime.sendMessage({type: 'stopRecordSignal'}, function(response) { - console.log('stopRecordSignal sent'); - logClientAction("stopDuration stopRecordSignal sent"); + chrome.runtime.sendMessage({type: 'stopRecordSignal'}, (response) => { + if (chrome.runtime.lastError) { + logClientAction(`Stop record signal is failed. Error: ${chrome.runtime.lastError.message}`); + return; + } + logClientAction(`stopDuration stopRecordSignal received: ${response}`); }); } async function stopRecord() { if (!invalidStop) stopDuration(); - chrome.runtime.sendMessage({ type: 'screenCaptureStatus', active: false }); + + chrome.runtime.sendMessage( + { type: 'screenCaptureStatus', active: false }, + (response) => { + if (chrome.runtime.lastError) { + logClientAction(`Screen capture status sending failed. Error: ${chrome.runtime.lastError.message}`); + return; + } + logClientAction(`Screen capture status sending was successful: ${response}`); + }); isRecording = false; isPreviewEnabled = false; @@ -984,14 +1014,6 @@ async function startRecord() { await addFileToTempList(cameraFileName); logClientAction('Files added to temp list'); - chrome.storage.local.set({ - 'fileNames': { - screen: combinedFileName, - camera: cameraFileName - } - }); - logClientAction({ action: "Save fileNames to storage" }); - await chrome.runtime.sendMessage({ action: 'scheduleCleanup', delayMinutes: 245 @@ -1016,7 +1038,6 @@ async function startRecord() { console.log('Запись начата'); logClientAction('recording_started'); - //chrome.runtime.sendMessage({ action: "closePopup" }); } catch (error) { console.error('Ошибка при запуске записи:', error.message); logClientAction({ action: "Fail to start recording", error: error.message });