aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorAjay <[email protected]>2023-02-14 01:20:46 -0500
committerAjay <[email protected]>2023-02-14 01:20:46 -0500
commit8c994f362d729ac10c58d438b5f4faf492a7930e (patch)
tree35acf1db4b3fcc2cca59826f3662b5edd77f4bca
parent5ecb809c7331b3321cad15ca8acd1663a0933818 (diff)
downloadSponsorBlock-8c994f362d729ac10c58d438b5f4faf492a7930e.tar.gz
SponsorBlock-8c994f362d729ac10c58d438b5f4faf492a7930e.zip
Move requesting logic to shared lib
-rw-r--r--package-lock.json14
-rw-r--r--package.json2
-rw-r--r--src/background.ts72
-rw-r--r--src/types.ts6
-rw-r--r--src/utils.ts17
-rw-r--r--src/utils/genericUtils.ts16
-rw-r--r--src/utils/warnings.ts4
7 files changed, 20 insertions, 111 deletions
diff --git a/package-lock.json b/package-lock.json
index ac39d095..2e3613fc 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -27,7 +27,7 @@
],
"license": "LGPL-3.0-or-later",
"dependencies": {
- "@ajayyy/maze-utils": "^1.1.0",
+ "@ajayyy/maze-utils": "^1.1.2",
"content-scripts-register-polyfill": "^4.0.2",
"react": "^18.2.0",
"react-dom": "^18.2.0"
@@ -68,9 +68,9 @@
}
},
"node_modules/@ajayyy/maze-utils": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@ajayyy/maze-utils/-/maze-utils-1.1.0.tgz",
- "integrity": "sha512-Dc63B4Qbad14R590837b1ST0WFT8wWy4YFUmwheMiVABiG+G2m7o6wdq7Ln12pT/QUQO6h4/oKijEF3/ojXDVg==",
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@ajayyy/maze-utils/-/maze-utils-1.1.2.tgz",
+ "integrity": "sha512-hz8+ONJMnkX3q1XHzN2JEmmg4otsEr88SbnH2Oq35WfWuaGnjsm5VVowEZeAoEd/7ELxD+Mhk+rGZLMzSHXbqQ==",
"funding": [
{
"type": "individual",
@@ -13420,9 +13420,9 @@
},
"dependencies": {
"@ajayyy/maze-utils": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@ajayyy/maze-utils/-/maze-utils-1.1.0.tgz",
- "integrity": "sha512-Dc63B4Qbad14R590837b1ST0WFT8wWy4YFUmwheMiVABiG+G2m7o6wdq7Ln12pT/QUQO6h4/oKijEF3/ojXDVg=="
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@ajayyy/maze-utils/-/maze-utils-1.1.2.tgz",
+ "integrity": "sha512-hz8+ONJMnkX3q1XHzN2JEmmg4otsEr88SbnH2Oq35WfWuaGnjsm5VVowEZeAoEd/7ELxD+Mhk+rGZLMzSHXbqQ=="
},
"@ampproject/remapping": {
"version": "2.2.0",
diff --git a/package.json b/package.json
index 4a9f3949..2c5e666b 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,7 @@
"description": "",
"main": "background.js",
"dependencies": {
- "@ajayyy/maze-utils": "^1.1.0",
+ "@ajayyy/maze-utils": "^1.1.2",
"content-scripts-register-polyfill": "^4.0.2",
"react": "^18.2.0",
"react-dom": "^18.2.0"
diff --git a/src/background.ts b/src/background.ts
index 682adf49..1720af01 100644
--- a/src/background.ts
+++ b/src/background.ts
@@ -10,6 +10,7 @@ window.SB = Config;
import Utils from "./utils";
import { GenericUtils } from "./utils/genericUtils";
+import { sendRealRequestToCustomServer, setupBackgroundRequestProxy } from "@ajayyy/maze-utils/lib/background-request-proxy";
const utils = new Utils({
registerFirefoxContentScript,
unregisterFirefoxContentScript
@@ -25,34 +26,7 @@ utils.wait(() => Config.config !== null).then(function() {
if (Config.config.supportInvidious) utils.setupExtraSiteContentScripts();
});
-function onTabUpdatedListener(tabId: number) {
- 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);
-}
+setupBackgroundRequestProxy();
chrome.runtime.onMessage.addListener(function (request, sender, callback) {
switch(request.message) {
@@ -68,16 +42,6 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) {
case "openPage":
chrome.tabs.create({url: chrome.runtime.getURL(request.url)});
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":
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 = {}) {
const 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") {
- 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;
-}
+ return await (sendRealRequestToCustomServer(type, serverAddress + address, data));
+} \ No newline at end of file
diff --git a/src/types.ts b/src/types.ts
index 4454d511..b7eff4c0 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -26,12 +26,6 @@ export interface ContentContainer {
};
}
-export interface FetchResponse {
- responseText: string;
- status: number;
- ok: boolean;
-}
-
export type HashedValue = string & { __hashBrand: unknown };
export interface VideoDurationResponse {
diff --git a/src/utils.ts b/src/utils.ts
index 1cdbf73f..dbcbc545 100644
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -1,10 +1,11 @@
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 { waitFor } from "@ajayyy/maze-utils";
import { isSafari } from "./utils/configUtils";
import { findValidElementFromSelector } from "@ajayyy/maze-utils/lib/dom";
+import { FetchResponse, sendRequestToCustomServer } from "@ajayyy/maze-utils/lib/background-request-proxy"
export default class Utils {
@@ -251,18 +252,8 @@ export default class Utils {
* @param address The address to add to the SponsorBlock server address
* @param callback
*/
- async asyncRequestToCustomServer(type: string, url: string, data = {}): Promise<FetchResponse> {
- return new Promise((resolve) => {
- // Ask the background script to do the work
- chrome.runtime.sendMessage({
- message: "sendRequest",
- type,
- url,
- data
- }, (response) => {
- resolve(response);
- });
- });
+ asyncRequestToCustomServer(type: string, url: string, data = {}): Promise<FetchResponse> {
+ return sendRequestToCustomServer(type, url, data);
}
/**
diff --git a/src/utils/genericUtils.ts b/src/utils/genericUtils.ts
index 675f7096..78c481e3 100644
--- a/src/utils/genericUtils.ts
+++ b/src/utils/genericUtils.ts
@@ -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);
}
-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 {
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
@@ -84,6 +71,5 @@ export const GenericUtils = {
getErrorMessage,
getLuminance,
generateUserID,
- indexesOf,
- objectToURI
+ indexesOf
} \ No newline at end of file
diff --git a/src/utils/warnings.ts b/src/utils/warnings.ts
index 17e919ba..0ff3980c 100644
--- a/src/utils/warnings.ts
+++ b/src/utils/warnings.ts
@@ -1,8 +1,8 @@
+import { objectToURI } from "@ajayyy/maze-utils";
import Config from "../config";
import GenericNotice, { NoticeOptions } from "../render/GenericNotice";
import { ContentContainer } from "../types";
import Utils from "../utils";
-import { GenericUtils } from "./genericUtils";
const utils = new Utils();
export interface ChatConfig {
@@ -62,5 +62,5 @@ export async function openWarningDialog(contentContainer: ContentContainer): Pro
}
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));
}