Skip to content

Commit cd78c46

Browse files
authored
Merge pull request #1521 from mini-bomba/popup
Update popup on segment updates + some code cleanup
2 parents 758b6f1 + b7a574f commit cd78c46

File tree

4 files changed

+266
-292
lines changed

4 files changed

+266
-292
lines changed

src/background.ts

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ if (utils.isFirefox()) {
2424
utils.wait(() => Config.config !== null).then(function() {
2525
if (Config.config.supportInvidious) utils.setupExtraSiteContentScripts();
2626
});
27-
}
27+
}
2828

2929
function onTabUpdatedListener(tabId: number) {
3030
chrome.tabs.sendMessage(tabId, {
@@ -77,17 +77,17 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) {
7777
ok: response.ok
7878
});
7979
});
80-
80+
8181
return true;
8282
case "submitVote":
8383
submitVote(request.type, request.UUID, request.category).then(callback);
84-
84+
8585
//this allows the callback to be called later
8686
return true;
87-
case "registerContentScript":
87+
case "registerContentScript":
8888
registerFirefoxContentScript(request);
8989
return false;
90-
case "unregisterContentScript":
90+
case "unregisterContentScript":
9191
unregisterFirefoxContentScript(request.id)
9292
return false;
9393
case "tabs": {
@@ -106,6 +106,8 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) {
106106
return true;
107107
}
108108
case "time":
109+
case "infoUpdated":
110+
case "videoChanged":
109111
if (sender.tab) {
110112
popupPort[sender.tab.id]?.postMessage(request);
111113
}
@@ -156,8 +158,8 @@ chrome.runtime.onInstalled.addListener(function () {
156158
/**
157159
* Only works on Firefox.
158160
* Firefox requires that it be applied after every extension restart.
159-
*
160-
* @param {JSON} options
161+
*
162+
* @param {JSON} options
161163
*/
162164
function registerFirefoxContentScript(options: Registration) {
163165
const oldRegistration = contentScriptRegistrations[options.id];
@@ -174,7 +176,7 @@ function registerFirefoxContentScript(options: Registration) {
174176
/**
175177
* Only works on Firefox.
176178
* Firefox requires that this is handled by the background script
177-
*
179+
*
178180
*/
179181
function unregisterFirefoxContentScript(id: string) {
180182
contentScriptRegistrations[id].unregister();
@@ -225,10 +227,10 @@ async function asyncRequestToServer(type: string, address: string, data = {}) {
225227

226228
/**
227229
* Sends a request to the specified url
228-
*
230+
*
229231
* @param type The request type "GET", "POST", etc.
230232
* @param address The address to add to the SponsorBlock server address
231-
* @param callback
233+
* @param callback
232234
*/
233235
async function sendRequestToCustomServer(type: string, url: string, data = {}) {
234236
// If GET, convert JSON to parameters
@@ -248,4 +250,4 @@ async function sendRequestToCustomServer(type: string, url: string, data = {}) {
248250
});
249251

250252
return response;
251-
}
253+
}

src/content.ts

Lines changed: 42 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,6 @@ function messageListener(request: Message, sender: unknown, sendResponse: (respo
215215
case "getVideoID":
216216
sendResponse({
217217
videoID: sponsorVideoID,
218-
creatingSegment: isSegmentCreationInProgress(),
219218
});
220219

221220
break;
@@ -243,15 +242,9 @@ function messageListener(request: Message, sender: unknown, sendResponse: (respo
243242
// update video on refresh if videoID invalid
244243
if (!sponsorVideoID) videoIDChange(getYouTubeVideoID(document));
245244
// fetch segments
246-
sponsorsLookup(false).then(() => sendResponse({
247-
found: sponsorDataFound,
248-
status: lastResponseStatus,
249-
sponsorTimes: sponsorTimes,
250-
time: video.currentTime,
251-
onMobileYouTube
252-
}));
245+
sponsorsLookup(false);
253246

254-
return true;
247+
break;
255248
case "unskip":
256249
unskipSponsorTime(sponsorTimes.find((segment) => segment.UUID === request.UUID), null, true);
257250
break;
@@ -384,7 +377,7 @@ function resetValues() {
384377
categoryPill?.setVisibility(false);
385378
}
386379

387-
async function videoIDChange(id): Promise<void> {
380+
async function videoIDChange(id: string): Promise<void> {
388381
// don't switch to invalid value
389382
if (!id && sponsorVideoID && !document?.URL?.includes("youtube.com/clip/")) return;
390383
//if the id has not changed return unless the video element has changed
@@ -438,10 +431,14 @@ async function videoIDChange(id): Promise<void> {
438431
}
439432
}
440433

441-
//close popup
442-
closeInfoMenu();
434+
// Notify the popup about the video change
435+
chrome.runtime.sendMessage({
436+
message: "videoChanged",
437+
videoID: sponsorVideoID,
438+
whitelisted: channelWhitelisted
439+
});
443440

444-
sponsorsLookup(id);
441+
sponsorsLookup();
445442

446443
// Make sure all player buttons are properly added
447444
updateVisibilityOfPlayerControlsButton();
@@ -1004,6 +1001,14 @@ async function sponsorsLookup(keepOldSubmissions = true) {
10041001
?.sort((a, b) => a.segment[0] - b.segment[0]);
10051002
if (!recievedSegments || !recievedSegments.length) {
10061003
// return if no video found
1004+
chrome.runtime.sendMessage({
1005+
message: "infoUpdated",
1006+
found: false,
1007+
status: lastResponseStatus,
1008+
sponsorTimes: sponsorTimes,
1009+
time: video.currentTime,
1010+
onMobileYouTube
1011+
});
10071012
retryFetch(404);
10081013
return;
10091014
}
@@ -1093,6 +1098,16 @@ async function sponsorsLookup(keepOldSubmissions = true) {
10931098

10941099
importExistingChapters(true);
10951100

1101+
// notify popup of segment changes
1102+
chrome.runtime.sendMessage({
1103+
message: "infoUpdated",
1104+
found: sponsorDataFound,
1105+
status: lastResponseStatus,
1106+
sponsorTimes: sponsorTimes,
1107+
time: video.currentTime,
1108+
onMobileYouTube
1109+
});
1110+
10961111
if (Config.config.isVip) {
10971112
lockedCategoriesLookup();
10981113
}
@@ -1138,8 +1153,8 @@ async function lockedCategoriesLookup(): Promise<void> {
11381153
}
11391154

11401155
function retryFetch(errorCode: number): void {
1141-
if (!Config.config.refetchWhenNotFound) return;
11421156
sponsorDataFound = false;
1157+
if (!Config.config.refetchWhenNotFound) return;
11431158

11441159
if (retryFetchTimeout) clearTimeout(retryFetchTimeout);
11451160
if ((errorCode !== 404 && retryCount > 1) || (errorCode !== 404 && retryCount > 10)) {
@@ -1219,12 +1234,12 @@ function startSkipScheduleCheckingForStartSponsors() {
12191234
}
12201235
}
12211236

1222-
function getYouTubeVideoID(document: Document, url?: string): string | boolean {
1237+
function getYouTubeVideoID(document: Document, url?: string): string {
12231238
url ||= document.URL;
12241239
// pageType shortcut
1225-
if (pageType === PageType.Channel) return getYouTubeVideoIDFromDocument()
1240+
if (pageType === PageType.Channel) return getYouTubeVideoIDFromDocument();
12261241
// clips should never skip, going from clip to full video has no indications.
1227-
if (url.includes("youtube.com/clip/")) return false;
1242+
if (url.includes("youtube.com/clip/")) return null;
12281243
// skip to document and don't hide if on /embed/
12291244
if (url.includes("/embed/") && url.includes("youtube.com")) return getYouTubeVideoIDFromDocument(false, PageType.Embed);
12301245
// 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 {
12351250
return getYouTubeVideoIDFromURL(url) || getYouTubeVideoIDFromDocument(false);
12361251
}
12371252

1238-
function getYouTubeVideoIDFromDocument(hideIcon = true, pageHint = PageType.Watch): string | boolean {
1253+
function getYouTubeVideoIDFromDocument(hideIcon = true, pageHint = PageType.Watch): string {
12391254
const selector = "a.ytp-title-link[data-sessionlink='feature=player-title']";
12401255
// get ID from document (channel trailer / embedded playlist)
12411256
const element = pageHint === PageType.Embed ? document.querySelector(selector)
@@ -1247,11 +1262,11 @@ function getYouTubeVideoIDFromDocument(hideIcon = true, pageHint = PageType.Watc
12471262
pageType = pageHint;
12481263
return getYouTubeVideoIDFromURL(videoURL);
12491264
} else {
1250-
return false;
1265+
return null;
12511266
}
12521267
}
12531268

1254-
function getYouTubeVideoIDFromURL(url: string): string | boolean {
1269+
function getYouTubeVideoIDFromURL(url: string): string {
12551270
if(url.startsWith("https://www.youtube.com/tv#/")) url = url.replace("#", "");
12561271

12571272
//Attempt to parse url
@@ -1260,7 +1275,7 @@ function getYouTubeVideoIDFromURL(url: string): string | boolean {
12601275
urlObject = new URL(url);
12611276
} catch (e) {
12621277
console.error("[SB] Unable to parse URL: " + url);
1263-
return false;
1278+
return null;
12641279
}
12651280

12661281
// Check if valid hostname
@@ -1274,25 +1289,25 @@ function getYouTubeVideoIDFromURL(url: string): string | boolean {
12741289
utils.wait(() => Config.config !== null).then(() => videoIDChange(getYouTubeVideoIDFromURL(url)));
12751290
}
12761291

1277-
return false;
1292+
return null;
12781293
} else {
12791294
onInvidious = false;
12801295
}
12811296

12821297
//Get ID from searchParam
12831298
if (urlObject.searchParams.has("v") && ["/watch", "/watch/"].includes(urlObject.pathname) || urlObject.pathname.startsWith("/tv/watch")) {
12841299
const id = urlObject.searchParams.get("v");
1285-
return id.length == 11 ? id : false;
1300+
return id.length == 11 ? id : null;
12861301
} else if (urlObject.pathname.startsWith("/embed/") || urlObject.pathname.startsWith("/shorts/")) {
12871302
try {
12881303
const id = urlObject.pathname.split("/")[2]
12891304
if (id?.length >=11 ) return id.slice(0, 11);
12901305
} catch (e) {
12911306
console.error("[SB] Video ID not valid for " + url);
1292-
return false;
1307+
return null;
12931308
}
12941309
}
1295-
return false;
1310+
return null;
12961311
}
12971312

12981313
/**
@@ -1794,7 +1809,8 @@ async function updateVisibilityOfPlayerControlsButton(): Promise<void> {
17941809
updateEditButtonsOnPlayer();
17951810

17961811
// Don't show the info button on embeds
1797-
if (Config.config.hideInfoButtonPlayerControls || document.URL.includes("/embed/") || onInvidious) {
1812+
if (Config.config.hideInfoButtonPlayerControls || document.URL.includes("/embed/") || onInvidious
1813+
|| document.getElementById("sponsorBlockPopupContainer") != null) {
17981814
playerButtons.info.button.style.display = "none";
17991815
} else {
18001816
playerButtons.info.button.style.removeProperty("display");

src/messageTypes.ts

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ interface BaseMessage {
99
}
1010

1111
interface DefaultMessage {
12-
message:
12+
message:
1313
"update"
1414
| "sponsorStart"
1515
| "getVideoID"
@@ -83,19 +83,19 @@ interface GetVideoIdResponse {
8383
videoID: string;
8484
}
8585

86-
interface GetChannelIDResponse {
86+
export interface GetChannelIDResponse {
8787
channelID: string;
8888
}
8989

90-
interface SponsorStartResponse {
90+
export interface SponsorStartResponse {
9191
creatingSegment: boolean;
9292
}
9393

94-
interface IsChannelWhitelistedResponse {
94+
export interface IsChannelWhitelistedResponse {
9595
value: boolean;
9696
}
9797

98-
export type MessageResponse =
98+
export type MessageResponse =
9999
IsInfoFoundMessageResponse
100100
| GetVideoIdResponse
101101
| GetChannelIDResponse
@@ -111,7 +111,7 @@ export interface VoteResponse {
111111
responseText: string;
112112
}
113113

114-
export interface ImportSegmentsResponse {
114+
interface ImportSegmentsResponse {
115115
importedSegments: SponsorTime[];
116116
}
117117

@@ -120,4 +120,14 @@ export interface TimeUpdateMessage {
120120
time: number;
121121
}
122122

123-
export type PopupMessage = TimeUpdateMessage;
123+
export type InfoUpdatedMessage = IsInfoFoundMessageResponse & {
124+
message: "infoUpdated";
125+
}
126+
127+
export interface VideoChangedPopupMessage {
128+
message: "videoChanged";
129+
videoID: string;
130+
whitelisted: boolean;
131+
}
132+
133+
export type PopupMessage = TimeUpdateMessage | InfoUpdatedMessage | VideoChangedPopupMessage;

0 commit comments

Comments
 (0)