Merge pull request #1521 from mini-bomba/popup

Update popup on segment updates + some code cleanup
This commit is contained in:
Ajay Ramachandran
2022-10-11 20:57:21 -04:00
committed by GitHub
4 changed files with 261 additions and 287 deletions

View File

@@ -106,6 +106,8 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) {
return true; return true;
} }
case "time": case "time":
case "infoUpdated":
case "videoChanged":
if (sender.tab) { if (sender.tab) {
popupPort[sender.tab.id]?.postMessage(request); popupPort[sender.tab.id]?.postMessage(request);
} }

View File

@@ -215,7 +215,6 @@ function messageListener(request: Message, sender: unknown, sendResponse: (respo
case "getVideoID": case "getVideoID":
sendResponse({ sendResponse({
videoID: sponsorVideoID, videoID: sponsorVideoID,
creatingSegment: isSegmentCreationInProgress(),
}); });
break; break;
@@ -243,15 +242,9 @@ function messageListener(request: Message, sender: unknown, sendResponse: (respo
// update video on refresh if videoID invalid // update video on refresh if videoID invalid
if (!sponsorVideoID) videoIDChange(getYouTubeVideoID(document)); if (!sponsorVideoID) videoIDChange(getYouTubeVideoID(document));
// fetch segments // fetch segments
sponsorsLookup(false).then(() => sendResponse({ sponsorsLookup(false);
found: sponsorDataFound,
status: lastResponseStatus,
sponsorTimes: sponsorTimes,
time: video.currentTime,
onMobileYouTube
}));
return true; break;
case "unskip": case "unskip":
unskipSponsorTime(sponsorTimes.find((segment) => segment.UUID === request.UUID), null, true); unskipSponsorTime(sponsorTimes.find((segment) => segment.UUID === request.UUID), null, true);
break; break;
@@ -384,7 +377,7 @@ function resetValues() {
categoryPill?.setVisibility(false); categoryPill?.setVisibility(false);
} }
async function videoIDChange(id): Promise<void> { async function videoIDChange(id: string): Promise<void> {
// don't switch to invalid value // don't switch to invalid value
if (!id && sponsorVideoID && !document?.URL?.includes("youtube.com/clip/")) return; if (!id && sponsorVideoID && !document?.URL?.includes("youtube.com/clip/")) return;
//if the id has not changed return unless the video element has changed //if the id has not changed return unless the video element has changed
@@ -438,10 +431,14 @@ async function videoIDChange(id): Promise<void> {
} }
} }
//close popup // Notify the popup about the video change
closeInfoMenu(); chrome.runtime.sendMessage({
message: "videoChanged",
videoID: sponsorVideoID,
whitelisted: channelWhitelisted
});
sponsorsLookup(id); sponsorsLookup();
// Make sure all player buttons are properly added // Make sure all player buttons are properly added
updateVisibilityOfPlayerControlsButton(); updateVisibilityOfPlayerControlsButton();
@@ -1004,6 +1001,14 @@ async function sponsorsLookup(keepOldSubmissions = true) {
?.sort((a, b) => a.segment[0] - b.segment[0]); ?.sort((a, b) => a.segment[0] - b.segment[0]);
if (!recievedSegments || !recievedSegments.length) { if (!recievedSegments || !recievedSegments.length) {
// return if no video found // return if no video found
chrome.runtime.sendMessage({
message: "infoUpdated",
found: false,
status: lastResponseStatus,
sponsorTimes: sponsorTimes,
time: video.currentTime,
onMobileYouTube
});
retryFetch(404); retryFetch(404);
return; return;
} }
@@ -1093,6 +1098,16 @@ async function sponsorsLookup(keepOldSubmissions = true) {
importExistingChapters(true); importExistingChapters(true);
// notify popup of segment changes
chrome.runtime.sendMessage({
message: "infoUpdated",
found: sponsorDataFound,
status: lastResponseStatus,
sponsorTimes: sponsorTimes,
time: video.currentTime,
onMobileYouTube
});
if (Config.config.isVip) { if (Config.config.isVip) {
lockedCategoriesLookup(); lockedCategoriesLookup();
} }
@@ -1138,8 +1153,8 @@ async function lockedCategoriesLookup(): Promise<void> {
} }
function retryFetch(errorCode: number): void { function retryFetch(errorCode: number): void {
if (!Config.config.refetchWhenNotFound) return;
sponsorDataFound = false; sponsorDataFound = false;
if (!Config.config.refetchWhenNotFound) return;
if (retryFetchTimeout) clearTimeout(retryFetchTimeout); if (retryFetchTimeout) clearTimeout(retryFetchTimeout);
if ((errorCode !== 404 && retryCount > 1) || (errorCode !== 404 && retryCount > 10)) { if ((errorCode !== 404 && retryCount > 1) || (errorCode !== 404 && retryCount > 10)) {
@@ -1219,12 +1234,12 @@ function startSkipScheduleCheckingForStartSponsors() {
} }
} }
function getYouTubeVideoID(document: Document, url?: string): string | boolean { function getYouTubeVideoID(document: Document, url?: string): string {
url ||= document.URL; url ||= document.URL;
// pageType shortcut // pageType shortcut
if (pageType === PageType.Channel) return getYouTubeVideoIDFromDocument() if (pageType === PageType.Channel) return getYouTubeVideoIDFromDocument();
// clips should never skip, going from clip to full video has no indications. // clips should never skip, going from clip to full video has no indications.
if (url.includes("youtube.com/clip/")) return false; if (url.includes("youtube.com/clip/")) return null;
// skip to document and don't hide if on /embed/ // skip to document and don't hide if on /embed/
if (url.includes("/embed/") && url.includes("youtube.com")) return getYouTubeVideoIDFromDocument(false, PageType.Embed); if (url.includes("/embed/") && url.includes("youtube.com")) return getYouTubeVideoIDFromDocument(false, PageType.Embed);
// skip to URL if matches youtube watch or invidious or matches youtube pattern // skip to URL if matches youtube watch or invidious or matches youtube pattern
@@ -1235,7 +1250,7 @@ function getYouTubeVideoID(document: Document, url?: string): string | boolean {
return getYouTubeVideoIDFromURL(url) || getYouTubeVideoIDFromDocument(false); return getYouTubeVideoIDFromURL(url) || getYouTubeVideoIDFromDocument(false);
} }
function getYouTubeVideoIDFromDocument(hideIcon = true, pageHint = PageType.Watch): string | boolean { function getYouTubeVideoIDFromDocument(hideIcon = true, pageHint = PageType.Watch): string {
const selector = "a.ytp-title-link[data-sessionlink='feature=player-title']"; const selector = "a.ytp-title-link[data-sessionlink='feature=player-title']";
// get ID from document (channel trailer / embedded playlist) // get ID from document (channel trailer / embedded playlist)
const element = pageHint === PageType.Embed ? document.querySelector(selector) const element = pageHint === PageType.Embed ? document.querySelector(selector)
@@ -1247,11 +1262,11 @@ function getYouTubeVideoIDFromDocument(hideIcon = true, pageHint = PageType.Watc
pageType = pageHint; pageType = pageHint;
return getYouTubeVideoIDFromURL(videoURL); return getYouTubeVideoIDFromURL(videoURL);
} else { } else {
return false; return null;
} }
} }
function getYouTubeVideoIDFromURL(url: string): string | boolean { function getYouTubeVideoIDFromURL(url: string): string {
if(url.startsWith("https://www.youtube.com/tv#/")) url = url.replace("#", ""); if(url.startsWith("https://www.youtube.com/tv#/")) url = url.replace("#", "");
//Attempt to parse url //Attempt to parse url
@@ -1260,7 +1275,7 @@ function getYouTubeVideoIDFromURL(url: string): string | boolean {
urlObject = new URL(url); urlObject = new URL(url);
} catch (e) { } catch (e) {
console.error("[SB] Unable to parse URL: " + url); console.error("[SB] Unable to parse URL: " + url);
return false; return null;
} }
// Check if valid hostname // Check if valid hostname
@@ -1274,7 +1289,7 @@ function getYouTubeVideoIDFromURL(url: string): string | boolean {
utils.wait(() => Config.config !== null).then(() => videoIDChange(getYouTubeVideoIDFromURL(url))); utils.wait(() => Config.config !== null).then(() => videoIDChange(getYouTubeVideoIDFromURL(url)));
} }
return false; return null;
} else { } else {
onInvidious = false; onInvidious = false;
} }
@@ -1282,17 +1297,17 @@ function getYouTubeVideoIDFromURL(url: string): string | boolean {
//Get ID from searchParam //Get ID from searchParam
if (urlObject.searchParams.has("v") && ["/watch", "/watch/"].includes(urlObject.pathname) || urlObject.pathname.startsWith("/tv/watch")) { if (urlObject.searchParams.has("v") && ["/watch", "/watch/"].includes(urlObject.pathname) || urlObject.pathname.startsWith("/tv/watch")) {
const id = urlObject.searchParams.get("v"); const id = urlObject.searchParams.get("v");
return id.length == 11 ? id : false; return id.length == 11 ? id : null;
} else if (urlObject.pathname.startsWith("/embed/") || urlObject.pathname.startsWith("/shorts/")) { } else if (urlObject.pathname.startsWith("/embed/") || urlObject.pathname.startsWith("/shorts/")) {
try { try {
const id = urlObject.pathname.split("/")[2] const id = urlObject.pathname.split("/")[2]
if (id?.length >=11 ) return id.slice(0, 11); if (id?.length >=11 ) return id.slice(0, 11);
} catch (e) { } catch (e) {
console.error("[SB] Video ID not valid for " + url); console.error("[SB] Video ID not valid for " + url);
return false; return null;
} }
} }
return false; return null;
} }
/** /**
@@ -1794,7 +1809,8 @@ async function updateVisibilityOfPlayerControlsButton(): Promise<void> {
updateEditButtonsOnPlayer(); updateEditButtonsOnPlayer();
// Don't show the info button on embeds // Don't show the info button on embeds
if (Config.config.hideInfoButtonPlayerControls || document.URL.includes("/embed/") || onInvidious) { if (Config.config.hideInfoButtonPlayerControls || document.URL.includes("/embed/") || onInvidious
|| document.getElementById("sponsorBlockPopupContainer") != null) {
playerButtons.info.button.style.display = "none"; playerButtons.info.button.style.display = "none";
} else { } else {
playerButtons.info.button.style.removeProperty("display"); playerButtons.info.button.style.removeProperty("display");

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[];
} }
@@ -120,4 +120,14 @@ export interface TimeUpdateMessage {
time: number; time: number;
} }
export type PopupMessage = TimeUpdateMessage; export type InfoUpdatedMessage = IsInfoFoundMessageResponse & {
message: "infoUpdated";
}
export interface VideoChangedPopupMessage {
message: "videoChanged";
videoID: string;
whitelisted: boolean;
}
export type PopupMessage = TimeUpdateMessage | InfoUpdatedMessage | VideoChangedPopupMessage;

View File

@@ -1,8 +1,24 @@
import Config from "./config"; import Config from "./config";
import Utils from "./utils"; import Utils from "./utils";
import { SponsorTime, SponsorHideType, ActionType, SegmentUUID, SponsorSourceType, StorageChangesObject } from "./types"; import {
import { Message, MessageResponse, IsInfoFoundMessageResponse, ImportSegmentsResponse, PopupMessage } from "./messageTypes"; ActionType,
SegmentUUID,
SponsorHideType,
SponsorSourceType,
SponsorTime,
StorageChangesObject,
} from "./types";
import {
GetChannelIDResponse,
IsChannelWhitelistedResponse,
IsInfoFoundMessageResponse,
Message,
MessageResponse,
PopupMessage,
SponsorStartResponse,
VoteResponse,
} from "./messageTypes";
import { showDonationLink } from "./utils/configUtils"; import { showDonationLink } from "./utils/configUtils";
import { AnimationUtils } from "./utils/animationUtils"; import { AnimationUtils } from "./utils/animationUtils";
import { GenericUtils } from "./utils/genericUtils"; import { GenericUtils } from "./utils/genericUtils";
@@ -11,6 +27,7 @@ import { localizeHtmlPage } from "./utils/pageUtils";
import { exportTimes } from "./utils/exporter"; import { exportTimes } from "./utils/exporter";
import GenericNotice from "./render/GenericNotice"; import GenericNotice from "./render/GenericNotice";
import { noRefreshFetchingChaptersAllowed } from "./utils/licenseKey"; import { noRefreshFetchingChaptersAllowed } from "./utils/licenseKey";
const utils = new Utils(); const utils = new Utils();
interface MessageListener { interface MessageListener {
@@ -67,8 +84,7 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
}; };
type PageElements = { [key: string]: HTMLElement } & InputPageElements type PageElements = { [key: string]: HTMLElement } & InputPageElements
/** If true, the content script is in the process of creating a new segment. */ let stopLoadingAnimation = null;
let creatingSegment = false;
//the start and end time pairs (2d) //the start and end time pairs (2d)
let sponsorTimes: SponsorTime[] = []; let sponsorTimes: SponsorTime[] = [];
@@ -376,7 +392,6 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
messageHandler.sendMessage(tabs[0].id, { message: 'getVideoID' }, function (result) { messageHandler.sendMessage(tabs[0].id, { message: 'getVideoID' }, function (result) {
if (result !== undefined && result.videoID) { if (result !== undefined && result.videoID) {
currentVideoID = result.videoID; currentVideoID = result.videoID;
creatingSegment = result.creatingSegment;
loadTabData(tabs, updating); loadTabData(tabs, updating);
} else if (result === undefined && chrome.runtime.lastError) { } else if (result === undefined && chrome.runtime.lastError) {
@@ -411,7 +426,13 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
}, (tabs) => onTabs(tabs, updating)); }, (tabs) => onTabs(tabs, updating));
} }
function infoFound(request: IsInfoFoundMessageResponse) { async function infoFound(request: IsInfoFoundMessageResponse) {
// End any loading animation
if (stopLoadingAnimation != null) {
stopLoadingAnimation();
stopLoadingAnimation = null;
}
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();
@@ -427,13 +448,10 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
PageElements.loadingIndicator.style.display = "none"; PageElements.loadingIndicator.style.display = "none";
downloadedTimes = request.sponsorTimes ?? []; downloadedTimes = request.sponsorTimes ?? [];
displayDownloadedSponsorTimes(downloadedTimes, request.time);
if (request.found) { if (request.found) {
PageElements.videoFound.innerHTML = chrome.i18n.getMessage("sponsorFound"); PageElements.videoFound.innerHTML = chrome.i18n.getMessage("sponsorFound");
PageElements.issueReporterImportExport.classList.remove("hidden"); PageElements.issueReporterImportExport.classList.remove("hidden");
if (request.sponsorTimes) {
displayDownloadedSponsorTimes(request.sponsorTimes, request.time);
}
} else if (request.status == 404 || request.status == 200) { } else if (request.status == 404 || request.status == 200) {
PageElements.videoFound.innerHTML = chrome.i18n.getMessage("sponsor404"); PageElements.videoFound.innerHTML = chrome.i18n.getMessage("sponsor404");
PageElements.issueReporterImportExport.classList.remove("hidden"); PageElements.issueReporterImportExport.classList.remove("hidden");
@@ -444,62 +462,40 @@ 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;
// Only update the segments after a segment was created // Only update the segments after a segment was created
if (!creatingSegment) { if (!response.creatingSegment) {
sponsorTimes = Config.config.unsubmittedSegments[currentVideoID] || []; sponsorTimes = Config.config.unsubmittedSegments[currentVideoID] || [];
} }
@@ -676,19 +672,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");
@@ -733,15 +721,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' },
);
});
} }
} }
@@ -751,9 +731,16 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
PageElements.showNoticeAgain.style.display = "none"; PageElements.showNoticeAgain.style.display = "none";
} }
function isCreatingSegment(): boolean {
const segments = Config.config.unsubmittedSegments[currentVideoID];
if (!segments) return false;
const lastSegment = segments[segments.length - 1];
return lastSegment && lastSegment?.segment?.length !== 2;
}
/** Updates any UI related to segment editing and submission according to the current state. */ /** Updates any UI related to segment editing and submission according to the current state. */
function updateSegmentEditingUI() { function updateSegmentEditingUI() {
PageElements.sponsorStart.innerText = chrome.i18n.getMessage(creatingSegment ? "sponsorEnd" : "sponsorStart"); PageElements.sponsorStart.innerText = chrome.i18n.getMessage(isCreatingSegment() ? "sponsorEnd" : "sponsorStart");
PageElements.submitTimes.style.display = sponsorTimes && sponsorTimes.length > 0 ? "unset" : "none"; PageElements.submitTimes.style.display = sponsorTimes && sponsorTimes.length > 0 ? "unset" : "none";
PageElements.submissionHint.style.display = sponsorTimes && sponsorTimes.length > 0 ? "unset" : "none"; PageElements.submissionHint.style.display = sponsorTimes && sponsorTimes.length > 0 ? "unset" : "none";
@@ -772,20 +759,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
@@ -862,163 +851,111 @@ 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 async function whitelistChannel() {
if (response.successType == 1 || (response.successType == -1 && response.statusCode == 429)) { //get the channel url
//success (treat rate limits as a success) const response = await sendTabMessageAsync({ message: 'getChannelID' }) as GetChannelIDResponse;
addVoteMessage(chrome.i18n.getMessage("voted"), UUID); if (!response.channelID) {
} else if (response.successType == -1) { alert(chrome.i18n.getMessage("channelDataNotFound") + " https://github.com/ajayyy/SponsorBlock/issues/753");
addVoteMessage(GenericUtils.getErrorMessage(response.statusCode, response.responseText), UUID); return;
} }
setTimeout(() => removeVoteMessage(UUID), 1500);
} //get whitelisted channels
} let whitelistedChannels = Config.config.whitelistedChannels;
); if (whitelistedChannels == undefined) {
whitelistedChannels = [];
}
//add on this channel
whitelistedChannels.push(response.channelID);
//change button
PageElements.whitelistChannel.style.display = "none";
PageElements.unwhitelistChannel.style.display = "unset";
document.querySelectorAll('.SBWhitelistIcon')[0].classList.add("rotated");
//show 'consider force channel check' alert
if (!Config.config.forceChannelCheck) PageElements.whitelistForceCheck.classList.remove("hidden");
//save this
Config.config.whitelistedChannels = whitelistedChannels;
//send a message to the client
sendTabMessage({
message: 'whitelistChange',
value: true
}); });
} }
function whitelistChannel() { 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) {
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 //remove this channel
whitelistedChannels.push(response.channelID); const index = whitelistedChannels.indexOf(response.channelID);
whitelistedChannels.splice(index, 1);
//change button //change button
PageElements.whitelistChannel.style.display = "none"; PageElements.whitelistChannel.style.display = "unset";
PageElements.unwhitelistChannel.style.display = "unset"; PageElements.unwhitelistChannel.style.display = "none";
document.querySelectorAll('.SBWhitelistIcon')[0].classList.add("rotated"); document.querySelectorAll('.SBWhitelistIcon')[0].classList.remove("rotated");
//show 'consider force channel check' alert //hide 'consider force channel check' alert
if (!Config.config.forceChannelCheck) PageElements.whitelistForceCheck.classList.remove("hidden"); PageElements.whitelistForceCheck.classList.add("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: false
}, tabs => {
messageHandler.sendMessage(
tabs[0].id, {
message: 'whitelistChange',
value: true
});
}
);
}
);
}); });
} }
function unwhitelistChannel() { function startLoadingAnimation() {
//get the channel url stopLoadingAnimation = AnimationUtils.applyLoadingAnimation(PageElements.refreshSegmentsButton, 0.3);
messageHandler.query({
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
const index = whitelistedChannels.indexOf(response.channelID);
whitelistedChannels.splice(index, 1);
//change button
PageElements.whitelistChannel.style.display = "unset";
PageElements.unwhitelistChannel.style.display = "none";
document.querySelectorAll('.SBWhitelistIcon')[0].classList.remove("rotated");
//hide 'consider force channel check' alert
PageElements.whitelistForceCheck.classList.add("hidden");
//save this
Config.config.whitelistedChannels = whitelistedChannels;
//send a message to the client
messageHandler.query({
active: true,
currentWindow: true
}, tabs => {
messageHandler.sendMessage(
tabs[0].id, {
message: 'whitelistChange',
value: false
});
}
);
}
);
});
} }
function refreshSegments() { function refreshSegments() {
const stopAnimation = AnimationUtils.applyLoadingAnimation(PageElements.refreshSegmentsButton, 0.3); startLoadingAnimation();
sendTabMessage({ message: 'refreshSegments' });
messageHandler.query({
active: true,
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
}); });
@@ -1030,18 +967,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)
*/ */
@@ -1074,10 +999,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");
} }
@@ -1142,6 +1067,27 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
case "time": case "time":
displayDownloadedSponsorTimes(downloadedTimes, msg.time); displayDownloadedSponsorTimes(downloadedTimes, msg.time);
break; break;
case "infoUpdated":
infoFound(msg);
break;
case "videoChanged":
currentVideoID = msg.videoID
sponsorTimes = Config.config.unsubmittedSegments[currentVideoID] ?? [];
updateSegmentEditingUI();
if (msg.whitelisted) {
PageElements.whitelistChannel.style.display = "none";
PageElements.unwhitelistChannel.style.display = "unset";
PageElements.whitelistToggle.checked = true;
document.querySelectorAll('.SBWhitelistIcon')[0].classList.add("rotated");
}
// Clear segments list & start loading animation
// We'll get a ping once they're loaded
startLoadingAnimation();
PageElements.videoFound.innerHTML = chrome.i18n.getMessage("Loading");
displayDownloadedSponsorTimes([], 0);
break;
} }
} }
} }