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() {
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));
// 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));
});
} else if (request.download) {
}
// send download task to server, return response
async function downloadLink(toDownload) {
const path = "api/download/";
let payload = {
"data": [
{
"youtube_id": request.download["url"],
"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;
}
);

View File

@ -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"));
}

View File

@ -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;