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,58 +458,38 @@ 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, if (response.value) {
currentWindow: true PageElements.whitelistChannel.style.display = "none";
}, tabs => { PageElements.unwhitelistChannel.style.display = "unset";
messageHandler.sendMessage( PageElements.whitelistToggle.checked = true;
tabs[0].id, document.querySelectorAll('.SBWhitelistIcon')[0].classList.add("rotated");
{ message: 'isChannelWhitelisted' },
function (response) {
if (response.value) {
PageElements.whitelistChannel.style.display = "none";
PageElements.unwhitelistChannel.style.display = "unset";
PageElements.whitelistToggle.checked = true;
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, startSponsorCallback(response);
currentWindow: true,
}, (tabs) => {
messageHandler.sendMessage(
tabs[0].id,
{ from: 'popup', message: 'sponsorStart' },
async (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
const removeListener = (listener: typeof lateUpdate) => { const removeListener = (listener: typeof lateUpdate) => {
const index = Config.configSyncListeners.indexOf(listener); const index = Config.configSyncListeners.indexOf(listener);
if (index !== -1) Config.configSyncListeners.splice(index, 1); if (index !== -1) Config.configSyncListeners.splice(index, 1);
}; };
const lateUpdate = () => { const lateUpdate = () => {
startSponsorCallback(response); startSponsorCallback(response);
removeListener(lateUpdate); removeListener(lateUpdate);
}; };
Config.configSyncListeners.push(lateUpdate); Config.configSyncListeners.push(lateUpdate);
// 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, message: "hideSegment",
currentWindow: true type: downloadedTimes[i].hidden,
}, tabs => { UUID: UUID
messageHandler.sendMessage( })
tabs[0].id,
{
message: "hideSegment",
type: downloadedTimes[i].hidden,
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,20 +749,22 @@ 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 }, tabs => {
}, tabs => { messageHandler.sendMessage(
messageHandler.sendMessage( tabs[0].id,
tabs[0].id, data,
data, callback
(response) => resolve(response)
);
}
); );
}); }
);
}
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,163 +841,109 @@ 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({
message: "submitVote",
type: type,
UUID: UUID
}) as VoteResponse;
messageHandler.query({ if (response != undefined) {
active: true, //see if it was a success or failure
currentWindow: true if (response.successType == 1 || (response.successType == -1 && response.statusCode == 429)) {
}, tabs => { //success (treat rate limits as a success)
messageHandler.sendMessage( addVoteMessage(chrome.i18n.getMessage("voted"), UUID);
tabs[0].id, } else if (response.successType == -1) {
{ addVoteMessage(GenericUtils.getErrorMessage(response.statusCode, response.responseText), UUID);
message: "submitVote", }
type: type, setTimeout(() => removeVoteMessage(UUID), 1500);
UUID: UUID }
}, function (response) {
if (response != undefined) {
//see if it was a success or failure
if (response.successType == 1 || (response.successType == -1 && response.statusCode == 429)) {
//success (treat rate limits as a success)
addVoteMessage(chrome.i18n.getMessage("voted"), UUID);
} else if (response.successType == -1) {
addVoteMessage(GenericUtils.getErrorMessage(response.statusCode, response.responseText), UUID);
}
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, if (!response.channelID) {
currentWindow: true alert(chrome.i18n.getMessage("channelDataNotFound") + " https://github.com/ajayyy/SponsorBlock/issues/753");
}, tabs => { return;
messageHandler.sendMessage( }
tabs[0].id,
{ message: 'getChannelID' },
function (response) {
if (!response.channelID) {
alert(chrome.i18n.getMessage("channelDataNotFound") + " https://github.com/ajayyy/SponsorBlock/issues/753");
return;
}
//get whitelisted channels //get whitelisted channels
let whitelistedChannels = Config.config.whitelistedChannels; let whitelistedChannels = Config.config.whitelistedChannels;
if (whitelistedChannels == undefined) { if (whitelistedChannels == undefined) {
whitelistedChannels = []; whitelistedChannels = [];
} }
//add on this channel //add on this channel
whitelistedChannels.push(response.channelID); whitelistedChannels.push(response.channelID);
//change button //change button
PageElements.whitelistChannel.style.display = "none"; PageElements.whitelistChannel.style.display = "none";
PageElements.unwhitelistChannel.style.display = "unset"; PageElements.unwhitelistChannel.style.display = "unset";
document.querySelectorAll('.SBWhitelistIcon')[0].classList.add("rotated"); document.querySelectorAll('.SBWhitelistIcon')[0].classList.add("rotated");
//show 'consider force channel check' alert //show 'consider force channel check' alert
if (!Config.config.forceChannelCheck) PageElements.whitelistForceCheck.classList.remove("hidden"); if (!Config.config.forceChannelCheck) PageElements.whitelistForceCheck.classList.remove("hidden");
//save this //save this
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, message: 'whitelistChange',
currentWindow: true value: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id, {
message: 'whitelistChange',
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
let whitelistedChannels = Config.config.whitelistedChannels;
if (whitelistedChannels == undefined) {
whitelistedChannels = [];
}
//remove this channel //get whitelisted channels
const index = whitelistedChannels.indexOf(response.channelID); let whitelistedChannels = Config.config.whitelistedChannels;
whitelistedChannels.splice(index, 1); if (whitelistedChannels == undefined) {
whitelistedChannels = [];
}
//change button //remove this channel
PageElements.whitelistChannel.style.display = "unset"; const index = whitelistedChannels.indexOf(response.channelID);
PageElements.unwhitelistChannel.style.display = "none"; whitelistedChannels.splice(index, 1);
document.querySelectorAll('.SBWhitelistIcon')[0].classList.remove("rotated");
//hide 'consider force channel check' alert //change button
PageElements.whitelistForceCheck.classList.add("hidden"); PageElements.whitelistChannel.style.display = "unset";
PageElements.unwhitelistChannel.style.display = "none";
document.querySelectorAll('.SBWhitelistIcon')[0].classList.remove("rotated");
//save this //hide 'consider force channel check' alert
Config.config.whitelistedChannels = whitelistedChannels; PageElements.whitelistForceCheck.classList.add("hidden");
//send a message to the client //save this
messageHandler.query({ Config.config.whitelistedChannels = whitelistedChannels;
active: true,
currentWindow: true //send a message to the client
}, tabs => { sendTabMessage({
messageHandler.sendMessage( message: 'whitelistChange',
tabs[0].id, { value: false
message: 'whitelistChange',
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, stopAnimation();
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id,
{ message: 'refreshSegments' },
(response) => {
infoFound(response);
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");
} }