diff --git a/src/background.ts b/src/background.ts index 74382357..0c11ab06 100644 --- a/src/background.ts +++ b/src/background.ts @@ -1,4 +1,4 @@ -import * as Types from "./types"; +import * as CompileConfig from "../config.json"; import Config from "./config"; // Make the config public for debugging purposes @@ -30,7 +30,17 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) { switch(request.message) { case "openConfig": chrome.runtime.openOptionsPage(); - return + return; + case "sendRequest": + sendRequestToCustomServer(request.type, request.url, request.data).then(async (response) => { + callback({ + responseText: await response.text(), + status: response.status, + ok: response.ok + }); + }); + + return true; case "addSponsorTime": addSponsorTime(request.time, request.videoID, callback); @@ -47,7 +57,7 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) { //this allows the callback to be called later return true; case "submitVote": - submitVote(request.type, request.UUID, request.category, callback); + submitVote(request.type, request.UUID, request.category).then(callback); //this allows the callback to be called later return true; @@ -147,7 +157,7 @@ function addSponsorTime(time, videoID, callback) { }); } -function submitVote(type, UUID, category, callback) { +async function submitVote(type: number, UUID: string, category: string) { let userID = Config.config.userID; if (userID == undefined || userID === "undefined") { @@ -159,24 +169,60 @@ function submitVote(type, UUID, category, callback) { let typeSection = (type !== undefined) ? "&type=" + type : "&category=" + category; //publish this vote - utils.sendRequestToServer("POST", "/api/voteOnSponsorTime?UUID=" + UUID + "&userID=" + userID + typeSection, function(xmlhttp, error) { - if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { - callback({ - successType: 1 - }); - } else if (xmlhttp.readyState == 4 && xmlhttp.status == 405) { - //duplicate vote - callback({ - successType: 0, - statusCode: xmlhttp.status - }); - } else if (error) { - //error while connect - callback({ - successType: -1, - statusCode: xmlhttp.status - }); + let response = await asyncRequestToServer("POST", "/api/voteOnSponsorTime?UUID=" + UUID + "&userID=" + userID + typeSection); + + if (response.ok) { + return { + successType: 1 + }; + } else if (response.status == 405) { + //duplicate vote + return { + successType: 0, + statusCode: response.status + }; + } else { + //error while connect + return { + successType: -1, + statusCode: response.status + }; + } +} + +async function asyncRequestToServer(type: string, address: string, data = {}) { + let serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress; + + return await (sendRequestToCustomServer(type, serverAddress + address, data)); +} + +/** + * Sends a request to the specified url + * + * @param type The request type "GET", "POST", etc. + * @param address The address to add to the SponsorBlock server address + * @param callback + */ +async function sendRequestToCustomServer(type: string, url: string, data = {}) { + // If GET, convert JSON to parameters + if (type.toLowerCase() === "get") { + for (const key in data) { + let seperator = url.includes("?") ? "&" : "?"; + let value = (typeof(data[key]) === "string") ? data[key]: JSON.stringify(data[key]); + url += seperator + key + "=" + value; } + data = null; + } + + const response = await fetch(url, { + method: type, + headers: { + 'Content-Type': 'application/json' + }, + redirect: 'follow', + body: data ? JSON.stringify(data) : null }); + + return response; } \ No newline at end of file diff --git a/src/config.ts b/src/config.ts index d26859ec..1b0a56d1 100644 --- a/src/config.ts +++ b/src/config.ts @@ -268,7 +268,7 @@ async function migrateOldFormats() { let response = await utils.asyncRequestToCustomServer("GET", "https://sponsor.ajay.app/invidious/api/v1/channels/" + item.split("/")[2] + "?fields=authorId"); if (response.ok) { - newChannelList.push((await response.json()).authorId); + newChannelList.push((JSON.parse(response.responseText)).authorId); } else { // Add it at the beginning so it gets converted later newChannelList.unshift(item); diff --git a/src/content.ts b/src/content.ts index 9aae0f02..b86fa332 100644 --- a/src/content.ts +++ b/src/content.ts @@ -1,6 +1,6 @@ import Config from "./config"; -import { SponsorTime, CategorySkipOption, CategorySelection, VideoID, SponsorHideType } from "./types"; +import { SponsorTime, CategorySkipOption, CategorySelection, VideoID, SponsorHideType, FetchResponse } from "./types"; import { ContentContainer } from "./types"; import Utils from "./utils"; @@ -615,9 +615,9 @@ function sponsorsLookup(id: string) { utils.asyncRequestToServer('GET', "/api/skipSegments", { videoID: id, categories - }).then(async (response: Response) => { - if (response.status === 200) { - let recievedSegments: SponsorTime[] = await response.json(); + }).then(async (response: FetchResponse) => { + if (response.ok) { + let recievedSegments: SponsorTime[] = JSON.parse(response.responseText); if (!recievedSegments.length) { console.error("[SponsorBlock] Server returned malformed response: " + JSON.stringify(recievedSegments)); return; @@ -984,7 +984,7 @@ function skipToTime(v: HTMLVideoElement, skipTime: number[], skippingSegments: S for (const segment of skippingSegments) { let index = sponsorTimes.indexOf(segment); if (index !== -1 && !sponsorSkipped[index]) { - utils.sendRequestToServer("POST", "/api/viewedVideoSponsorTime?UUID=" + segment.UUID); + utils.asyncRequestToServer("POST", "/api/viewedVideoSponsorTime?UUID=" + segment.UUID); sponsorSkipped[index] = true; } else if (sponsorSkipped[index]) { @@ -1507,7 +1507,7 @@ async function sendSubmitMessage(){ document.getElementById("submitButton").style.animation = "unset"; ( document.getElementById("submitImage")).src = chrome.extension.getURL("icons/PlayerUploadFailedIconSponsorBlocker256px.png"); - alert(utils.getErrorMessage(response.status) + "\n\n" + (await response.text())); + alert(utils.getErrorMessage(response.status) + "\n\n" + (response.responseText)); } } diff --git a/src/popup.ts b/src/popup.ts index 914dddc5..e5e3d6ca 100644 --- a/src/popup.ts +++ b/src/popup.ts @@ -168,9 +168,9 @@ async function runThePopup(messageListener?: MessageListener) { if (userID != undefined) { //there are probably some views on these submissions then //get the amount of views from the sponsors submitted - utils.sendRequestToServer("GET", "/api/getViewsForUser?userID=" + userID, function(xmlhttp) { - if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { - let viewCount = JSON.parse(xmlhttp.responseText).viewCount; + utils.sendRequestToServer("GET", "/api/getViewsForUser?userID=" + userID, function(response) { + if (response.status == 200) { + let viewCount = JSON.parse(response.responseText).viewCount; if (viewCount != 0) { if (viewCount > 1) { PageElements.sponsorTimesViewsDisplayEndWord.innerText = chrome.i18n.getMessage("Segments"); @@ -185,9 +185,9 @@ async function runThePopup(messageListener?: MessageListener) { }); //get this time in minutes - utils.sendRequestToServer("GET", "/api/getSavedTimeForUser?userID=" + userID, function(xmlhttp) { - if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { - let minutesSaved = JSON.parse(xmlhttp.responseText).timeSaved; + utils.sendRequestToServer("GET", "/api/getSavedTimeForUser?userID=" + userID, function(response) { + if (response.status == 200) { + let minutesSaved = JSON.parse(response.responseText).timeSaved; if (minutesSaved != 0) { if (minutesSaved != 1) { PageElements.sponsorTimesOthersTimeSavedEndWord.innerText = chrome.i18n.getMessage("minsLower"); @@ -797,9 +797,9 @@ async function runThePopup(messageListener?: MessageListener) { //make the options username setting option visible function setUsernameButton() { //get username from the server - utils.sendRequestToServer("GET", "/api/getUsername?userID=" + Config.config.userID, function (xmlhttp, error) { - if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { - PageElements.usernameInput.value = JSON.parse(xmlhttp.responseText).userName; + utils.sendRequestToServer("GET", "/api/getUsername?userID=" + Config.config.userID, function (response) { + if (response.status == 200) { + PageElements.usernameInput.value = JSON.parse(response.responseText).userName; PageElements.submitUsername.style.display = "unset"; PageElements.usernameInput.style.display = "unset"; @@ -808,13 +808,13 @@ async function runThePopup(messageListener?: MessageListener) { PageElements.setUsername.style.display = "unset"; PageElements PageElements.setUsernameStatusContainer.style.display = "none"; - } else if (xmlhttp.readyState == 4) { + } else { PageElements.setUsername.style.display = "unset"; PageElements.submitUsername.style.display = "none"; PageElements.usernameInput.style.display = "none"; PageElements.setUsernameStatusContainer.style.display = "unset"; - PageElements.setUsernameStatus.innerText = utils.getErrorMessage(xmlhttp.status); + PageElements.setUsernameStatus.innerText = utils.getErrorMessage(response.status); } }); } @@ -826,15 +826,15 @@ async function runThePopup(messageListener?: MessageListener) { PageElements.setUsernameStatus.innerText = "Loading..."; //get the userID - utils.sendRequestToServer("POST", "/api/setUsername?userID=" + Config.config.userID + "&username=" + PageElements.usernameInput.value, function (xmlhttp, error) { - if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { + utils.sendRequestToServer("POST", "/api/setUsername?userID=" + Config.config.userID + "&username=" + PageElements.usernameInput.value, function (response) { + if (response.status == 200) { //submitted PageElements.submitUsername.style.display = "none"; PageElements.usernameInput.style.display = "none"; PageElements.setUsernameStatus.innerText = chrome.i18n.getMessage("success"); - } else if (xmlhttp.readyState == 4) { - PageElements.setUsernameStatus.innerText = utils.getErrorMessage(xmlhttp.status); + } else { + PageElements.setUsernameStatus.innerText = utils.getErrorMessage(response.status); } }); diff --git a/src/types.ts b/src/types.ts index 002f4daf..3bef9248 100644 --- a/src/types.ts +++ b/src/types.ts @@ -22,6 +22,12 @@ interface ContentContainer { } } +interface FetchResponse { + responseText: string, + status: number, + ok: boolean +} + interface VideoDurationResponse { duration: number; } @@ -55,6 +61,7 @@ interface SponsorTime { type VideoID = string; export { + FetchResponse, VideoDurationResponse, ContentContainer, CategorySelection, diff --git a/src/utils.ts b/src/utils.ts index a634112c..f3501b5d 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,5 +1,5 @@ import Config from "./config"; -import { CategorySelection, SponsorTime } from "./types"; +import { CategorySelection, SponsorTime, FetchResponse } from "./types"; import * as CompileConfig from "../config.json"; @@ -276,29 +276,18 @@ class Utils { * @param address The address to add to the SponsorBlock server address * @param callback */ - async asyncRequestToCustomServer(type: string, url: string, data = {}) { - - // If GET, convert JSON to parameters - if (type.toLowerCase() === "get") { - for (const key in data) { - let seperator = url.includes("?") ? "&" : "?"; - let value = (typeof(data[key]) === "string") ? data[key]: JSON.stringify(data[key]); - url += seperator + key + "=" + value; - } - - data = null; - } - - const response = await fetch(url, { - method: type, - headers: { - 'Content-Type': 'application/json' - }, - redirect: 'follow', - body: data ? JSON.stringify(data) : null - }); - - return response; + async asyncRequestToCustomServer(type: string, url: string, data = {}): Promise { + return new Promise((resolve) => { + // Ask the background script to do the work + chrome.runtime.sendMessage({ + message: "sendRequest", + type, + url, + data + }, (response) => { + resolve(response); + }); + }) } /** @@ -308,7 +297,7 @@ class Utils { * @param address The address to add to the SponsorBlock server address * @param callback */ - async asyncRequestToServer(type: string, address: string, data = {}) { + async asyncRequestToServer(type: string, address: string, data = {}): Promise { let serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress; return await (this.asyncRequestToCustomServer(type, serverAddress + address, data)); @@ -321,25 +310,17 @@ class Utils { * @param address The address to add to the SponsorBlock server address * @param callback */ - sendRequestToServer(type: string, address: string, callback?: (xmlhttp: XMLHttpRequest, err: boolean) => any) { - let xmlhttp = new XMLHttpRequest(); - + sendRequestToServer(type: string, address: string, callback?: (response: FetchResponse) => void) { let serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress; - - xmlhttp.open(type, serverAddress + address, true); - - if (callback != undefined) { - xmlhttp.onreadystatechange = function () { - callback(xmlhttp, false); - }; - - xmlhttp.onerror = function(ev) { - callback(xmlhttp, true); - }; - } - - //submit this request - xmlhttp.send(); + + // Ask the background script to do the work + chrome.runtime.sendMessage({ + message: "sendRequest", + type, + url: serverAddress + address + }, (response) => { + callback(response); + }); } getFormattedMinutes(seconds: number) {