Dedupe & clean up popup -> content script communication code

This commit is contained in:
mini-bomba
2022-10-08 18:58:21 +02:00
parent 78e9f41854
commit 4a3b33cb85
2 changed files with 123 additions and 220 deletions

View File

@@ -83,15 +83,15 @@ interface GetVideoIdResponse {
videoID: string; videoID: string;
} }
interface GetChannelIDResponse { export interface GetChannelIDResponse {
channelID: string; channelID: string;
} }
interface SponsorStartResponse { export interface SponsorStartResponse {
creatingSegment: boolean; creatingSegment: boolean;
} }
interface IsChannelWhitelistedResponse { export interface IsChannelWhitelistedResponse {
value: boolean; value: boolean;
} }
@@ -111,7 +111,7 @@ export interface VoteResponse {
responseText: string; responseText: string;
} }
export interface ImportSegmentsResponse { interface ImportSegmentsResponse {
importedSegments: SponsorTime[]; importedSegments: SponsorTime[];
} }

View File

@@ -10,11 +10,14 @@ import {
StorageChangesObject, StorageChangesObject,
} from "./types"; } from "./types";
import { import {
ImportSegmentsResponse, GetChannelIDResponse,
IsChannelWhitelistedResponse,
IsInfoFoundMessageResponse, IsInfoFoundMessageResponse,
Message, Message,
MessageResponse, MessageResponse,
PopupMessage, PopupMessage,
SponsorStartResponse,
VoteResponse,
} from "./messageTypes"; } from "./messageTypes";
import { showDonationLink } from "./utils/configUtils"; import { showDonationLink } from "./utils/configUtils";
import { AnimationUtils } from "./utils/animationUtils"; import { AnimationUtils } from "./utils/animationUtils";
@@ -425,7 +428,7 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
}, (tabs) => onTabs(tabs, updating)); }, (tabs) => onTabs(tabs, updating));
} }
function infoFound(request: IsInfoFoundMessageResponse) { async function infoFound(request: IsInfoFoundMessageResponse) {
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
//This page doesn't have the injected content script, or at least not yet //This page doesn't have the injected content script, or at least not yet
displayNoVideo(); displayNoVideo();
@@ -455,35 +458,18 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
} }
//see if whitelist button should be swapped //see if whitelist button should be swapped
messageHandler.query({ const response = await sendTabMessageAsync({ message: 'isChannelWhitelisted' }) as IsChannelWhitelistedResponse;
active: true,
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id,
{ message: 'isChannelWhitelisted' },
function (response) {
if (response.value) { if (response.value) {
PageElements.whitelistChannel.style.display = "none"; PageElements.whitelistChannel.style.display = "none";
PageElements.unwhitelistChannel.style.display = "unset"; PageElements.unwhitelistChannel.style.display = "unset";
PageElements.whitelistToggle.checked = true; PageElements.whitelistToggle.checked = true;
document.querySelectorAll('.SBWhitelistIcon')[0].classList.add("rotated"); document.querySelectorAll('.SBWhitelistIcon')[0].classList.add("rotated");
} }
});
}
);
} }
function sendSponsorStartMessage() { async function sendSponsorStartMessage() {
//the content script will get the message if a YouTube page is open //the content script will get the message if a YouTube page is open
messageHandler.query({ const response = await sendTabMessageAsync({ from: 'popup', message: 'sponsorStart' }) as SponsorStartResponse;
active: true,
currentWindow: true,
}, (tabs) => {
messageHandler.sendMessage(
tabs[0].id,
{ from: 'popup', message: 'sponsorStart' },
async (response) => {
startSponsorCallback(response); startSponsorCallback(response);
// Perform a second update after the config changes take effect as a workaround for a race condition // Perform a second update after the config changes take effect as a workaround for a race condition
@@ -501,12 +487,9 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
// Remove the listener after 200ms in case the changes were propagated by the time we got the response // Remove the listener after 200ms in case the changes were propagated by the time we got the response
setTimeout(() => removeListener(lateUpdate), 200); setTimeout(() => removeListener(lateUpdate), 200);
},
);
});
} }
function startSponsorCallback(response: { creatingSegment: boolean }) { function startSponsorCallback(response: SponsorStartResponse) {
creatingSegment = response.creatingSegment; creatingSegment = response.creatingSegment;
// Only update the segments after a segment was created // Only update the segments after a segment was created
@@ -687,19 +670,11 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
downloadedTimes[i].hidden = SponsorHideType.Hidden; downloadedTimes[i].hidden = SponsorHideType.Hidden;
} }
messageHandler.query({ sendTabMessage({
active: true,
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id,
{
message: "hideSegment", message: "hideSegment",
type: downloadedTimes[i].hidden, type: downloadedTimes[i].hidden,
UUID: UUID UUID: UUID
} })
);
});
}); });
const skipButton = document.createElement("img"); const skipButton = document.createElement("img");
@@ -743,15 +718,7 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
function submitTimes() { function submitTimes() {
if (sponsorTimes.length > 0) { if (sponsorTimes.length > 0) {
messageHandler.query({ sendTabMessage({ message: 'submitTimes' })
active: true,
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id,
{ message: 'submitTimes' },
);
});
} }
} }
@@ -782,8 +749,7 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
chrome.runtime.sendMessage({ "message": "openHelp" }); chrome.runtime.sendMessage({ "message": "openHelp" });
} }
function sendTabMessage(data: Message): Promise<unknown> { function sendTabMessage(data: Message, callback?) {
return new Promise((resolve) => {
messageHandler.query({ messageHandler.query({
active: true, active: true,
currentWindow: true currentWindow: true
@@ -791,11 +757,14 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
messageHandler.sendMessage( messageHandler.sendMessage(
tabs[0].id, tabs[0].id,
data, data,
(response) => resolve(response) callback
); );
} }
); );
}); }
function sendTabMessageAsync(data: Message): Promise<unknown> {
return new Promise((resolve) => sendTabMessage(data, (response) => resolve(response)))
} }
//make the options username setting option visible //make the options username setting option visible
@@ -872,21 +841,15 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
thanksForVotingText.removeAttribute("innerText"); thanksForVotingText.removeAttribute("innerText");
} }
function vote(type, UUID) { async function vote(type, UUID) {
//add loading info //add loading info
addVoteMessage(chrome.i18n.getMessage("Loading"), UUID); addVoteMessage(chrome.i18n.getMessage("Loading"), UUID);
const response = await sendTabMessageAsync({
messageHandler.query({
active: true,
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id,
{
message: "submitVote", message: "submitVote",
type: type, type: type,
UUID: UUID UUID: UUID
}, function (response) { }) as VoteResponse;
if (response != undefined) { if (response != undefined) {
//see if it was a success or failure //see if it was a success or failure
if (response.successType == 1 || (response.successType == -1 && response.statusCode == 429)) { if (response.successType == 1 || (response.successType == -1 && response.statusCode == 429)) {
@@ -898,20 +861,10 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
setTimeout(() => removeVoteMessage(UUID), 1500); setTimeout(() => removeVoteMessage(UUID), 1500);
} }
} }
);
});
}
function whitelistChannel() { async function whitelistChannel() {
//get the channel url //get the channel url
messageHandler.query({ const response = await sendTabMessageAsync({ message: 'getChannelID' }) as GetChannelIDResponse;
active: true,
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id,
{ message: 'getChannelID' },
function (response) {
if (!response.channelID) { if (!response.channelID) {
alert(chrome.i18n.getMessage("channelDataNotFound") + " https://github.com/ajayyy/SponsorBlock/issues/753"); alert(chrome.i18n.getMessage("channelDataNotFound") + " https://github.com/ajayyy/SponsorBlock/issues/753");
return; return;
@@ -938,32 +891,16 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
Config.config.whitelistedChannels = whitelistedChannels; Config.config.whitelistedChannels = whitelistedChannels;
//send a message to the client //send a message to the client
messageHandler.query({ sendTabMessage({
active: true,
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id, {
message: 'whitelistChange', message: 'whitelistChange',
value: true value: true
}); });
} }
);
}
);
});
}
function unwhitelistChannel() { async function unwhitelistChannel() {
//get the channel url //get the channel url
messageHandler.query({ const response = await sendTabMessageAsync({ message: 'getChannelID' }) as GetChannelIDResponse;
active: true,
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id,
{ message: 'getChannelID' },
function (response) {
//get whitelisted channels //get whitelisted channels
let whitelistedChannels = Config.config.whitelistedChannels; let whitelistedChannels = Config.config.whitelistedChannels;
if (whitelistedChannels == undefined) { if (whitelistedChannels == undefined) {
@@ -986,49 +923,27 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
Config.config.whitelistedChannels = whitelistedChannels; Config.config.whitelistedChannels = whitelistedChannels;
//send a message to the client //send a message to the client
messageHandler.query({ sendTabMessage({
active: true,
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id, {
message: 'whitelistChange', message: 'whitelistChange',
value: false value: false
}); });
} }
);
}
);
});
}
function refreshSegments() { async function refreshSegments() {
const stopAnimation = AnimationUtils.applyLoadingAnimation(PageElements.refreshSegmentsButton, 0.3); const stopAnimation = AnimationUtils.applyLoadingAnimation(PageElements.refreshSegmentsButton, 0.3);
messageHandler.query({ infoFound(await sendTabMessageAsync({ message: 'refreshSegments' }) as IsInfoFoundMessageResponse)
active: true,
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id,
{ message: 'refreshSegments' },
(response) => {
infoFound(response);
stopAnimation(); stopAnimation();
} }
)
}
);
}
function skipSegment(actionType: ActionType, UUID: SegmentUUID, element?: HTMLElement): void { function skipSegment(actionType: ActionType, UUID: SegmentUUID, element?: HTMLElement): void {
if (actionType === ActionType.Chapter) { if (actionType === ActionType.Chapter) {
sendMessage({ sendTabMessage({
message: "unskip", message: "unskip",
UUID: UUID UUID: UUID
}); });
} else { } else {
sendMessage({ sendTabMessage({
message: "reskip", message: "reskip",
UUID: UUID UUID: UUID
}); });
@@ -1040,18 +955,6 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
} }
} }
function sendMessage(request: Message): void {
messageHandler.query({
active: true,
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id,
request
);
});
}
/** /**
* Should skipping be disabled (visuals stay) * Should skipping be disabled (visuals stay)
*/ */
@@ -1084,10 +987,10 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
async function importSegments() { async function importSegments() {
const text = (PageElements.importSegmentsText as HTMLInputElement).value; const text = (PageElements.importSegmentsText as HTMLInputElement).value;
await sendTabMessage({ sendTabMessage({
message: "importSegments", message: "importSegments",
data: text data: text
}) as ImportSegmentsResponse; });
PageElements.importSegmentsMenu.classList.add("hidden"); PageElements.importSegmentsMenu.classList.add("hidden");
} }