Move requesting logic to shared lib

This commit is contained in:
Ajay
2023-02-14 01:20:46 -05:00
parent 5ecb809c73
commit 8c994f362d
7 changed files with 20 additions and 111 deletions

14
package-lock.json generated
View File

@@ -27,7 +27,7 @@
], ],
"license": "LGPL-3.0-or-later", "license": "LGPL-3.0-or-later",
"dependencies": { "dependencies": {
"@ajayyy/maze-utils": "^1.1.0", "@ajayyy/maze-utils": "^1.1.2",
"content-scripts-register-polyfill": "^4.0.2", "content-scripts-register-polyfill": "^4.0.2",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0" "react-dom": "^18.2.0"
@@ -68,9 +68,9 @@
} }
}, },
"node_modules/@ajayyy/maze-utils": { "node_modules/@ajayyy/maze-utils": {
"version": "1.1.0", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/@ajayyy/maze-utils/-/maze-utils-1.1.0.tgz", "resolved": "https://registry.npmjs.org/@ajayyy/maze-utils/-/maze-utils-1.1.2.tgz",
"integrity": "sha512-Dc63B4Qbad14R590837b1ST0WFT8wWy4YFUmwheMiVABiG+G2m7o6wdq7Ln12pT/QUQO6h4/oKijEF3/ojXDVg==", "integrity": "sha512-hz8+ONJMnkX3q1XHzN2JEmmg4otsEr88SbnH2Oq35WfWuaGnjsm5VVowEZeAoEd/7ELxD+Mhk+rGZLMzSHXbqQ==",
"funding": [ "funding": [
{ {
"type": "individual", "type": "individual",
@@ -13420,9 +13420,9 @@
}, },
"dependencies": { "dependencies": {
"@ajayyy/maze-utils": { "@ajayyy/maze-utils": {
"version": "1.1.0", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/@ajayyy/maze-utils/-/maze-utils-1.1.0.tgz", "resolved": "https://registry.npmjs.org/@ajayyy/maze-utils/-/maze-utils-1.1.2.tgz",
"integrity": "sha512-Dc63B4Qbad14R590837b1ST0WFT8wWy4YFUmwheMiVABiG+G2m7o6wdq7Ln12pT/QUQO6h4/oKijEF3/ojXDVg==" "integrity": "sha512-hz8+ONJMnkX3q1XHzN2JEmmg4otsEr88SbnH2Oq35WfWuaGnjsm5VVowEZeAoEd/7ELxD+Mhk+rGZLMzSHXbqQ=="
}, },
"@ampproject/remapping": { "@ampproject/remapping": {
"version": "2.2.0", "version": "2.2.0",

View File

@@ -4,7 +4,7 @@
"description": "", "description": "",
"main": "background.js", "main": "background.js",
"dependencies": { "dependencies": {
"@ajayyy/maze-utils": "^1.1.0", "@ajayyy/maze-utils": "^1.1.2",
"content-scripts-register-polyfill": "^4.0.2", "content-scripts-register-polyfill": "^4.0.2",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0" "react-dom": "^18.2.0"

View File

@@ -10,6 +10,7 @@ window.SB = Config;
import Utils from "./utils"; import Utils from "./utils";
import { GenericUtils } from "./utils/genericUtils"; import { GenericUtils } from "./utils/genericUtils";
import { sendRealRequestToCustomServer, setupBackgroundRequestProxy } from "@ajayyy/maze-utils/lib/background-request-proxy";
const utils = new Utils({ const utils = new Utils({
registerFirefoxContentScript, registerFirefoxContentScript,
unregisterFirefoxContentScript unregisterFirefoxContentScript
@@ -25,34 +26,7 @@ utils.wait(() => Config.config !== null).then(function() {
if (Config.config.supportInvidious) utils.setupExtraSiteContentScripts(); if (Config.config.supportInvidious) utils.setupExtraSiteContentScripts();
}); });
function onTabUpdatedListener(tabId: number) { setupBackgroundRequestProxy();
chrome.tabs.sendMessage(tabId, {
message: 'update',
}, () => void chrome.runtime.lastError ); // Suppress error on Firefox
}
function onNavigationApiAvailableChange(changes: {[key: string]: chrome.storage.StorageChange}) {
if (changes.navigationApiAvailable) {
if (changes.navigationApiAvailable.newValue) {
chrome.tabs.onUpdated.removeListener(onTabUpdatedListener);
} else {
chrome.tabs.onUpdated.addListener(onTabUpdatedListener);
}
}
}
// If Navigation API is not supported, then background has to inform content script about video change.
// This happens on Safari, Firefox, and Chromium 101 (inclusive) and below.
chrome.tabs.onUpdated.addListener(onTabUpdatedListener);
utils.wait(() => Config.local !== null).then(() => {
if (Config.local.navigationApiAvailable) {
chrome.tabs.onUpdated.removeListener(onTabUpdatedListener);
}
});
if (!Config.configSyncListeners.includes(onNavigationApiAvailableChange)) {
Config.configSyncListeners.push(onNavigationApiAvailableChange);
}
chrome.runtime.onMessage.addListener(function (request, sender, callback) { chrome.runtime.onMessage.addListener(function (request, sender, callback) {
switch(request.message) { switch(request.message) {
@@ -68,16 +42,6 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) {
case "openPage": case "openPage":
chrome.tabs.create({url: chrome.runtime.getURL(request.url)}); chrome.tabs.create({url: chrome.runtime.getURL(request.url)});
return false; return false;
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 "submitVote": case "submitVote":
submitVote(request.type, request.UUID, request.category).then(callback); submitVote(request.type, request.UUID, request.category).then(callback);
@@ -222,35 +186,9 @@ async function submitVote(type: number, UUID: string, category: string) {
} }
} }
async function asyncRequestToServer(type: string, address: string, data = {}) { async function asyncRequestToServer(type: string, address: string, data = {}) {
const serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress; const serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress;
return await (sendRequestToCustomServer(type, serverAddress + address, data)); return await (sendRealRequestToCustomServer(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") {
url = GenericUtils.objectToURI(url, data, true);
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

@@ -26,12 +26,6 @@ export interface ContentContainer {
}; };
} }
export interface FetchResponse {
responseText: string;
status: number;
ok: boolean;
}
export type HashedValue = string & { __hashBrand: unknown }; export type HashedValue = string & { __hashBrand: unknown };
export interface VideoDurationResponse { export interface VideoDurationResponse {

View File

@@ -1,10 +1,11 @@
import Config, { VideoDownvotes } from "./config"; import Config, { VideoDownvotes } from "./config";
import { CategorySelection, SponsorTime, FetchResponse, BackgroundScriptContainer, Registration, HashedValue, VideoID, SponsorHideType } from "./types"; import { CategorySelection, SponsorTime, BackgroundScriptContainer, Registration, HashedValue, VideoID, SponsorHideType } from "./types";
import * as CompileConfig from "../config.json"; import * as CompileConfig from "../config.json";
import { waitFor } from "@ajayyy/maze-utils"; import { waitFor } from "@ajayyy/maze-utils";
import { isSafari } from "./utils/configUtils"; import { isSafari } from "./utils/configUtils";
import { findValidElementFromSelector } from "@ajayyy/maze-utils/lib/dom"; import { findValidElementFromSelector } from "@ajayyy/maze-utils/lib/dom";
import { FetchResponse, sendRequestToCustomServer } from "@ajayyy/maze-utils/lib/background-request-proxy"
export default class Utils { export default class Utils {
@@ -251,18 +252,8 @@ export default 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 = {}): Promise<FetchResponse> { asyncRequestToCustomServer(type: string, url: string, data = {}): Promise<FetchResponse> {
return new Promise((resolve) => { return sendRequestToCustomServer(type, url, data);
// Ask the background script to do the work
chrome.runtime.sendMessage({
message: "sendRequest",
type,
url,
data
}, (response) => {
resolve(response);
});
});
} }
/** /**

View File

@@ -49,19 +49,6 @@ function indexesOf<T>(array: T[], value: T): number[] {
return array.map((v, i) => v === value ? i : -1).filter(i => i !== -1); return array.map((v, i) => v === value ? i : -1).filter(i => i !== -1);
} }
function objectToURI<T>(url: string, data: T, includeQuestionMark: boolean): string {
let counter = 0;
for (const key in data) {
const seperator = (url.includes("?") || counter > 0) ? "&" : (includeQuestionMark ? "?" : "");
const value = (typeof(data[key]) === "string") ? data[key] as unknown as string : JSON.stringify(data[key]);
url += seperator + encodeURIComponent(key) + "=" + encodeURIComponent(value);
counter++;
}
return url;
}
function generateUserID(length = 36): string { function generateUserID(length = 36): string {
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = ""; let result = "";
@@ -84,6 +71,5 @@ export const GenericUtils = {
getErrorMessage, getErrorMessage,
getLuminance, getLuminance,
generateUserID, generateUserID,
indexesOf, indexesOf
objectToURI
} }

View File

@@ -1,8 +1,8 @@
import { objectToURI } from "@ajayyy/maze-utils";
import Config from "../config"; import Config from "../config";
import GenericNotice, { NoticeOptions } from "../render/GenericNotice"; import GenericNotice, { NoticeOptions } from "../render/GenericNotice";
import { ContentContainer } from "../types"; import { ContentContainer } from "../types";
import Utils from "../utils"; import Utils from "../utils";
import { GenericUtils } from "./genericUtils";
const utils = new Utils(); const utils = new Utils();
export interface ChatConfig { export interface ChatConfig {
@@ -62,5 +62,5 @@ export async function openWarningDialog(contentContainer: ContentContainer): Pro
} }
export function openChat(config: ChatConfig): void { export function openChat(config: ChatConfig): void {
window.open("https://chat.sponsor.ajay.app/#" + GenericUtils.objectToURI("", config, false)); window.open("https://chat.sponsor.ajay.app/#" + objectToURI("", config, false));
} }