Skip to content

Commit

Permalink
Merge SB v5.7
Browse files Browse the repository at this point in the history
upgrade to mv3
get submission count from server
fix submission menu after video ends
  • Loading branch information
ajayyy authored and hanydd committed Jun 23, 2024
1 parent f20dd06 commit 50fc648
Show file tree
Hide file tree
Showing 12 changed files with 56 additions and 62 deletions.
2 changes: 1 addition & 1 deletion maze-utils
7 changes: 3 additions & 4 deletions src/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { setupTabUpdates } from "../maze-utils/src/tab-updates";
import { generateUserID } from "../maze-utils/src/setup";
import { isFirefoxOrSafari } from "../maze-utils/src";
import { injectUpdatedScripts } from "../maze-utils/src/cleanup";
import { logWarn } from "./utils/logger";
import { chromeP } from "../maze-utils/src/browserApi";

const popupPort: Record<string, chrome.runtime.Port> = {};
Expand Down Expand Up @@ -106,10 +107,8 @@ chrome.runtime.onInstalled.addListener(function () {

}, 1500);

// Only do this once the old version understands how to clean itself up
if (!isFirefoxOrSafari() && chrome.runtime.getManifest().version !== "5.4.13") {
// TODO: Add logging back on error
injectUpdatedScripts().catch();
if (!isFirefoxOrSafari()) {
injectUpdatedScripts().catch(logWarn);
}
});

Expand Down
3 changes: 2 additions & 1 deletion src/components/SkipNoticeComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { downvoteButtonColor, SkipNoticeAction } from "../utils/noticeUtils";
import { generateUserID } from "../../maze-utils/src/setup";
import { keybindToString } from "../../maze-utils/src/config";
import { getFormattedTime } from "../../maze-utils/src/formating";
import { getVideo } from "../../maze-utils/src/video";

