From 723c54d9037d496c7d1f746f79cb3fed64bc1c29 Mon Sep 17 00:00:00 2001 From: ascens1ve Date: Sun, 18 May 2025 17:28:19 +0300 Subject: [PATCH 1/5] Fix: add correct behavior to chrome sendMessage --- client/scripts/background.js | 5 +++ client/scripts/common.js | 2 +- client/scripts/index.js | 7 ---- client/scripts/media.js | 71 +++++++++++++++++++++++------------- 4 files changed, 52 insertions(+), 33 deletions(-) diff --git a/client/scripts/background.js b/client/scripts/background.js index 83e1c15..21fe8f6 100644 --- a/client/scripts/background.js +++ b/client/scripts/background.js @@ -228,6 +228,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) => { @@ -240,7 +242,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..7e33cc4 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}); diff --git a/client/scripts/index.js b/client/scripts/index.js index d7e0f0c..4947eaf 100644 --- a/client/scripts/index.js +++ b/client/scripts/index.js @@ -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 35017b6..cd9d722 100644 --- a/client/scripts/media.js +++ b/client/scripts/media.js @@ -191,9 +191,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() { @@ -241,7 +241,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; @@ -310,6 +318,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" }); @@ -340,7 +354,15 @@ async function getMediaDevices() { }; 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'); @@ -615,7 +637,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'); } } @@ -754,7 +776,7 @@ async function initSession(formData) { } } -function stopDuration() { +async function stopDuration() { const durationMs = new Date() - startTime; const seconds = Math.floor((durationMs / 1000) % 60); @@ -765,22 +787,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; @@ -945,14 +975,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 @@ -977,7 +999,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 }); From 390a8f356614ed9281cb69501fc0fddd13d6520c Mon Sep 17 00:00:00 2001 From: ascens1ve Date: Thu, 22 May 2025 22:33:13 +0300 Subject: [PATCH 2/5] Add await to async function --- client/scripts/media.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/client/scripts/media.js b/client/scripts/media.js index cd9d722..56b15a5 100644 --- a/client/scripts/media.js +++ b/client/scripts/media.js @@ -348,7 +348,7 @@ async function getMediaDevices() { stopDuration(); await sendButtonsStates('needPermissions'); await showModalNotify(["Текущие записи завершатся. Чтобы продолжить запись заново, выдайте разрешения во всплывающем окне по кнопке Разрешения и начните запись."], "Доступ к камере потерян!"); - updateInvalidStopValue(true); + await updateInvalidStopValue(true); stopRecord(); } }; @@ -376,7 +376,7 @@ async function getMediaDevices() { stopDuration(); await sendButtonsStates('needPermissions'); await showModalNotify(["Текущие записи завершатся. Чтобы продолжить запись заново, выдайте разрешения в расширении во всплывающем окне по кнопке Разрешения и начните запись."], "Доступ к экрану потерян!"); - updateInvalidStopValue(true); + await updateInvalidStopValue(true); stopRecord(); } }; @@ -395,7 +395,7 @@ async function getMediaDevices() { stopDuration(); await sendButtonsStates('needPermissions'); await showModalNotify(["Текущие записи завершатся. Чтобы продолжить запись заново, выдайте разрешения в расширении во всплывающем окне по кнопке Разрешения и начните запись."], "Доступ к микрофону потерян!"); - updateInvalidStopValue(true); + await updateInvalidStopValue(true); stopRecord(); } }; @@ -669,7 +669,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(); @@ -707,7 +707,7 @@ chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => { logClientAction({ action: "Generate session ID locally", sessionId }); } } - updateInvalidStopValue(false); + await updateInvalidStopValue(false); startRecord() .then(async () => { From c70ba80b2b645046e9c6d4d2ad8581d59c5d157e Mon Sep 17 00:00:00 2001 From: proitshnik Date: Sun, 25 May 2025 15:23:16 +0300 Subject: [PATCH 3/5] Server off for test build --- client/scripts/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/scripts/index.js b/client/scripts/index.js index 4947eaf..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 = { From 354ceb0af96645b1f6d94e01dcad240e031e5a59 Mon Sep 17 00:00:00 2001 From: ascens1ve Date: Sun, 25 May 2025 16:07:19 +0300 Subject: [PATCH 4/5] Add reject to Promise --- client/scripts/common.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/client/scripts/common.js b/client/scripts/common.js index 7e33cc4..255ba0c 100644 --- a/client/scripts/common.js +++ b/client/scripts/common.js @@ -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) => { @@ -91,7 +91,6 @@ export async function showModalNotify(messages, title = "Уведомление" overlay.appendChild(modal); document.body.appendChild(overlay); } else { - chrome.runtime.sendMessage({ type: "showModalNotifyOnMedia", messages: messages, From ad587b058293f8c9ff63458d7d9cb881defad4a4 Mon Sep 17 00:00:00 2001 From: ascens1ve Date: Sun, 25 May 2025 16:59:31 +0300 Subject: [PATCH 5/5] Update: delete event listener after click close button --- client/scripts/common.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/client/scripts/common.js b/client/scripts/common.js index 255ba0c..408bef0 100644 --- a/client/scripts/common.js +++ b/client/scripts/common.js @@ -81,11 +81,14 @@ 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);