Moved requests to the background script.

This should avoid ad blockers messing with requests.

Helps with https://github.com/ajayyy/SponsorBlock/issues/354
This commit is contained in:
Ajay Ramachandran
2020-05-24 22:42:55 -04:00
parent f165b3b602
commit 39155fdf99
6 changed files with 120 additions and 86 deletions

View File

@@ -1,4 +1,4 @@
import * as Types from "./types"; import * as CompileConfig from "../config.json";
import Config from "./config"; import Config from "./config";
// Make the config public for debugging purposes // Make the config public for debugging purposes
@@ -30,7 +30,17 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) {
switch(request.message) { switch(request.message) {
case "openConfig": case "openConfig":
chrome.runtime.openOptionsPage(); 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": case "addSponsorTime":
addSponsorTime(request.time, request.videoID, callback); 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 //this allows the callback to be called later
return true; return true;
case "submitVote": 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 //this allows the callback to be called later
return true; 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; let userID = Config.config.userID;
if (userID == undefined || userID === "undefined") { if (userID == undefined || userID === "undefined") {
@@ -159,24 +169,60 @@ function submitVote(type, UUID, category, callback) {
let typeSection = (type !== undefined) ? "&type=" + type : "&category=" + category; let typeSection = (type !== undefined) ? "&type=" + type : "&category=" + category;
//publish this vote //publish this vote
utils.sendRequestToServer("POST", "/api/voteOnSponsorTime?UUID=" + UUID + "&userID=" + userID + typeSection, function(xmlhttp, error) { let response = await asyncRequestToServer("POST", "/api/voteOnSponsorTime?UUID=" + UUID + "&userID=" + userID + typeSection);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback({ if (response.ok) {
successType: 1 return {
}); successType: 1
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 405) { };
//duplicate vote } else if (response.status == 405) {
callback({ //duplicate vote
successType: 0, return {
statusCode: xmlhttp.status successType: 0,
}); statusCode: response.status
} else if (error) { };
//error while connect } else {
callback({ //error while connect
successType: -1, return {
statusCode: xmlhttp.status 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;
} }

View File

@@ -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"); let response = await utils.asyncRequestToCustomServer("GET", "https://sponsor.ajay.app/invidious/api/v1/channels/" + item.split("/")[2] + "?fields=authorId");
if (response.ok) { if (response.ok) {
newChannelList.push((await response.json()).authorId); newChannelList.push((JSON.parse(response.responseText)).authorId);
} else { } else {
// Add it at the beginning so it gets converted later // Add it at the beginning so it gets converted later
newChannelList.unshift(item); newChannelList.unshift(item);

View File

@@ -1,6 +1,6 @@
import Config from "./config"; 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 { ContentContainer } from "./types";
import Utils from "./utils"; import Utils from "./utils";
@@ -615,9 +615,9 @@ function sponsorsLookup(id: string) {
utils.asyncRequestToServer('GET', "/api/skipSegments", { utils.asyncRequestToServer('GET', "/api/skipSegments", {
videoID: id, videoID: id,
categories categories
}).then(async (response: Response) => { }).then(async (response: FetchResponse) => {
if (response.status === 200) { if (response.ok) {
let recievedSegments: SponsorTime[] = await response.json(); let recievedSegments: SponsorTime[] = JSON.parse(response.responseText);
if (!recievedSegments.length) { if (!recievedSegments.length) {
console.error("[SponsorBlock] Server returned malformed response: " + JSON.stringify(recievedSegments)); console.error("[SponsorBlock] Server returned malformed response: " + JSON.stringify(recievedSegments));
return; return;
@@ -984,7 +984,7 @@ function skipToTime(v: HTMLVideoElement, skipTime: number[], skippingSegments: S
for (const segment of skippingSegments) { for (const segment of skippingSegments) {
let index = sponsorTimes.indexOf(segment); let index = sponsorTimes.indexOf(segment);
if (index !== -1 && !sponsorSkipped[index]) { if (index !== -1 && !sponsorSkipped[index]) {
utils.sendRequestToServer("POST", "/api/viewedVideoSponsorTime?UUID=" + segment.UUID); utils.asyncRequestToServer("POST", "/api/viewedVideoSponsorTime?UUID=" + segment.UUID);
sponsorSkipped[index] = true; sponsorSkipped[index] = true;
} else if (sponsorSkipped[index]) { } else if (sponsorSkipped[index]) {
@@ -1507,7 +1507,7 @@ async function sendSubmitMessage(){
document.getElementById("submitButton").style.animation = "unset"; document.getElementById("submitButton").style.animation = "unset";
(<HTMLImageElement> document.getElementById("submitImage")).src = chrome.extension.getURL("icons/PlayerUploadFailedIconSponsorBlocker256px.png"); (<HTMLImageElement> 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));
} }
} }

View File

@@ -168,9 +168,9 @@ async function runThePopup(messageListener?: MessageListener) {
if (userID != undefined) { if (userID != undefined) {
//there are probably some views on these submissions then //there are probably some views on these submissions then
//get the amount of views from the sponsors submitted //get the amount of views from the sponsors submitted
utils.sendRequestToServer("GET", "/api/getViewsForUser?userID=" + userID, function(xmlhttp) { utils.sendRequestToServer("GET", "/api/getViewsForUser?userID=" + userID, function(response) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { if (response.status == 200) {
let viewCount = JSON.parse(xmlhttp.responseText).viewCount; let viewCount = JSON.parse(response.responseText).viewCount;
if (viewCount != 0) { if (viewCount != 0) {
if (viewCount > 1) { if (viewCount > 1) {
PageElements.sponsorTimesViewsDisplayEndWord.innerText = chrome.i18n.getMessage("Segments"); PageElements.sponsorTimesViewsDisplayEndWord.innerText = chrome.i18n.getMessage("Segments");
@@ -185,9 +185,9 @@ async function runThePopup(messageListener?: MessageListener) {
}); });
//get this time in minutes //get this time in minutes
utils.sendRequestToServer("GET", "/api/getSavedTimeForUser?userID=" + userID, function(xmlhttp) { utils.sendRequestToServer("GET", "/api/getSavedTimeForUser?userID=" + userID, function(response) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { if (response.status == 200) {
let minutesSaved = JSON.parse(xmlhttp.responseText).timeSaved; let minutesSaved = JSON.parse(response.responseText).timeSaved;
if (minutesSaved != 0) { if (minutesSaved != 0) {
if (minutesSaved != 1) { if (minutesSaved != 1) {
PageElements.sponsorTimesOthersTimeSavedEndWord.innerText = chrome.i18n.getMessage("minsLower"); PageElements.sponsorTimesOthersTimeSavedEndWord.innerText = chrome.i18n.getMessage("minsLower");
@@ -797,9 +797,9 @@ async function runThePopup(messageListener?: MessageListener) {
//make the options username setting option visible //make the options username setting option visible
function setUsernameButton() { function setUsernameButton() {
//get username from the server //get username from the server
utils.sendRequestToServer("GET", "/api/getUsername?userID=" + Config.config.userID, function (xmlhttp, error) { utils.sendRequestToServer("GET", "/api/getUsername?userID=" + Config.config.userID, function (response) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { if (response.status == 200) {
PageElements.usernameInput.value = JSON.parse(xmlhttp.responseText).userName; PageElements.usernameInput.value = JSON.parse(response.responseText).userName;
PageElements.submitUsername.style.display = "unset"; PageElements.submitUsername.style.display = "unset";
PageElements.usernameInput.style.display = "unset"; PageElements.usernameInput.style.display = "unset";
@@ -808,13 +808,13 @@ async function runThePopup(messageListener?: MessageListener) {
PageElements.setUsername.style.display = "unset"; PageElements.setUsername.style.display = "unset";
PageElements PageElements
PageElements.setUsernameStatusContainer.style.display = "none"; PageElements.setUsernameStatusContainer.style.display = "none";
} else if (xmlhttp.readyState == 4) { } else {
PageElements.setUsername.style.display = "unset"; PageElements.setUsername.style.display = "unset";
PageElements.submitUsername.style.display = "none"; PageElements.submitUsername.style.display = "none";
PageElements.usernameInput.style.display = "none"; PageElements.usernameInput.style.display = "none";
PageElements.setUsernameStatusContainer.style.display = "unset"; 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..."; PageElements.setUsernameStatus.innerText = "Loading...";
//get the userID //get the userID
utils.sendRequestToServer("POST", "/api/setUsername?userID=" + Config.config.userID + "&username=" + PageElements.usernameInput.value, function (xmlhttp, error) { utils.sendRequestToServer("POST", "/api/setUsername?userID=" + Config.config.userID + "&username=" + PageElements.usernameInput.value, function (response) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { if (response.status == 200) {
//submitted //submitted
PageElements.submitUsername.style.display = "none"; PageElements.submitUsername.style.display = "none";
PageElements.usernameInput.style.display = "none"; PageElements.usernameInput.style.display = "none";
PageElements.setUsernameStatus.innerText = chrome.i18n.getMessage("success"); PageElements.setUsernameStatus.innerText = chrome.i18n.getMessage("success");
} else if (xmlhttp.readyState == 4) { } else {
PageElements.setUsernameStatus.innerText = utils.getErrorMessage(xmlhttp.status); PageElements.setUsernameStatus.innerText = utils.getErrorMessage(response.status);
} }
}); });

View File

@@ -22,6 +22,12 @@ interface ContentContainer {
} }
} }
interface FetchResponse {
responseText: string,
status: number,
ok: boolean
}
interface VideoDurationResponse { interface VideoDurationResponse {
duration: number; duration: number;
} }
@@ -55,6 +61,7 @@ interface SponsorTime {
type VideoID = string; type VideoID = string;
export { export {
FetchResponse,
VideoDurationResponse, VideoDurationResponse,
ContentContainer, ContentContainer,
CategorySelection, CategorySelection,

View File

@@ -1,5 +1,5 @@
import Config from "./config"; import Config from "./config";
import { CategorySelection, SponsorTime } from "./types"; import { CategorySelection, SponsorTime, FetchResponse } from "./types";
import * as CompileConfig from "../config.json"; import * as CompileConfig from "../config.json";
@@ -276,29 +276,18 @@ class Utils {
* @param address The address to add to the SponsorBlock server address * @param address The address to add to the SponsorBlock server address
* @param callback * @param callback
*/ */
async asyncRequestToCustomServer(type: string, url: string, data = {}) { async asyncRequestToCustomServer(type: string, url: string, data = {}): Promise<FetchResponse> {
return new Promise((resolve) => {
// If GET, convert JSON to parameters // Ask the background script to do the work
if (type.toLowerCase() === "get") { chrome.runtime.sendMessage({
for (const key in data) { message: "sendRequest",
let seperator = url.includes("?") ? "&" : "?"; type,
let value = (typeof(data[key]) === "string") ? data[key]: JSON.stringify(data[key]); url,
url += seperator + key + "=" + value; data
} }, (response) => {
resolve(response);
data = null; });
} })
const response = await fetch(url, {
method: type,
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
body: data ? JSON.stringify(data) : null
});
return response;
} }
/** /**
@@ -308,7 +297,7 @@ class Utils {
* @param address The address to add to the SponsorBlock server address * @param address The address to add to the SponsorBlock server address
* @param callback * @param callback
*/ */
async asyncRequestToServer(type: string, address: string, data = {}) { async asyncRequestToServer(type: string, address: string, data = {}): Promise<FetchResponse> {
let serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress; let serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress;
return await (this.asyncRequestToCustomServer(type, serverAddress + address, data)); 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 address The address to add to the SponsorBlock server address
* @param callback * @param callback
*/ */
sendRequestToServer(type: string, address: string, callback?: (xmlhttp: XMLHttpRequest, err: boolean) => any) { sendRequestToServer(type: string, address: string, callback?: (response: FetchResponse) => void) {
let xmlhttp = new XMLHttpRequest();
let serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress; let serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress;
xmlhttp.open(type, serverAddress + address, true); // Ask the background script to do the work
chrome.runtime.sendMessage({
if (callback != undefined) { message: "sendRequest",
xmlhttp.onreadystatechange = function () { type,
callback(xmlhttp, false); url: serverAddress + address
}; }, (response) => {
callback(response);
xmlhttp.onerror = function(ev) { });
callback(xmlhttp, true);
};
}
//submit this request
xmlhttp.send();
} }
getFormattedMinutes(seconds: number) { getFormattedMinutes(seconds: number) {