From 8dcc4109d11b3036bfc371796956b829881b0da7 Mon Sep 17 00:00:00 2001 From: simon Date: Sun, 3 Apr 2022 20:54:29 +0700 Subject: [PATCH] refactor background.js onMessage event listener --- extension/background.js | 132 ++++++++++++++++++++++++++-------------- extension/popup.js | 80 ++++++++++++++++++------ extension/script.js | 6 +- 3 files changed, 146 insertions(+), 72 deletions(-) diff --git a/extension/background.js b/extension/background.js index b0bbf6d..0a865f0 100644 --- a/extension/background.js +++ b/extension/background.js @@ -11,10 +11,8 @@ let browserType = getBrowser(); function getBrowser() { if (typeof chrome !== "undefined") { if (typeof browser !== "undefined") { - console.log("detected firefox"); return browser; } else { - console.log("detected chrome"); return chrome; } } else { @@ -24,15 +22,40 @@ function getBrowser() { } +// send get request to API backend +async function sendGet(path, access) { + + const url = `${access.url}:${access.port}/${path}`; + console.log("GET: " + url); + + const rawResponse = await fetch(url, { + method: "GET", + headers: { + "Accept": "application/json", + "Content-Type": "application/json", + "Authorization": "Token " + access.apiKey, + "mode": "no-cors" + } + }); + + const content = await rawResponse.json(); + return content; +} + + // send post request to API backend -async function sendPayload(url, token, payload) { +async function sendPost(path, access, payload) { + + const url = `${access.url}:${access.port}/${path}`; + console.log("POST: " + url); + console.log("POST: " + JSON.stringify(payload)) const rawResponse = await fetch(url, { method: "POST", headers: { "Accept": "application/json", "Content-Type": "application/json", - "Authorization": token, + "Authorization": "Token " + access.apiKey, "mode": "no-cors" }, body: JSON.stringify(payload) @@ -43,56 +66,71 @@ async function sendPayload(url, token, payload) { } -// read access storage and send -function forwardRequest(payload) { +// read access details from storage.local +async function getAccess() { - console.log("running forwardRequest"); + var storage = await browserType.storage.local.get("access"); - function onGot(item) { - console.log(item.access); - - const url = `${item.access.url}:${item.access.port}/api/download/`; - console.log(`sending to ${url}`); - const token = `Token ${item.access.apiKey}`; - - sendPayload(url, token, payload).then(content => { - console.log(content); - }) - - }; - - function onError(error) { - console.local("failed to get access details"); - console.log(`Error: ${error}`); - }; - - browserType.storage.local.get("access", function(result) { - onGot(result) - }); + return storage.access } -// listen for messages -browserType.runtime.onMessage.addListener( - function(request, sender, sendResponse) { - console.log("responding from background.js listener"); - console.log(JSON.stringify(request)); - if (request.youtube) { - browserType.storage.local.set(request, function() { - console.log("Stored history: " + JSON.stringify(request)); - }); - } else if (request.download) { - let payload = { - "data": [ - { - "youtube_id": request.download["url"], - "status": "pending", - } - ] +// send ping to server, return response +async function verifyConnection() { + + const path = "api/ping/"; + let access = await getAccess(); + let response = await sendGet(path, access) + console.log("verify connection: " + JSON.stringify(response)); + + return response +} + + +// store last youtube link +function setYoutubeLink(data) { + browserType.storage.local.set(data, function() { + console.log("Stored history: " + JSON.stringify(data)); + }); +} + + +// send download task to server, return response +async function downloadLink(toDownload) { + + const path = "api/download/"; + let payload = { + "data": [ + { + "youtube_id": toDownload, + "status": "pending", } - console.log(payload); - forwardRequest(payload); + ] + } + let access = await getAccess(); + let response = await sendPost(path, access, payload) + + return response + +} + + +// event listener for messages from script.js and popup.js +browser.runtime.onMessage.addListener( + (data, sender) => { + console.log("message background.js listener: " + JSON.stringify(data)) + if (data.verify === true) { + let response = verifyConnection() + return Promise.resolve(response); + } else if (data.youtube) { + setYoutubeLink(data) + } else if (data.download) { + let response = downloadLink(data.download.url) + return Promise.resolve(response); } + + return false; + } ); diff --git a/extension/popup.js b/extension/popup.js index 5458afc..b7e8ba1 100644 --- a/extension/popup.js +++ b/extension/popup.js @@ -8,10 +8,8 @@ let browserType = getBrowser(); function getBrowser() { if (typeof chrome !== "undefined") { if (typeof browser !== "undefined") { - console.log("detected firefox"); return browser; } else { - console.log("detected chrome"); return chrome; } } else { @@ -20,9 +18,9 @@ function getBrowser() { }; } + // store access details document.getElementById("save-login").addEventListener("click", function () { - console.log("save form"); let toStore = { "access": { "url": document.getElementById("url").value, @@ -30,20 +28,49 @@ document.getElementById("save-login").addEventListener("click", function () { "apiKey": document.getElementById("api-key").value } }; - console.log(toStore); browserType.storage.local.set(toStore, function() { console.log("Stored connection details: " + JSON.stringify(toStore)); + pingBackend(); }); }) +// verify connection status +document.getElementById("status-icon").addEventListener("click", function() { + pingBackend(); +}) + + +// send ping message to TA backend +function pingBackend() { + + function handleResponse(message) { + if (message.response === "pong") { + setStatusIcon(true); + console.log("connection validated") + } + } + + function handleError(error) { + console.log(`Error: ${error}`); + setStatusIcon(false); + } + + console.log("ping TA server") + let sending = browserType.runtime.sendMessage({"verify": true}); + sending.then(handleResponse, handleError); + +} + + +// change status icon based on connection status function setStatusIcon(connected) { let statusIcon = document.getElementById("status-icon") if (connected == true) { - console.log("connected"); + statusIcon.innerHTML = "☑"; + statusIcon.style.color = "green"; } else { - console.log("not connected"); statusIcon.innerHTML = "☒"; statusIcon.style.color = "red"; } @@ -51,21 +78,43 @@ function setStatusIcon(connected) { } +// download link +document.getElementById("download").addEventListener("click", function () { + + let button = document.getElementById("downloadButton"); + let payload = { + "download": { + "url": button.getAttribute("data-id") + } + }; + + function handleResponse(message) { + console.log("popup.js response: " + JSON.stringify(message)); + } + + function handleError(error) { + console.log(`Error: ${error}`); + } + + let sending = browserType.runtime.sendMessage(payload); + sending.then(handleResponse, handleError) + +}) + + // fill in form document.addEventListener("DOMContentLoaded", async () => { - console.log("executing dom loader"); - function onGot(item) { if (!item.access) { console.log("no access details found"); setStatusIcon(false); return } - console.log(item.access); document.getElementById("url").value = item.access.url; document.getElementById("port").value = item.access.port; document.getElementById("api-key").value = item.access.apiKey; + pingBackend(); }; function onError(error) { @@ -83,7 +132,7 @@ document.addEventListener("DOMContentLoaded", async () => { }) function downlodButton(result) { - console.log("running build dl button"); + let download = document.getElementById("download"); let title = document.createElement("p"); title.innerText = result.youtube.title; @@ -93,17 +142,8 @@ function downlodButton(result) { button.id = "downloadButton"; button.setAttribute("data-id", result.youtube.url); - button.addEventListener("click", function () { - console.log("send download message"); - let payload = { - "download": { - "url": result.youtube.url - } - }; - browserType.runtime.sendMessage(payload); - }); - download.appendChild(title); download.appendChild(button); download.appendChild(document.createElement("hr")); + } diff --git a/extension/script.js b/extension/script.js index 8c61233..9057bc5 100644 --- a/extension/script.js +++ b/extension/script.js @@ -2,8 +2,6 @@ content script running on youtube.com */ -console.log("running script.js"); - let browserType = getBrowser(); @@ -25,7 +23,6 @@ function getBrowser() { function sendUrl() { - console.log("run sendUrl from script.js"); let payload = { "youtube": { @@ -33,7 +30,7 @@ function sendUrl() { "title": document.title } } - console.log(JSON.stringify(payload)); + console.log("youtube link: " + JSON.stringify(payload)); browserType.runtime.sendMessage(payload, function(response) { console.log(response.farewell); }); @@ -42,7 +39,6 @@ function sendUrl() { document.addEventListener("yt-navigate-finish", function (event) { - console.log("running setimeout") setTimeout(function(){ sendUrl(); return false;