refactor background.js onMessage event listener

This commit is contained in:
simon 2022-04-03 20:54:29 +07:00
parent 175e14aedd
commit 8dcc4109d1
No known key found for this signature in database
GPG Key ID: 2C15AA5E89985DD4
3 changed files with 146 additions and 72 deletions

View File

@ -11,10 +11,8 @@ let browserType = getBrowser();
function getBrowser() { function getBrowser() {
if (typeof chrome !== "undefined") { if (typeof chrome !== "undefined") {
if (typeof browser !== "undefined") { if (typeof browser !== "undefined") {
console.log("detected firefox");
return browser; return browser;
} else { } else {
console.log("detected chrome");
return chrome; return chrome;
} }
} else { } 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 // 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, { const rawResponse = await fetch(url, {
method: "POST", method: "POST",
headers: { headers: {
"Accept": "application/json", "Accept": "application/json",
"Content-Type": "application/json", "Content-Type": "application/json",
"Authorization": token, "Authorization": "Token " + access.apiKey,
"mode": "no-cors" "mode": "no-cors"
}, },
body: JSON.stringify(payload) body: JSON.stringify(payload)
@ -43,56 +66,71 @@ async function sendPayload(url, token, payload) {
} }
// read access storage and send // read access details from storage.local
function forwardRequest(payload) { async function getAccess() {
console.log("running forwardRequest"); var storage = await browserType.storage.local.get("access");
function onGot(item) { return storage.access
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)
});
} }
// 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) { // send ping to server, return response
browserType.storage.local.set(request, function() { async function verifyConnection() {
console.log("Stored history: " + JSON.stringify(request));
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));
}); });
} else if (request.download) { }
// send download task to server, return response
async function downloadLink(toDownload) {
const path = "api/download/";
let payload = { let payload = {
"data": [ "data": [
{ {
"youtube_id": request.download["url"], "youtube_id": toDownload,
"status": "pending", "status": "pending",
} }
] ]
} }
console.log(payload); let access = await getAccess();
forwardRequest(payload); 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;
} }
); );

View File

@ -8,10 +8,8 @@ let browserType = getBrowser();
function getBrowser() { function getBrowser() {
if (typeof chrome !== "undefined") { if (typeof chrome !== "undefined") {
if (typeof browser !== "undefined") { if (typeof browser !== "undefined") {
console.log("detected firefox");
return browser; return browser;
} else { } else {
console.log("detected chrome");
return chrome; return chrome;
} }
} else { } else {
@ -20,9 +18,9 @@ function getBrowser() {
}; };
} }
// store access details // store access details
document.getElementById("save-login").addEventListener("click", function () { document.getElementById("save-login").addEventListener("click", function () {
console.log("save form");
let toStore = { let toStore = {
"access": { "access": {
"url": document.getElementById("url").value, "url": document.getElementById("url").value,
@ -30,20 +28,49 @@ document.getElementById("save-login").addEventListener("click", function () {
"apiKey": document.getElementById("api-key").value "apiKey": document.getElementById("api-key").value
} }
}; };
console.log(toStore);
browserType.storage.local.set(toStore, function() { browserType.storage.local.set(toStore, function() {
console.log("Stored connection details: " + JSON.stringify(toStore)); 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) { function setStatusIcon(connected) {
let statusIcon = document.getElementById("status-icon") let statusIcon = document.getElementById("status-icon")
if (connected == true) { if (connected == true) {
console.log("connected"); statusIcon.innerHTML = "☑";
statusIcon.style.color = "green";
} else { } else {
console.log("not connected");
statusIcon.innerHTML = "☒"; statusIcon.innerHTML = "☒";
statusIcon.style.color = "red"; 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 // fill in form
document.addEventListener("DOMContentLoaded", async () => { document.addEventListener("DOMContentLoaded", async () => {
console.log("executing dom loader");
function onGot(item) { function onGot(item) {
if (!item.access) { if (!item.access) {
console.log("no access details found"); console.log("no access details found");
setStatusIcon(false); setStatusIcon(false);
return return
} }
console.log(item.access);
document.getElementById("url").value = item.access.url; document.getElementById("url").value = item.access.url;
document.getElementById("port").value = item.access.port; document.getElementById("port").value = item.access.port;
document.getElementById("api-key").value = item.access.apiKey; document.getElementById("api-key").value = item.access.apiKey;
pingBackend();
}; };
function onError(error) { function onError(error) {
@ -83,7 +132,7 @@ document.addEventListener("DOMContentLoaded", async () => {
}) })
function downlodButton(result) { function downlodButton(result) {
console.log("running build dl button");
let download = document.getElementById("download"); let download = document.getElementById("download");
let title = document.createElement("p"); let title = document.createElement("p");
title.innerText = result.youtube.title; title.innerText = result.youtube.title;
@ -93,17 +142,8 @@ function downlodButton(result) {
button.id = "downloadButton"; button.id = "downloadButton";
button.setAttribute("data-id", result.youtube.url); 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(title);
download.appendChild(button); download.appendChild(button);
download.appendChild(document.createElement("hr")); download.appendChild(document.createElement("hr"));
} }

View File

@ -2,8 +2,6 @@
content script running on youtube.com content script running on youtube.com
*/ */
console.log("running script.js");
let browserType = getBrowser(); let browserType = getBrowser();
@ -25,7 +23,6 @@ function getBrowser() {
function sendUrl() { function sendUrl() {
console.log("run sendUrl from script.js");
let payload = { let payload = {
"youtube": { "youtube": {
@ -33,7 +30,7 @@ function sendUrl() {
"title": document.title "title": document.title
} }
} }
console.log(JSON.stringify(payload)); console.log("youtube link: " + JSON.stringify(payload));
browserType.runtime.sendMessage(payload, function(response) { browserType.runtime.sendMessage(payload, function(response) {
console.log(response.farewell); console.log(response.farewell);
}); });
@ -42,7 +39,6 @@ function sendUrl() {
document.addEventListener("yt-navigate-finish", function (event) { document.addEventListener("yt-navigate-finish", function (event) {
console.log("running setimeout")
setTimeout(function(){ setTimeout(function(){
sendUrl(); sendUrl();
return false; return false;