enum SkipButtonState {
Undo, // Unskip
Expand Down Expand Up @@ -677,7 +678,7 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
getFullDurationCountdown(index: number): () => number {
return () => {
const sponsorTime = this.segments[index];
const duration = Math.round((sponsorTime.segment[1] - this.contentContainer().v.currentTime) * (1 / this.contentContainer().v.playbackRate));
const duration = Math.round((sponsorTime.segment[1] - getVideo().currentTime) * (1 / getVideo().playbackRate));

return Math.max(duration, Config.config.skipNoticeDuration);
};
Expand Down
9 changes: 5 additions & 4 deletions src/components/SponsorTimeEditComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { DEFAULT_CATEGORY } from "../utils/categoryUtils";
import { getFormattedTime, getFormattedTimeToSeconds } from "../../maze-utils/src/formating";
import { asyncRequestToServer } from "../utils/requests";
import { defaultPreviewTime } from "../utils/constants";
import { getVideo } from "../../maze-utils/src/video";

export interface SponsorTimeEditProps {
index: number;
Expand Down Expand Up @@ -374,7 +375,7 @@ class SponsorTimeEditComponent extends React.Component<SponsorTimeEditProps, Spo
checkToShowFullVideoWarning(): void {
const sponsorTime = this.props.contentContainer().sponsorTimesSubmitting[this.props.index];
const segmentDuration = sponsorTime.segment[1] - sponsorTime.segment[0];
const videoPercentage = segmentDuration / this.props.contentContainer().v.duration;
const videoPercentage = segmentDuration / getVideo().duration;

if (videoPercentage > 0.6 && !this.fullVideoWarningShown
&& (sponsorTime.category === "sponsor" || sponsorTime.category === "selfpromo" || sponsorTime.category === "chooseACategory")) {
Expand Down Expand Up @@ -511,7 +512,7 @@ class SponsorTimeEditComponent extends React.Component<SponsorTimeEditProps, Spo
}

setTimeToEnd(): void {
this.setTimeTo(1, this.props.contentContainer().v.duration);
this.setTimeTo(1, getVideo().duration);
}

/**
Expand Down Expand Up @@ -598,7 +599,7 @@ class SponsorTimeEditComponent extends React.Component<SponsorTimeEditProps, Spo
sponsorTimesSubmitting[this.props.index].segment[0] = startTime;
}
} else if (this.state.sponsorTimeEdits[1] === null && category === "outro" && !sponsorTimesSubmitting[this.props.index].segment[1]) {
sponsorTimesSubmitting[this.props.index].segment[1] = this.props.contentContainer().v.duration;
sponsorTimesSubmitting[this.props.index].segment[1] = getVideo().duration;
this.props.contentContainer().updateEditButtonsOnPlayer();
}

Expand Down Expand Up @@ -640,7 +641,7 @@ class SponsorTimeEditComponent extends React.Component<SponsorTimeEditProps, Spo
const endTime = sponsorTimes[index].segment[1];

// If segment starts at 0:00, start playback at the end of the segment
const skipTime = (startTime === 0 || skipToEndTime) ? endTime : (startTime - (seekTime * this.props.contentContainer().v.playbackRate));
const skipTime = (startTime === 0 || skipToEndTime) ? endTime : (startTime - (seekTime * getVideo().playbackRate));

this.props.contentContainer().previewTime(skipTime, !skipToEndTime);
}
Expand Down
7 changes: 4 additions & 3 deletions src/components/SubmissionNoticeComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import NoticeTextSelectionComponent from "./NoticeTextSectionComponent";
import SponsorTimeEditComponent from "./SponsorTimeEditComponent";
import { getGuidelineInfo } from "../utils/constants";
import { exportTimes } from "../utils/exporter";
import { getVideo } from "../../maze-utils/src/video";

export interface SubmissionNoticeProps {
// Contains functions and variables from the content script needed by the skip notice
Expand Down Expand Up @@ -66,7 +67,7 @@ class SubmissionNoticeComponent extends React.Component<SubmissionNoticeProps, S
this.forceUpdate();
});

this.videoObserver.observe(this.contentContainer().v, {
this.videoObserver.observe(getVideo(), {
attributes: true
});

Expand Down Expand Up @@ -131,7 +132,7 @@ class SubmissionNoticeComponent extends React.Component<SubmissionNoticeProps, S
{/* Sponsor Time List */}
<tr id={"sponsorSkipNoticeMiddleRow" + this.state.idSuffix}
className="sponsorTimeMessagesRow"
style={{maxHeight: (this.contentContainer().v?.offsetHeight - 200) + "px"}}
style={{maxHeight: (getVideo()?.offsetHeight - 200) + "px"}}
onMouseDown={(e) => e.stopPropagation()}>
<td style={{width: "100%"}}>
{this.getSponsorTimeMessages()}
Expand Down Expand Up @@ -283,7 +284,7 @@ class SubmissionNoticeComponent extends React.Component<SubmissionNoticeProps, S
categoryChangeListener(index: number, category: Category): void {
const dialogWidth = this.noticeRef?.current?.getElement()?.current?.offsetWidth;
if (category !== "chooseACategory" && Config.config.showCategoryGuidelines
&& this.contentContainer().v.offsetWidth > dialogWidth * 2) {
&& getVideo().offsetWidth > dialogWidth * 2) {
const options = {
title: chrome.i18n.getMessage(`category_${category}`),
textBoxes: getGuidelineInfo(category),
Expand Down
3 changes: 1 addition & 2 deletions src/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ setupVideoModule({
updateVisibilityOfPlayerControlsButton();
},
resetValues,
documentScript
documentScript: chrome.runtime.getManifest().manifest_version === 2 ? documentScript : undefined
}, () => Config);
setupThumbnailListener();

Expand Down Expand Up @@ -170,7 +170,6 @@ const skipNoticeContentContainer: ContentContainer = () => ({
sponsorTimes,
sponsorTimesSubmitting,
skipNotices,
v: getVideo(),
sponsorVideoID: getVideoID(),
reskipSponsorTime,
updatePreviewBar,
Expand Down
15 changes: 0 additions & 15 deletions src/globals.d.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,4 @@
import { SBObject } from "./config";
declare global {
interface Window { SB: SBObject }
// Remove this once the API becomes stable and types are shipped in @types/chrome
namespace chrome {
namespace declarativeContent {
export interface RequestContentScriptOptions {
allFrames?: boolean;
css?: string[];
instanceType?: "declarativeContent.RequestContentScript";
js?: string[];
matchAboutBlanck?: boolean;
}
export class RequestContentScript {
constructor(options: RequestContentScriptOptions);
}
}
}
}
14 changes: 8 additions & 6 deletions src/popup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
PageElements.showNoticeAgain.style.display = "unset";
}

const values = ["userName", "viewCount", "minutesSaved", "vip", "permissions"];
const values = ["userName", "viewCount", "minutesSaved", "vip", "permissions", "segmentCount"];

asyncRequestToServer("GET", "/api/userInfo", {
publicUserID: await getHash(Config.config.userID),
Expand Down Expand Up @@ -329,16 +329,18 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
PageElements.sponsorTimesOthersTimeSavedDisplay.innerText = getFormattedHours(minutesSaved);
}

//get the amount of times this user has contributed and display it to thank them
PageElements.sponsorTimesContributionsDisplay.innerText = Math.max(Config.config.sponsorTimesContributed ?? 0, userInfo.segmentCount).toLocaleString();
PageElements.sponsorTimesContributionsContainer.classList.remove("hidden");

PageElements.sponsorTimesOthersTimeSavedEndWord.innerText = chrome.i18n.getMessage("minsLower");

Config.config.isVip = userInfo.vip;
Config.config.permissions = userInfo.permissions;
}
});

//get the amount of times this user has contributed and display it to thank them
if (Config.config.sponsorTimesContributed != undefined) {
PageElements.sponsorTimesContributionsDisplay.innerText = Config.config.sponsorTimesContributed.toLocaleString();
PageElements.sponsorTimesContributionsContainer.classList.remove("hidden");
}


//get the amount of times this user has skipped a sponsor
if (Config.config.skipCount != undefined) {
Expand Down
3 changes: 2 additions & 1 deletion src/render/GenericNotice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const utils = new Utils();
import { ContentContainer } from "../types";
import NoticeTextSelectionComponent from "../components/NoticeTextSectionComponent";
import { ButtonListener } from "../../maze-utils/src/components/component-types";
import { getVideo } from "../../maze-utils/src/video";

export interface TextBox {
icon: string;
Expand Down Expand Up @@ -75,7 +76,7 @@ export default class GenericNotice {
{options.textBoxes?.length > 0 ?
<tr id={"sponsorSkipNoticeMiddleRow" + this.idSuffix}
className="sponsorTimeMessagesRow"
style={{maxHeight: this.contentContainer ? (this.contentContainer().v.offsetHeight - 200) + "px" : null}}>
style={{maxHeight: getVideo() ? (getVideo().offsetHeight - 200) + "px" : null}}>
<td style={{width: "100%"}}>
{this.getMessageBoxes(this.idSuffix, options.textBoxes)}
</td>
Expand Down
1 change: 0 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export interface ContentContainer {
sponsorTimes: SponsorTime[];
sponsorTimesSubmitting: SponsorTime[];
skipNotices: SkipNotice[];
v: HTMLVideoElement;
sponsorVideoID;
reskipSponsorTime: (segment: SponsorTime, forceSeek?: boolean) => void;
updatePreviewBar: () => void;
Expand Down
30 changes: 13 additions & 17 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ export default class Utils {
*/
setupExtraSitePermissions(callback: (granted: boolean) => void): void {
const permissions = [];
if (!isFirefoxOrSafari()) {
permissions.push("declarativeContent");
}
if (!isFirefoxOrSafari() || isSafari()) {
if (isSafari()) {
permissions.push("webNavigation");
}

Expand All @@ -67,6 +64,17 @@ export default class Utils {
});
}

getExtraSiteRegistration(): Registration {
return {
message: "registerContentScript",
id: "invidious",
allFrames: true,
js: this.js,
css: this.css,
matches: this.getPermissionRegex()
};
}

/**
* Registers the content scripts for the extra sites.
* Will use a different method depending on the browser.
Expand All @@ -75,14 +83,7 @@ export default class Utils {
* For now, it is just SB.config.invidiousInstances.
*/
setupExtraSiteContentScripts(): void {
const registration: Registration = {
message: "registerContentScript",
id: "invidious",
allFrames: true,
js: this.js,
css: this.css,
matches: this.getPermissionRegex()
};
const registration = this.getExtraSiteRegistration();

if (this.backgroundScriptContainer) {
this.backgroundScriptContainer.registerFirefoxContentScript(registration);
Expand All @@ -106,11 +107,6 @@ export default class Utils {
});
}

if (!isFirefoxOrSafari() && chrome.declarativeContent) {
// Only if we have permission
chrome.declarativeContent.onPageChanged.removeRules(["invidious"]);
}

chrome.permissions.remove({
origins: this.getPermissionRegex()
});
Expand Down
24 changes: 17 additions & 7 deletions src/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
window["SBLogs"] = {
debug: [],
warn: []
};
if (typeof window !== "undefined") {
window["SBLogs"] = {
debug: [],
warn: [],
};
}

export function logDebug(message: string) {
window["SBLogs"].debug.push(`[${new Date().toISOString()}] ${message}`);
if (typeof window !== "undefined") {
window["SBLogs"].debug.push(`[${new Date().toISOString()}] ${message}`);
} else {
console.log(`[${new Date().toISOString()}] ${message}`);
}
}

export function logWarn(message: string) {
window["SBLogs"].warn.push(`[${new Date().toISOString()}] ${message}`);
}
if (typeof window !== "undefined") {
window["SBLogs"].warn.push(`[${new Date().toISOString()}] ${message}`);
} else {
console.warn(`[${new Date().toISOString()}] ${message}`);
}
}

0 comments on commit 50fc648

Please sign in to comment.