mirror of
https://github.com/ajayyy/SponsorBlock.git
synced 2025-12-15 16:07:06 +03:00
Merge branch 'master' of https://github.com/ajayyy/SponsorBlock into improvements
This commit is contained in:
@@ -164,11 +164,7 @@ async function asyncRequestToServer(type: string, address: string, data = {}) {
|
||||
async function sendRequestToCustomServer(type: string, url: string, data = {}) {
|
||||
// If GET, convert JSON to parameters
|
||||
if (type.toLowerCase() === "get") {
|
||||
for (const key in data) {
|
||||
const seperator = url.includes("?") ? "&" : "?";
|
||||
const value = (typeof(data[key]) === "string") ? data[key]: JSON.stringify(data[key]);
|
||||
url += seperator + key + "=" + value;
|
||||
}
|
||||
url = utils.objectToURI(url, data, true);
|
||||
|
||||
data = null;
|
||||
}
|
||||
|
||||
@@ -363,11 +363,15 @@ class SkipNoticeComponent extends React.Component<SkipNoticeProps, SkipNoticeSta
|
||||
|
||||
for (let i = 0; i < this.state.messages.length; i++) {
|
||||
elements.push(
|
||||
<NoticeTextSelectionComponent idSuffix={this.idSuffix}
|
||||
text={this.state.messages[i]}
|
||||
onClick={this.state.messageOnClick}
|
||||
key={"messageBox" + i}>
|
||||
</NoticeTextSelectionComponent>
|
||||
<tr>
|
||||
<td>
|
||||
<NoticeTextSelectionComponent idSuffix={this.idSuffix}
|
||||
text={this.state.messages[i]}
|
||||
onClick={this.state.messageOnClick}
|
||||
key={i + "_messageBox"}>
|
||||
</NoticeTextSelectionComponent>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,6 @@ interface SBConfig {
|
||||
testingServer: boolean,
|
||||
refetchWhenNotFound: boolean,
|
||||
ytInfoPermissionGranted: boolean,
|
||||
askAboutUnlistedVideos: boolean,
|
||||
allowExpirements: boolean,
|
||||
autoHideInfoButton: boolean,
|
||||
|
||||
@@ -178,7 +177,6 @@ const Config: SBObject = {
|
||||
testingServer: false,
|
||||
refetchWhenNotFound: true,
|
||||
ytInfoPermissionGranted: false,
|
||||
askAboutUnlistedVideos: true,
|
||||
allowExpirements: true,
|
||||
autoHideInfoButton: true,
|
||||
|
||||
@@ -363,6 +361,10 @@ function migrateOldFormats(config: SBConfig) {
|
||||
config.categorySelections = config.categorySelections;
|
||||
}
|
||||
|
||||
if (config["askAboutUnlistedVideos"]) {
|
||||
chrome.storage.sync.remove("askAboutUnlistedVideos");
|
||||
}
|
||||
|
||||
// Adding preview category
|
||||
if (!config["previewCategoryUpdate"]) {
|
||||
config["previewCategoryUpdate"] = true;
|
||||
|
||||
256
src/content.ts
256
src/content.ts
@@ -1,5 +1,6 @@
|
||||
import Config from "./config";
|
||||
import { SponsorTime, CategorySkipOption, VideoID, SponsorHideType, FetchResponse, VideoInfo, StorageChangesObject, CategoryActionType, ChannelIDInfo, ChannelIDStatus, SegmentUUID, Category } from "./types";
|
||||
import { SponsorTime, CategorySkipOption, VideoID, SponsorHideType, VideoInfo, StorageChangesObject, CategoryActionType, ChannelIDInfo, ChannelIDStatus, SponsorSourceType, SegmentUUID, Category } from "./types";
|
||||
|
||||
import { ContentContainer } from "./types";
|
||||
import Utils from "./utils";
|
||||
const utils = new Utils();
|
||||
@@ -11,7 +12,7 @@ import SkipNotice from "./render/SkipNotice";
|
||||
import SkipNoticeComponent from "./components/SkipNoticeComponent";
|
||||
import SubmissionNotice from "./render/SubmissionNotice";
|
||||
import { Message, MessageResponse } from "./messageTypes";
|
||||
import GenericNotice from "./render/GenericNotice";
|
||||
import * as Chat from "./js-components/chat";
|
||||
|
||||
// Hack to get the CSS loaded on permission-based sites (Invidious)
|
||||
utils.wait(() => Config.config !== null, 5000, 10).then(addCSS);
|
||||
@@ -176,6 +177,9 @@ function messageListener(request: Message, sender: unknown, sendResponse: (respo
|
||||
case "submitTimes":
|
||||
submitSponsorTimes();
|
||||
break;
|
||||
case "refreshSegments":
|
||||
sponsorsLookup(sponsorVideoID, false).then(() => sendResponse({}));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,6 +211,7 @@ function resetValues() {
|
||||
//reset sponsor times
|
||||
sponsorTimes = null;
|
||||
sponsorLookupRetries = 0;
|
||||
sponsorSkipped = [];
|
||||
|
||||
videoInfo = null;
|
||||
channelWhitelisted = false;
|
||||
@@ -234,6 +239,10 @@ function resetValues() {
|
||||
|
||||
// Reset advert playing flag
|
||||
isAdPlaying = false;
|
||||
|
||||
for (let i = 0; i < skipNotices.length; i++) {
|
||||
skipNotices.pop().close();
|
||||
}
|
||||
}
|
||||
|
||||
async function videoIDChange(id) {
|
||||
@@ -271,9 +280,6 @@ async function videoIDChange(id) {
|
||||
// Update whitelist data when the video data is loaded
|
||||
whitelistCheck();
|
||||
|
||||
// Temporary expirement
|
||||
unlistedCheck();
|
||||
|
||||
//setup the preview bar
|
||||
if (previewBar === null) {
|
||||
if (onMobileYouTube) {
|
||||
@@ -567,7 +573,7 @@ function setupVideoListeners() {
|
||||
}
|
||||
}
|
||||
|
||||
async function sponsorsLookup(id: string) {
|
||||
async function sponsorsLookup(id: string, keepOldSubmissions = true) {
|
||||
if (!video) refreshVideoAttachments();
|
||||
//there is still no video here
|
||||
if (!video) {
|
||||
@@ -588,43 +594,45 @@ async function sponsorsLookup(id: string) {
|
||||
|
||||
// Check for hashPrefix setting
|
||||
const hashPrefix = (await utils.getHash(id, 1)).substr(0, 4);
|
||||
utils.asyncRequestToServer('GET', "/api/skipSegments/" + hashPrefix, {
|
||||
const response = await utils.asyncRequestToServer('GET', "/api/skipSegments/" + hashPrefix, {
|
||||
categories
|
||||
}).then(async (response: FetchResponse) => {
|
||||
if (response?.ok) {
|
||||
const recievedSegments: SponsorTime[] = JSON.parse(response.responseText)
|
||||
?.filter((video) => video.videoID === id)
|
||||
?.map((video) => video.segments)[0];
|
||||
if (!recievedSegments || !recievedSegments.length) {
|
||||
// return if no video found
|
||||
retryFetch();
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
sponsorDataFound = true;
|
||||
if (response?.ok) {
|
||||
const recievedSegments: SponsorTime[] = JSON.parse(response.responseText)
|
||||
?.filter((video) => video.videoID === id)
|
||||
?.map((video) => video.segments)[0];
|
||||
if (!recievedSegments || !recievedSegments.length) {
|
||||
// return if no video found
|
||||
retryFetch();
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if any old submissions should be kept
|
||||
if (sponsorTimes !== null) {
|
||||
for (let i = 0; i < sponsorTimes.length; i++) {
|
||||
if (sponsorTimes[i].UUID === null) {
|
||||
// This is a user submission, keep it
|
||||
recievedSegments.push(sponsorTimes[i]);
|
||||
}
|
||||
sponsorDataFound = true;
|
||||
|
||||
// Check if any old submissions should be kept
|
||||
if (sponsorTimes !== null && keepOldSubmissions) {
|
||||
for (let i = 0; i < sponsorTimes.length; i++) {
|
||||
if (sponsorTimes[i].source === SponsorSourceType.Local) {
|
||||
// This is a user submission, keep it
|
||||
recievedSegments.push(sponsorTimes[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const oldSegments = sponsorTimes || [];
|
||||
sponsorTimes = recievedSegments;
|
||||
const oldSegments = sponsorTimes || [];
|
||||
sponsorTimes = recievedSegments;
|
||||
|
||||
// Hide all submissions smaller than the minimum duration
|
||||
if (Config.config.minDuration !== 0) {
|
||||
for (let i = 0; i < sponsorTimes.length; i++) {
|
||||
if (sponsorTimes[i].segment[1] - sponsorTimes[i].segment[0] < Config.config.minDuration) {
|
||||
sponsorTimes[i].hidden = SponsorHideType.MinimumDuration;
|
||||
}
|
||||
// Hide all submissions smaller than the minimum duration
|
||||
if (Config.config.minDuration !== 0) {
|
||||
for (let i = 0; i < sponsorTimes.length; i++) {
|
||||
if (sponsorTimes[i].segment[1] - sponsorTimes[i].segment[0] < Config.config.minDuration) {
|
||||
sponsorTimes[i].hidden = SponsorHideType.MinimumDuration;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (keepOldSubmissions) {
|
||||
for (const segment of oldSegments) {
|
||||
const otherSegment = sponsorTimes.find((other) => segment.UUID === other.UUID);
|
||||
if (otherSegment) {
|
||||
@@ -633,37 +641,34 @@ async function sponsorsLookup(id: string) {
|
||||
otherSegment.category = segment.category;
|
||||
}
|
||||
}
|
||||
|
||||
startSkipScheduleCheckingForStartSponsors();
|
||||
|
||||
// Reset skip save
|
||||
sponsorSkipped = [];
|
||||
|
||||
//update the preview bar
|
||||
//leave the type blank for now until categories are added
|
||||
if (lastPreviewBarUpdate == id || (lastPreviewBarUpdate == null && !isNaN(video.duration))) {
|
||||
//set it now
|
||||
//otherwise the listener can handle it
|
||||
updatePreviewBar();
|
||||
}
|
||||
|
||||
sponsorLookupRetries = 0;
|
||||
} else if (response?.status === 404) {
|
||||
retryFetch();
|
||||
} else if (sponsorLookupRetries < 15 && !recheckStarted) {
|
||||
recheckStarted = true;
|
||||
|
||||
//TODO lower when server becomes better (back to 1 second)
|
||||
//some error occurred, try again in a second
|
||||
setTimeout(() => {
|
||||
if (sponsorVideoID && sponsorTimes?.length === 0) {
|
||||
sponsorsLookup(sponsorVideoID);
|
||||
}
|
||||
}, 5000 + Math.random() * 15000 + 5000 * sponsorLookupRetries);
|
||||
|
||||
sponsorLookupRetries++;
|
||||
}
|
||||
});
|
||||
|
||||
startSkipScheduleCheckingForStartSponsors();
|
||||
|
||||
//update the preview bar
|
||||
//leave the type blank for now until categories are added
|
||||
if (lastPreviewBarUpdate == id || (lastPreviewBarUpdate == null && !isNaN(video.duration))) {
|
||||
//set it now
|
||||
//otherwise the listener can handle it
|
||||
updatePreviewBar();
|
||||
}
|
||||
|
||||
sponsorLookupRetries = 0;
|
||||
} else if (response?.status === 404) {
|
||||
retryFetch();
|
||||
} else if (sponsorLookupRetries < 15 && !recheckStarted) {
|
||||
recheckStarted = true;
|
||||
|
||||
//TODO lower when server becomes better (back to 1 second)
|
||||
//some error occurred, try again in a second
|
||||
setTimeout(() => {
|
||||
if (sponsorVideoID && sponsorTimes?.length === 0) {
|
||||
sponsorsLookup(sponsorVideoID);
|
||||
}
|
||||
}, 5000 + Math.random() * 15000 + 5000 * sponsorLookupRetries);
|
||||
|
||||
sponsorLookupRetries++;
|
||||
}
|
||||
}
|
||||
|
||||
function retryFetch(): void {
|
||||
@@ -864,7 +869,7 @@ async function whitelistCheck() {
|
||||
|
||||
channelIDInfo = {
|
||||
status: ChannelIDStatus.Found,
|
||||
id: getChannelID()
|
||||
id: getChannelID().match(/^\/?([^\s/]+)/)[0]
|
||||
}
|
||||
} catch (e) {
|
||||
channelIDInfo = {
|
||||
@@ -876,7 +881,8 @@ async function whitelistCheck() {
|
||||
}
|
||||
|
||||
//see if this is a whitelisted channel
|
||||
if (whitelistedChannels != undefined && whitelistedChannels.includes(getChannelID())) {
|
||||
if (whitelistedChannels != undefined &&
|
||||
channelIDInfo.status === ChannelIDStatus.Found && whitelistedChannels.includes(channelIDInfo.id)) {
|
||||
channelWhitelisted = true;
|
||||
}
|
||||
|
||||
@@ -884,66 +890,6 @@ async function whitelistCheck() {
|
||||
if (Config.config.forceChannelCheck && sponsorTimes?.length > 0) startSkipScheduleCheckingForStartSponsors();
|
||||
}
|
||||
|
||||
async function unlistedCheck() {
|
||||
if (!Config.config.allowExpirements || !Config.config.askAboutUnlistedVideos) return;
|
||||
|
||||
try {
|
||||
await utils.wait(() => !!videoInfo && !!document.getElementById("info-text")
|
||||
&& !!document.querySelector(".ytd-video-primary-info-renderer > .badge > yt-icon > svg"), 6000, 1000);
|
||||
|
||||
const isUnlisted = document.querySelector(".ytd-video-primary-info-renderer > .badge > yt-icon > svg > g > path")
|
||||
?.getAttribute("d")?.includes("M3.9 12c0-1.71 1.39-3.1 3.1-3.1h"); // Icon of unlisted badge
|
||||
const yearMatches = document.querySelector("#info-text > #info-strings > yt-formatted-string")
|
||||
?.innerHTML?.match(/20[0-9]{2}/);
|
||||
const year = yearMatches ? parseInt(yearMatches[0]) : -1;
|
||||
const isOld = !isNaN(year) && year < 2017 && year > 2004;
|
||||
const views = parseInt(videoInfo?.videoDetails?.viewCount);
|
||||
const isHighViews = views > 15000;
|
||||
|
||||
if (isUnlisted && isOld && isHighViews && (!sponsorTimes || sponsorTimes.length <= 0)) {
|
||||
// Ask if they want to submit this videoID
|
||||
const notice = new GenericNotice(skipNoticeContentContainer, "unlistedWarning", {
|
||||
title: chrome.i18n.getMessage("experimentUnlistedTitle"),
|
||||
textBoxes: chrome.i18n.getMessage("experimentUnlistedText").split("\n"),
|
||||
buttons: [
|
||||
{
|
||||
name: chrome.i18n.getMessage("experiementOptOut"),
|
||||
listener: () => {
|
||||
Config.config.allowExpirements = false;
|
||||
|
||||
notice.close();
|
||||
}
|
||||
},
|
||||
{
|
||||
name: chrome.i18n.getMessage("hideForever"),
|
||||
listener: () => {
|
||||
Config.config.askAboutUnlistedVideos = false;
|
||||
|
||||
notice.close();
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "Submit",
|
||||
listener: () => {
|
||||
utils.asyncRequestToServer("POST", "/api/unlistedVideo", {
|
||||
videoID: sponsorVideoID,
|
||||
year,
|
||||
views,
|
||||
channelID: channelIDInfo.status === ChannelIDStatus.Found ? channelIDInfo.id : undefined
|
||||
});
|
||||
|
||||
notice.close();
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns info about the next upcoming sponsor skip
|
||||
*/
|
||||
@@ -1297,6 +1243,7 @@ function startOrEndTimingNewSegment() {
|
||||
segment: [getRealCurrentTime()],
|
||||
UUID: null,
|
||||
category: Config.config.defaultCategory,
|
||||
source: SponsorSourceType.Local
|
||||
});
|
||||
} else {
|
||||
// Finish creating the new segment
|
||||
@@ -1350,8 +1297,9 @@ function updateSponsorTimesSubmitting(getFromConfig = true) {
|
||||
for (const segmentTime of segmentTimes) {
|
||||
sponsorTimesSubmitting.push({
|
||||
segment: segmentTime.segment,
|
||||
UUID: null,
|
||||
category: segmentTime.category
|
||||
UUID: segmentTime.UUID,
|
||||
category: segmentTime.category,
|
||||
source: segmentTime.source
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1385,9 +1333,11 @@ function openInfoMenu() {
|
||||
let htmlData = xmlhttp.responseText;
|
||||
// Hack to replace head data (title, favicon)
|
||||
htmlData = htmlData.replace(/<head>[\S\s]*<\/head>/gi, "");
|
||||
// Hack to replace body tag with div
|
||||
// Hack to replace body and html tag with div
|
||||
htmlData = htmlData.replace(/<body/gi, "<div");
|
||||
htmlData = htmlData.replace(/<\/body/gi, "</div");
|
||||
htmlData = htmlData.replace(/<html/gi, "<div");
|
||||
htmlData = htmlData.replace(/<\/html/gi, "</div");
|
||||
|
||||
popup.innerHTML = htmlData;
|
||||
|
||||
@@ -1421,11 +1371,12 @@ function openInfoMenu() {
|
||||
const settings = <HTMLImageElement> popup.querySelector("#sbPopupIconSettings");
|
||||
const edit = <HTMLImageElement> popup.querySelector("#sbPopupIconEdit");
|
||||
const check = <HTMLImageElement> popup.querySelector("#sbPopupIconCheck");
|
||||
const refreshSegments = <HTMLImageElement> popup.querySelector("#refreshSegments");
|
||||
logo.src = chrome.extension.getURL("icons/IconSponsorBlocker256px.png");
|
||||
settings.src = chrome.extension.getURL("icons/settings.svg");
|
||||
edit.src = chrome.extension.getURL("icons/pencil.svg");
|
||||
check.src = chrome.extension.getURL("icons/check.svg");
|
||||
check.src = chrome.extension.getURL("icons/thumb.svg");
|
||||
refreshSegments.src = chrome.extension.getURL("icons/refresh.svg");
|
||||
|
||||
parentNode.insertBefore(popup, parentNode.firstChild);
|
||||
|
||||
@@ -1522,7 +1473,15 @@ function vote(type: number, UUID: SegmentUUID, category?: Category, skipNotice?:
|
||||
//success (treat rate limits as a success)
|
||||
skipNotice.afterVote.bind(skipNotice)(utils.getSponsorTimeFromUUID(sponsorTimes, UUID), type, category);
|
||||
} else if (response.successType == -1) {
|
||||
skipNotice.setNoticeInfoMessage.bind(skipNotice)(utils.getErrorMessage(response.statusCode, response.responseText))
|
||||
if (response.statusCode === 403 && response.responseText.startsWith("Vote rejected due to a warning from a moderator.")) {
|
||||
skipNotice.setNoticeInfoMessageWithOnClick.bind(skipNotice)(() => {
|
||||
Chat.openWarningChat(response.responseText);
|
||||
skipNotice.closeListener.call(skipNotice);
|
||||
}, chrome.i18n.getMessage("voteRejectedWarning"));
|
||||
} else {
|
||||
skipNotice.setNoticeInfoMessage.bind(skipNotice)(utils.getErrorMessage(response.statusCode, response.responseText))
|
||||
}
|
||||
|
||||
skipNotice.resetVoteButtonInfo.bind(skipNotice)();
|
||||
}
|
||||
}
|
||||
@@ -1565,7 +1524,7 @@ function submitSponsorTimes() {
|
||||
async function sendSubmitMessage() {
|
||||
// Add loading animation
|
||||
playerButtons.submit.image.src = chrome.extension.getURL("icons/PlayerUploadIconSponsorBlocker.svg");
|
||||
playerButtons.submit.button.style.animation = "rotate 1s 0s infinite";
|
||||
const stopAnimation = utils.applyLoadingAnimation(playerButtons.submit.button, 1, () => updateEditButtonsOnPlayer());
|
||||
|
||||
//check if a sponsor exceeds the duration of the video
|
||||
for (let i = 0; i < sponsorTimesSubmitting.length; i++) {
|
||||
@@ -1597,28 +1556,23 @@ async function sendSubmitMessage() {
|
||||
});
|
||||
|
||||
if (response.status === 200) {
|
||||
// Handle submission success
|
||||
const submitButton = playerButtons.submit.button;
|
||||
|
||||
// Make the animation finite
|
||||
submitButton.style.animation = "rotate 1s";
|
||||
|
||||
// When the animation is over, hide the button
|
||||
const animationEndListener = () => {
|
||||
updateEditButtonsOnPlayer();
|
||||
|
||||
submitButton.style.animation = "none";
|
||||
|
||||
submitButton.removeEventListener("animationend", animationEndListener);
|
||||
};
|
||||
|
||||
submitButton.addEventListener("animationend", animationEndListener);
|
||||
stopAnimation();
|
||||
|
||||
// Remove segments from storage since they've already been submitted
|
||||
Config.config.segmentTimes.delete(sponsorVideoID);
|
||||
|
||||
const newSegments = sponsorTimesSubmitting;
|
||||
try {
|
||||
const recievedNewSegments = JSON.parse(response.responseText);
|
||||
if (recievedNewSegments?.length === newSegments.length) {
|
||||
for (let i = 0; i < recievedNewSegments.length; i++) {
|
||||
newSegments[i].UUID = recievedNewSegments[i].UUID;
|
||||
}
|
||||
}
|
||||
} catch(e) {} // eslint-disable-line no-empty
|
||||
|
||||
// Add submissions to current sponsors list
|
||||
sponsorTimes = (sponsorTimes || []).concat(sponsorTimesSubmitting);
|
||||
sponsorTimes = (sponsorTimes || []).concat(newSegments);
|
||||
|
||||
// Increase contribution count
|
||||
Config.config.sponsorTimesContributed = Config.config.sponsorTimesContributed + sponsorTimesSubmitting.length;
|
||||
@@ -1636,7 +1590,11 @@ async function sendSubmitMessage() {
|
||||
playerButtons.submit.button.style.animation = "unset";
|
||||
playerButtons.submit.image.src = chrome.extension.getURL("icons/PlayerUploadFailedIconSponsorBlocker.svg");
|
||||
|
||||
alert(utils.getErrorMessage(response.status, response.responseText));
|
||||
if (response.status === 403 && response.responseText.startsWith("Submission rejected due to a warning from a moderator.")) {
|
||||
Chat.openWarningChat(response.responseText);
|
||||
} else {
|
||||
alert(utils.getErrorMessage(response.status, response.responseText));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
44
src/js-components/chat.ts
Normal file
44
src/js-components/chat.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import Config from "../config";
|
||||
import Utils from "../utils";
|
||||
const utils = new Utils();
|
||||
|
||||
export interface ChatConfig {
|
||||
displayName: string,
|
||||
composerInitialValue?: string,
|
||||
customDescription?: string
|
||||
}
|
||||
|
||||
export function openChat(config: ChatConfig): void {
|
||||
const chat = document.createElement("div");
|
||||
chat.classList.add("sbChatNotice");
|
||||
chat.style.zIndex = "2000";
|
||||
|
||||
const iframe= document.createElement("iframe");
|
||||
iframe.src = "https://chat.sponsor.ajay.app/#" + utils.objectToURI("", config, false);
|
||||
chat.appendChild(iframe);
|
||||
|
||||
const closeButton = document.createElement("img");
|
||||
closeButton.classList.add("sbChatClose");
|
||||
closeButton.src = chrome.extension.getURL("icons/close.png");
|
||||
closeButton.addEventListener("click", () => {
|
||||
chat.remove();
|
||||
closeButton.remove();
|
||||
});
|
||||
chat.appendChild(closeButton);
|
||||
|
||||
const referenceNode = utils.findReferenceNode();
|
||||
referenceNode.prepend(chat);
|
||||
}
|
||||
|
||||
export async function openWarningChat(warningMessage: string): Promise<void> {
|
||||
const userNameData = await utils.asyncRequestToServer("GET", "/api/getUsername?userID=" + Config.config.userID);
|
||||
const userName = userNameData.ok ? JSON.parse(userNameData.responseText).userName : "";
|
||||
const publicUserID = await utils.getHash(Config.config.userID);
|
||||
|
||||
openChat({
|
||||
displayName: `${userName ? `${userName} | `: ``}${userName !== publicUserID ? publicUserID : ``}`,
|
||||
composerInitialValue: `I got a warning and want to know what I need to do to improve. ` +
|
||||
`Warning reason: ${warningMessage.match(/Warning reason: '(.+)'/)[1]}`,
|
||||
customDescription: chrome.i18n.getMessage("warningChatInfo")
|
||||
});
|
||||
}
|
||||
@@ -16,7 +16,8 @@ interface DefaultMessage {
|
||||
| "getVideoID"
|
||||
| "getChannelID"
|
||||
| "isChannelWhitelisted"
|
||||
| "submitTimes";
|
||||
| "submitTimes"
|
||||
| "refreshSegments";
|
||||
}
|
||||
|
||||
interface BoolValueMessage {
|
||||
@@ -52,5 +53,6 @@ export type MessageResponse =
|
||||
| GetVideoIdResponse
|
||||
| GetChannelIDResponse
|
||||
| SponsorStartResponse
|
||||
| IsChannelWhitelistedResponse;
|
||||
| IsChannelWhitelistedResponse
|
||||
| Record<string, never>;
|
||||
|
||||
|
||||
32
src/popup.ts
32
src/popup.ts
@@ -102,6 +102,7 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
|
||||
"videoFound",
|
||||
"sponsorMessageTimes",
|
||||
//"downloadedSponsorMessageTimes",
|
||||
"refreshSegmentsButton",
|
||||
"whitelistButton",
|
||||
"sbDonate"
|
||||
].forEach(id => PageElements[id] = document.getElementById(id));
|
||||
@@ -131,6 +132,7 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
|
||||
PageElements.submitUsername.addEventListener("click", submitUsername);
|
||||
PageElements.optionsButton.addEventListener("click", openOptions);
|
||||
PageElements.helpButton.addEventListener("click", openHelp);
|
||||
PageElements.refreshSegmentsButton.addEventListener("click", refreshSegments);
|
||||
|
||||
/** If true, the content script is in the process of creating a new segment. */
|
||||
let creatingSegment = false;
|
||||
@@ -239,6 +241,7 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
|
||||
|
||||
function onTabs(tabs) {
|
||||
messageHandler.sendMessage(tabs[0].id, {message: 'getVideoID'}, function(result) {
|
||||
console.log(result)
|
||||
if (result !== undefined && result.videoID) {
|
||||
currentVideoID = result.videoID;
|
||||
creatingSegment = result.creatingSegment;
|
||||
@@ -290,10 +293,12 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
|
||||
|
||||
if (request.found) {
|
||||
PageElements.videoFound.innerHTML = chrome.i18n.getMessage("sponsorFound");
|
||||
PageElements.refreshSegmentsButton.classList.remove("hidden");
|
||||
|
||||
displayDownloadedSponsorTimes(request);
|
||||
} else {
|
||||
PageElements.videoFound.innerHTML = chrome.i18n.getMessage("sponsor404");
|
||||
PageElements.refreshSegmentsButton.classList.add("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,13 +419,13 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
|
||||
const upvoteButton = document.createElement("img");
|
||||
upvoteButton.id = "sponsorTimesUpvoteButtonsContainer" + UUID;
|
||||
upvoteButton.className = "voteButton";
|
||||
upvoteButton.src = chrome.extension.getURL("icons/thumbs_up.svg");
|
||||
upvoteButton.src = chrome.runtime.getURL("icons/thumbs_up.svg");
|
||||
upvoteButton.addEventListener("click", () => vote(1, UUID));
|
||||
|
||||
const downvoteButton = document.createElement("img");
|
||||
downvoteButton.id = "sponsorTimesDownvoteButtonsContainer" + UUID;
|
||||
downvoteButton.className = "voteButton";
|
||||
downvoteButton.src = chrome.extension.getURL("icons/thumbs_down.svg");
|
||||
downvoteButton.src = chrome.runtime.getURL("icons/thumbs_down.svg");
|
||||
downvoteButton.addEventListener("click", () => vote(0, UUID));
|
||||
|
||||
//uuid button
|
||||
@@ -428,8 +433,12 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
|
||||
const uuidButton = document.createElement("img");
|
||||
uuidButton.id = "sponsorTimesCopyUUIDButtonContainer" + UUID;
|
||||
uuidButton.className = "voteButton";
|
||||
uuidButton.src = chrome.extension.getURL("icons/clipboard.svg");
|
||||
uuidButton.addEventListener("click", () => navigator.clipboard.writeText(UUID));
|
||||
uuidButton.src = chrome.runtime.getURL("icons/clipboard.svg");
|
||||
uuidButton.addEventListener("click", () => {
|
||||
navigator.clipboard.writeText(UUID);
|
||||
const stopAnimation = utils.applyLoadingAnimation(uuidButton, 0.3);
|
||||
stopAnimation();
|
||||
});
|
||||
|
||||
//add thumbs up, thumbs down and uuid copy buttons to the container
|
||||
voteButtonsContainer.appendChild(upvoteButton);
|
||||
@@ -676,6 +685,21 @@ async function runThePopup(messageListener?: MessageListener): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
function refreshSegments() {
|
||||
const stopAnimation = utils.applyLoadingAnimation(PageElements.refreshSegmentsButton, 0.3);
|
||||
|
||||
messageHandler.query({
|
||||
active: true,
|
||||
currentWindow: true
|
||||
}, tabs => {
|
||||
messageHandler.sendMessage(
|
||||
tabs[0].id,
|
||||
{message: 'refreshSegments'},
|
||||
() => stopAnimation()
|
||||
)}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Should skipping be disabled (visuals stay)
|
||||
*/
|
||||
|
||||
@@ -59,6 +59,11 @@ export enum CategoryActionType {
|
||||
export type SegmentUUID = string & { __segmentUUIDBrand: unknown };
|
||||
export type Category = string & { __categoryBrand: unknown };
|
||||
|
||||
export enum SponsorSourceType {
|
||||
Server = undefined,
|
||||
Local = 1
|
||||
}
|
||||
|
||||
export interface SponsorTime {
|
||||
segment: [number] | [number, number];
|
||||
UUID: SegmentUUID;
|
||||
@@ -66,6 +71,7 @@ export interface SponsorTime {
|
||||
category: Category;
|
||||
|
||||
hidden?: SponsorHideType;
|
||||
source?: SponsorSourceType;
|
||||
}
|
||||
|
||||
export interface PreviewBarOption {
|
||||
|
||||
52
src/utils.ts
52
src/utils.ts
@@ -167,6 +167,31 @@ export default class Utils {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a spinning animation and returns a function to be called when it should be stopped
|
||||
* The callback will be called when the animation is finished
|
||||
* It waits until a full rotation is complete
|
||||
*/
|
||||
applyLoadingAnimation(element: HTMLElement, time: number, callback?: () => void): () => void {
|
||||
element.style.animation = `rotate ${time}s 0s infinite`;
|
||||
|
||||
return () => {
|
||||
// Make the animation finite
|
||||
element.style.animation = `rotate ${time}s`;
|
||||
|
||||
// When the animation is over, hide the button
|
||||
const animationEndListener = () => {
|
||||
if (callback) callback();
|
||||
|
||||
element.style.animation = "none";
|
||||
|
||||
element.removeEventListener("animationend", animationEndListener);
|
||||
};
|
||||
|
||||
element.addEventListener("animationend", animationEndListener);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges any overlapping timestamp ranges into single segments and returns them as a new array.
|
||||
*/
|
||||
@@ -253,7 +278,8 @@ export default class Utils {
|
||||
|
||||
getLocalizedMessage(text: string): string | false {
|
||||
const valNewH = text.replace(/__MSG_(\w+)__/g, function(match, v1) {
|
||||
return v1 ? chrome.i18n.getMessage(v1).replace("\n", "<br/>") : "";
|
||||
return v1 ? chrome.i18n.getMessage(v1).replace(/</g, "<")
|
||||
.replace(/"/g, """).replace(/\n/g, "<br/>") : "";
|
||||
});
|
||||
|
||||
if(valNewH != text) {
|
||||
@@ -398,6 +424,19 @@ export default class Utils {
|
||||
return referenceNode;
|
||||
}
|
||||
|
||||
objectToURI<T>(url: string, data: T, includeQuestionMark: boolean): string {
|
||||
let counter = 0;
|
||||
for (const key in data) {
|
||||
const seperator = (url.includes("?") || counter > 0) ? "&" : (includeQuestionMark ? "?" : "");
|
||||
const value = (typeof(data[key]) === "string") ? data[key] as unknown as string : JSON.stringify(data[key]);
|
||||
url += seperator + encodeURIComponent(key) + "=" + encodeURIComponent(value);
|
||||
|
||||
counter++;
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
getFormattedTime(seconds: number, precise?: boolean): string {
|
||||
const hours = Math.floor(seconds / 60 / 60);
|
||||
const minutes = Math.floor(seconds / 60) % 60;
|
||||
@@ -462,14 +501,13 @@ export default class Utils {
|
||||
async getHash(value: string, times = 5000): Promise<string> {
|
||||
if (times <= 0) return "";
|
||||
|
||||
let hashBuffer = new TextEncoder().encode(value).buffer;
|
||||
|
||||
let hashHex = value;
|
||||
for (let i = 0; i < times; i++) {
|
||||
hashBuffer = await crypto.subtle.digest('SHA-256', hashBuffer);
|
||||
}
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(hashHex).buffer);
|
||||
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
||||
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
||||
hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
return hashHex;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user