Merge branch 'master' of https://github.com/ajayyy/SponsorBlock into experimental-ajay

This commit is contained in:
Ajay Ramachandran 2020-01-09 14:28:40 -05:00
commit 1715ee327f
8 changed files with 502 additions and 527 deletions

175
SB.js Normal file
View file

@ -0,0 +1,175 @@
SB = {};
// Function setup
Map.prototype.toJSON = function() {
return Array.from(this.entries());
};
class MapIO {
constructor(id) {
this.id = id;
this.map = SB.localConfig[this.id];
}
set(key, value) {
this.map.set(key, value);
SB.config.handler.set(undefined, this.id, encodeStoredItem(this.map));
return this.map;
}
get(key) {
return this.map.get(key);
}
has(key) {
return this.map.has(key);
}
deleteProperty(key) {
if (this.map.has(key)) {
this.map.delete(key);
return true;
} else {
return false;
}
}
size() {
return this.map.size;
}
delete(key) {
this.map.delete(key);
SB.config.handler.set(undefined, this.id, encodeStoredItem(this.map));
}
}
/**
* A Map cannot be stored in the chrome storage.
* This data will be encoded into an array instead as specified by the toJSON function.
*
* @param {*} data
*/
function encodeStoredItem(data) {
if(!(data instanceof Map)) return data;
return JSON.stringify(data);
}
/**
* A Map cannot be stored in the chrome storage.
* This data will be decoded from the array it is stored in
*
* @param {*} data
*/
function decodeStoredItem(data) {
if(typeof data !== "string") return data;
try {
let str = JSON.parse(data);
if(!Array.isArray(str)) return data;
return new Map(str);
} catch(e) {
// If all else fails, return the data
return data;
}
}
function configProxy() {
chrome.storage.onChanged.addListener((changes, namespace) => {
for (key in changes) {
SB.localConfig[key] = decodeStoredItem(changes[key].newValue);
}
});
var handler = {
set: function(obj, prop, value) {
SB.localConfig[prop] = value;
chrome.storage.sync.set({
[prop]: encodeStoredItem(value)
});
},
get: function(obj, prop) {
let data = SB.localConfig[prop];
if(data instanceof Map) data = new MapIO(prop);
return obj[prop] || data;
}
};
return new Proxy({handler}, handler);
}
function fetchConfig() {
return new Promise((resolve, reject) => {
chrome.storage.sync.get(null, function(items) {
SB.localConfig = items; // Data is ready
resolve();
});
});
}
function migrateOldFormats() { // Convert sponsorTimes format
for (key in SB.localConfig) {
if (key.startsWith("sponsorTimes") && key !== "sponsorTimes" && key !== "sponsorTimesContributed") {
SB.config.sponsorTimes.set(key.substr(12), SB.config[key]);
delete SB.config[key];
}
}
}
async function setupConfig() {
await fetchConfig();
addDefaults();
convertJSON();
SB.config = configProxy();
migrateOldFormats();
}
SB.defaults = {
"sponsorTimes": new Map(),
"startSponsorKeybind": ";",
"submitKeybind": "'",
"minutesSaved": 0,
"skipCount": 0,
"sponsorTimesContributed": 0,
"disableSkipping": false,
"disableAutoSkip": false,
"trackViewCount": true,
"dontShowNotice": false,
"hideVideoPlayerControls": false,
"hideInfoButtonPlayerControls": false,
"hideDeleteButtonPlayerControls": false,
"hideDiscordLaunches": 0,
"hideDiscordLink": false
}
// Reset config
function resetConfig() {
SB.config = SB.defaults;
};
function convertJSON() {
Object.keys(SB.defaults).forEach(key => {
SB.localConfig[key] = decodeStoredItem(SB.localConfig[key], key);
});
}
// Add defaults
function addDefaults() {
Object.keys(SB.defaults).forEach(key => {
if(!SB.localConfig.hasOwnProperty(key)) {
SB.localConfig[key] = SB.defaults[key];
}
});
};
// Sync config
setupConfig();

View file

@ -4,7 +4,9 @@ chrome.tabs.onUpdated.addListener(function(tabId) {
}, () => void chrome.runtime.lastError ); // Suppress error on Firefox }, () => void chrome.runtime.lastError ); // Suppress error on Firefox
}); });
chrome.runtime.onMessage.addListener(function (request, sender, callback) { chrome.runtime.onMessage.addListener(async function (request, sender, callback) {
await wait(() => SB.config !== undefined);
switch(request.message) { switch(request.message) {
case "submitTimes": case "submitTimes":
submitTimes(request.videoID, callback); submitTimes(request.videoID, callback);
@ -15,11 +17,12 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) {
addSponsorTime(request.time, request.videoID, callback); addSponsorTime(request.time, request.videoID, callback);
//this allows the callback to be called later //this allows the callback to be called later
return true; return true;
case "getSponsorTimes": case "getSponsorTimes":
getSponsorTimes(request.videoID, function(sponsorTimes) { getSponsorTimes(request.videoID, function(sponsorTimes) {
callback({ callback({
sponsorTimes: sponsorTimes sponsorTimes: sponsorTimes
}) })
}); });
@ -43,37 +46,31 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) {
//add help page on install //add help page on install
chrome.runtime.onInstalled.addListener(function (object) { chrome.runtime.onInstalled.addListener(function (object) {
setTimeout(function() { setTimeout(function() {
chrome.storage.sync.get(["userID"], function(result) { const userID = SB.config.userID;
const userID = result.userID;
// If there is no userID, then it is the first install. // If there is no userID, then it is the first install.
if (!userID){ if (!userID){
//open up the install page //open up the install page
chrome.tabs.create({url: chrome.extension.getURL("/help/index_en.html")}); chrome.tabs.create({url: chrome.extension.getURL("/help/index_en.html")});
//generate a userID //generate a userID
const newUserID = generateUserID(); const newUserID = generateUserID();
//save this UUID //save this UUID
chrome.storage.sync.set({ SB.config.userID = newUserID;
"userID": newUserID }
});
}
});
}, 1500); }, 1500);
}); });
//gets the sponsor times from memory //gets the sponsor times from memory
function getSponsorTimes(videoID, callback) { function getSponsorTimes(videoID, callback) {
let sponsorTimes = []; let sponsorTimes = [];
let sponsorTimeKey = "sponsorTimes" + videoID; let sponsorTimesStorage = SB.config.sponsorTimes.get(videoID);
chrome.storage.sync.get([sponsorTimeKey], function(result) {
let sponsorTimesStorage = result[sponsorTimeKey]; if (sponsorTimesStorage != undefined && sponsorTimesStorage.length > 0) {
if (sponsorTimesStorage != undefined && sponsorTimesStorage.length > 0) { sponsorTimes = sponsorTimesStorage;
sponsorTimes = sponsorTimesStorage; }
}
callback(sponsorTimes);
callback(sponsorTimes)
});
} }
function addSponsorTime(time, videoID, callback) { function addSponsorTime(time, videoID, callback) {
@ -91,21 +88,18 @@ function addSponsorTime(time, videoID, callback) {
} }
//save this info //save this info
let sponsorTimeKey = "sponsorTimes" + videoID; SB.config.sponsorTimes.set(videoID, sponsorTimes);
chrome.storage.sync.set({[sponsorTimeKey]: sponsorTimes}, callback); callback();
}); });
} }
function submitVote(type, UUID, callback) { function submitVote(type, UUID, callback) {
chrome.storage.sync.get(["userID"], function(result) { let userID = SB.config.userID;
let userID = result.userID;
if (userID == undefined || userID === "undefined") { if (userID == undefined || userID === "undefined") {
//generate one //generate one
userID = generateUserID(); userID = generateUserID();
chrome.storage.sync.set({ SB.config.userID = userID;
"userID": userID
});
} }
//publish this vote //publish this vote
@ -128,74 +122,62 @@ function submitVote(type, UUID, callback) {
}); });
} }
}) })
})
} }
function submitTimes(videoID, callback) { async function submitTimes(videoID, callback) {
//get the video times from storage //get the video times from storage
let sponsorTimeKey = 'sponsorTimes' + videoID; let sponsorTimes = SB.config.sponsorTimes.get(videoID);
chrome.storage.sync.get([sponsorTimeKey, "userID"], async function(result) { let userID = SB.config.userID;
let sponsorTimes = result[sponsorTimeKey];
let userID = result.userID; if (sponsorTimes != undefined && sponsorTimes.length > 0) {
let durationResult = await new Promise((resolve, reject) => {
if (sponsorTimes != undefined && sponsorTimes.length > 0) { chrome.tabs.query({
let durationResult = await new Promise((resolve, reject) => { active: true,
chrome.tabs.query({ currentWindow: true
active: true, }, function(tabs) {
currentWindow: true chrome.tabs.sendMessage(tabs[0].id, {
}, function(tabs) { message: "getVideoDuration"
chrome.tabs.sendMessage(tabs[0].id, { }, (response) => resolve(response));
message: "getVideoDuration"
}, (response) => resolve(response));
});
}); });
});
//check if a sponsor exceeds the duration of the video //check if a sponsor exceeds the duration of the video
for (let i = 0; i < sponsorTimes.length; i++) { for (let i = 0; i < sponsorTimes.length; i++) {
if (sponsorTimes[i][1] > durationResult.duration) { if (sponsorTimes[i][1] > durationResult.duration) {
sponsorTimes[i][1] = durationResult.duration; sponsorTimes[i][1] = durationResult.duration;
}
}
//submit these times
for (let i = 0; i < sponsorTimes.length; i++) {
//to prevent it from happeneing twice
let increasedContributionAmount = false;
//submit the sponsorTime
sendRequestToServer("GET", "/api/postVideoSponsorTimes?videoID=" + videoID + "&startTime=" + sponsorTimes[i][0] + "&endTime=" + sponsorTimes[i][1]
+ "&userID=" + userID, function(xmlhttp, error) {
if (xmlhttp.readyState == 4 && !error) {
callback({
statusCode: xmlhttp.status
});
if (xmlhttp.status == 200) {
//add these to the storage log
chrome.storage.sync.get(["sponsorTimesContributed"], function(result) {
let currentContributionAmount = 0;
if (result.sponsorTimesContributed != undefined) {
//current contribution amount is known
currentContributionAmount = result.sponsorTimesContributed;
}
//save the amount contributed
if (!increasedContributionAmount) {
increasedContributionAmount = true;
chrome.storage.sync.set({"sponsorTimesContributed": currentContributionAmount + sponsorTimes.length});
}
});
}
} else if (error) {
callback({
statusCode: -1
});
}
});
} }
} }
});
//submit these times
for (let i = 0; i < sponsorTimes.length; i++) {
//to prevent it from happeneing twice
let increasedContributionAmount = false;
//submit the sponsorTime
sendRequestToServer("GET", "/api/postVideoSponsorTimes?videoID=" + videoID + "&startTime=" + sponsorTimes[i][0] + "&endTime=" + sponsorTimes[i][1]
+ "&userID=" + userID, function(xmlhttp, error) {
if (xmlhttp.readyState == 4 && !error) {
callback({
statusCode: xmlhttp.status
});
if (xmlhttp.status == 200) {
//add these to the storage log
currentContributionAmount = SB.config.sponsorTimesContributed;
//save the amount contributed
if (!increasedContributionAmount) {
increasedContributionAmount = true;
SB.config.sponsorTimesContributed = currentContributionAmount + sponsorTimes.length;
}
}
} else if (error) {
callback({
statusCode: -1
});
}
});
}
}
} }
function sendRequestToServer(type, address, callback) { function sendRequestToServer(type, address, callback) {
@ -215,4 +197,4 @@ function sendRequestToServer(type, address, callback) {
//submit this request //submit this request
xmlhttp.send(); xmlhttp.send();
} }

View file

@ -58,11 +58,6 @@ var lastSponsorTimeSkippedUUID = null;
//if showing the start sponsor button or the end sponsor button on the player //if showing the start sponsor button or the end sponsor button on the player
var showingStartSponsor = true; var showingStartSponsor = true;
//should the video controls buttons be added
var hideVideoPlayerControls = false;
var hideInfoButtonPlayerControls = false;
var hideDeleteButtonPlayerControls = false;
//the sponsor times being prepared to be submitted //the sponsor times being prepared to be submitted
var sponsorTimesSubmitting = []; var sponsorTimesSubmitting = [];
@ -70,54 +65,6 @@ var sponsorTimesSubmitting = [];
//this is used to close the popup on YouTube when the other popup opens //this is used to close the popup on YouTube when the other popup opens
var popupInitialised = false; var popupInitialised = false;
//should skips happen at all
var disableSkipping = false;
chrome.storage.sync.get(["disableSkipping"], function(result) {
let disableSkippingStorage = result.disableSkipping;
if (disableSkippingStorage != undefined) {
disableSkipping = disableSkippingStorage;
}
});
//should skips be manual
var disableAutoSkip = false;
chrome.storage.sync.get(["disableAutoSkip"], function(result) {
let disableAutoSkipStorage = result.disableAutoSkip;
if (disableAutoSkipStorage != undefined) {
disableAutoSkip = disableAutoSkipStorage;
}
});
//should view counts be tracked
var trackViewCount = false;
chrome.storage.sync.get(["trackViewCount"], function(result) {
let trackViewCountStorage = result.trackViewCount;
if (trackViewCountStorage != undefined) {
trackViewCount = trackViewCountStorage;
} else {
trackViewCount = true;
}
});
//if the notice should not be shown
//happens when the user click's the "Don't show notice again" button
//option renamed when new notice was made
var dontShowNotice = false;
chrome.storage.sync.get(["dontShowNotice"], function(result) {
let dontShowNoticeAgain = result.dontShowNotice;
if (dontShowNoticeAgain != undefined) {
dontShowNotice = dontShowNoticeAgain;
}
});
//load the legacy option to hide the notice
var dontShowNoticeOld = false;
chrome.storage.sync.get(["dontShowNoticeAgain"], function(result) {
let dontShowNoticeAgain = result.dontShowNoticeAgain;
if (dontShowNoticeAgain != undefined) {
dontShowNoticeOld = dontShowNoticeAgain;
}
});
//get messages from the background script and the popup //get messages from the background script and the popup
chrome.runtime.onMessage.addListener(messageListener); chrome.runtime.onMessage.addListener(messageListener);
@ -126,7 +73,6 @@ function messageListener(request, sender, sendResponse) {
switch(request.message){ switch(request.message){
case "update": case "update":
videoIDChange(getYouTubeVideoID(document.URL)); videoIDChange(getYouTubeVideoID(document.URL));
break; break;
case "sponsorStart": case "sponsorStart":
sponsorMessageStarted(sendResponse); sponsorMessageStarted(sendResponse);
@ -191,35 +137,35 @@ function messageListener(request, sender, sendResponse) {
break; break;
case "dontShowNotice": case "dontShowNotice":
dontShowNotice = false; SB.config.dontShowNotice = true;
break; break;
case "changeStartSponsorButton": case "changeStartSponsorButton":
changeStartSponsorButton(request.showStartSponsor, request.uploadButtonVisible); changeStartSponsorButton(request.showStartSponsor, request.uploadButtonVisible);
break; break;
case "showNoticeAgain": case "showNoticeAgain":
dontShowNotice = false; SB.config.dontShowNotice = true;
break; break;
case "changeVideoPlayerControlsVisibility": case "changeVideoPlayerControlsVisibility":
hideVideoPlayerControls = request.value; SB.config.hideVideoPlayerControls = request.value;
updateVisibilityOfPlayerControlsButton(); updateVisibilityOfPlayerControlsButton();
break; break;
case "changeInfoButtonPlayerControlsVisibility": case "changeInfoButtonPlayerControlsVisibility":
hideInfoButtonPlayerControls = request.value; SB.config.hideInfoButtonPlayerControls = request.value;
updateVisibilityOfPlayerControlsButton(); updateVisibilityOfPlayerControlsButton();
break; break;
case "changeDeleteButtonPlayerControlsVisibility": case "changeDeleteButtonPlayerControlsVisibility":
hideDeleteButtonPlayerControls = request.value; SB.config.hideDeleteButtonPlayerControls = request.value;
updateVisibilityOfPlayerControlsButton(); updateVisibilityOfPlayerControlsButton();
break; break;
case "trackViewCount": case "trackViewCount":
trackViewCount = request.value; SB.config.trackViewCount = request.value;
break; break;
} }
} }
@ -231,19 +177,9 @@ document.onkeydown = async function(e){
let video = document.getElementById("movie_player"); let video = document.getElementById("movie_player");
let startSponsorKey = await new Promise((resolve, reject) => { let startSponsorKey = SB.config.startSponsorKeybind;
chrome.storage.sync.get(["startSponsorKeybind"], (result) => resolve(result));
});
let submitKey = await new Promise((resolve, reject) => {
chrome.storage.sync.get(["submitKeybind"], (result) => resolve(result));
});
if (startSponsorKey.startSponsorKeybind === undefined) { let submitKey = SB.config.submitKeybind;
startSponsorKey.startSponsorKeybind = ";"
}
if (submitKey.submitKeybind === undefined) {
submitKey.submitKeybind = "'"
}
//is the video in focus, otherwise they could be typing a comment //is the video in focus, otherwise they could be typing a comment
if (document.activeElement === video) { if (document.activeElement === video) {
@ -302,21 +238,17 @@ function videoIDChange(id) {
//warn them if they had unsubmitted times //warn them if they had unsubmitted times
if (previousVideoID != null) { if (previousVideoID != null) {
//get the sponsor times from storage //get the sponsor times from storage
let sponsorTimeKey = 'sponsorTimes' + previousVideoID; let sponsorTimes = SB.config.sponsorTimes.get(previousVideoID);
chrome.storage.sync.get([sponsorTimeKey], function(result) { if (sponsorTimes != undefined && sponsorTimes.length > 0) {
let sponsorTimes = result[sponsorTimeKey]; //warn them that they have unsubmitted sponsor times
chrome.runtime.sendMessage({
message: "alertPrevious",
previousVideoID: previousVideoID
})
}
if (sponsorTimes != undefined && sponsorTimes.length > 0) { //set the previous video id to the currentID
//warn them that they have unsubmitted sponsor times previousVideoID = id;
chrome.runtime.sendMessage({
message: "alertPrevious",
previousVideoID: previousVideoID
})
}
//set the previous video id to the currentID
previousVideoID = id;
});
} else { } else {
//set the previous id now, don't wait for chrome.storage.get //set the previous id now, don't wait for chrome.storage.get
previousVideoID = id; previousVideoID = id;
@ -358,30 +290,8 @@ function videoIDChange(id) {
} }
}); });
}); });
updateVisibilityOfPlayerControlsButton();
//see if video controls buttons should be added updateVisibilityOfPlayerControlsButton(false);
chrome.storage.sync.get(["hideVideoPlayerControls"], function(result) {
if (result.hideVideoPlayerControls != undefined) {
hideVideoPlayerControls = result.hideVideoPlayerControls;
}
updateVisibilityOfPlayerControlsButton();
});
chrome.storage.sync.get(["hideInfoButtonPlayerControls"], function(result) {
if (result.hideInfoButtonPlayerControls != undefined) {
hideInfoButtonPlayerControls = result.hideInfoButtonPlayerControls;
}
updateVisibilityOfPlayerControlsButton();
});
chrome.storage.sync.get(["hideDeleteButtonPlayerControls"], function(result) {
if (result.hideDeleteButtonPlayerControls != undefined) {
hideDeleteButtonPlayerControls = result.hideDeleteButtonPlayerControls;
}
updateVisibilityOfPlayerControlsButton(false);
});
} }
function sponsorsLookup(id, channelIDPromise) { function sponsorsLookup(id, channelIDPromise) {
@ -463,7 +373,7 @@ function sponsorsLookup(id, channelIDPromise) {
}); });
//add the event to run on the videos "ontimeupdate" //add the event to run on the videos "ontimeupdate"
if (!disableSkipping) { if (!SB.config.disableSkipping) {
v.ontimeupdate = function () { v.ontimeupdate = function () {
sponsorCheck(); sponsorCheck();
}; };
@ -542,20 +452,18 @@ function getChannelID() {
//checks if this channel is whitelisted, should be done only after the channelID has been loaded //checks if this channel is whitelisted, should be done only after the channelID has been loaded
function whitelistCheck() { function whitelistCheck() {
//see if this is a whitelisted channel //see if this is a whitelisted channel
chrome.storage.sync.get(["whitelistedChannels"], function(result) { let whitelistedChannels = SB.config.whitelistedChannels;
let whitelistedChannels = result.whitelistedChannels;
console.log(channelURL) console.log(channelURL)
if (whitelistedChannels != undefined && whitelistedChannels.includes(channelURL)) { if (whitelistedChannels != undefined && whitelistedChannels.includes(channelURL)) {
channelWhitelisted = true; channelWhitelisted = true;
} }
});
} }
//video skipping //video skipping
function sponsorCheck() { function sponsorCheck() {
if (disableSkipping) { if (SB.config.disableSkipping) {
// Make sure this isn't called again // Make sure this isn't called again
v.ontimeupdate = null; v.ontimeupdate = null;
return; return;
@ -621,7 +529,7 @@ function checkIfTimeToSkip(currentVideoTime, startTime, endTime) {
//skip fromt he start time to the end time for a certain index sponsor time //skip fromt he start time to the end time for a certain index sponsor time
function skipToTime(v, index, sponsorTimes, openNotice) { function skipToTime(v, index, sponsorTimes, openNotice) {
if (!disableAutoSkip) { if (!SB.config.disableAutoSkip) {
v.currentTime = sponsorTimes[index][1]; v.currentTime = sponsorTimes[index][1];
} }
@ -632,42 +540,23 @@ function skipToTime(v, index, sponsorTimes, openNotice) {
if (openNotice) { if (openNotice) {
//send out the message saying that a sponsor message was skipped //send out the message saying that a sponsor message was skipped
if (!dontShowNotice) { if (!SB.config.dontShowNotice) {
let skipNotice = new SkipNotice(this, currentUUID, disableAutoSkip); let skipNotice = new SkipNotice(this, currentUUID, SB.config.disableAutoSkip);
if (dontShowNoticeOld) {
//show why this notice is showing
skipNotice.addNoticeInfoMessage(chrome.i18n.getMessage("noticeUpdate"), chrome.i18n.getMessage("noticeUpdate2"));
//remove this setting
chrome.storage.sync.remove(["dontShowNoticeAgain"]);
dontShowNoticeOld = false;
}
//auto-upvote this sponsor //auto-upvote this sponsor
if (trackViewCount && !disableAutoSkip) { if (SB.config.trackViewCount && !SB.config.disableAutoSkip) {
vote(1, currentUUID, null); vote(1, currentUUID, null);
} }
} }
} }
//send telemetry that a this sponsor was skipped //send telemetry that a this sponsor was skipped
if (trackViewCount && !sponsorSkipped[index]) { if (SB.config.trackViewCount && !sponsorSkipped[index]) {
sendRequestToServer("POST", "/api/viewedVideoSponsorTime?UUID=" + currentUUID); sendRequestToServer("POST", "/api/viewedVideoSponsorTime?UUID=" + currentUUID);
if (!disableAutoSkip) { if (!SB.config.disableAutoSkip) {
// Count this as a skip // Count this as a skip
chrome.storage.sync.get(["minutesSaved"], function(result) { SB.config.minutesSaved = SB.config.minutesSaved + (sponsorTimes[index][1] - sponsorTimes[index][0]) / 60;
if (result.minutesSaved === undefined) result.minutesSaved = 0; SB.config.skipCount = SB.config.skipCount + 1;
chrome.storage.sync.set({"minutesSaved": result.minutesSaved + (sponsorTimes[index][1] - sponsorTimes[index][0]) / 60 });
});
chrome.storage.sync.get(["skipCount"], function(result) {
if (result.skipCount === undefined) result.skipCount = 0;
chrome.storage.sync.set({"skipCount": result.skipCount + 1 });
});
sponsorSkipped[index] = true; sponsorSkipped[index] = true;
} }
} }
@ -744,14 +633,14 @@ async function updateVisibilityOfPlayerControlsButton() {
await createButtons(); await createButtons();
if (hideVideoPlayerControls) { if (SB.config.hideDeleteButtonPlayerControls) {
removePlayerControlsButton(); removePlayerControlsButton();
} }
//don't show the info button on embeds //don't show the info button on embeds
if (hideInfoButtonPlayerControls || document.URL.includes("/embed/")) { if (SB.config.hideInfoButtonPlayerControls || document.URL.includes("/embed/")) {
document.getElementById("infoButton").style.display = "none"; document.getElementById("infoButton").style.display = "none";
} }
if (hideDeleteButtonPlayerControls) { if (SB.config.hideDeleteButtonPlayerControls) {
document.getElementById("deleteButton").style.display = "none"; document.getElementById("deleteButton").style.display = "none";
} }
} }
@ -803,7 +692,7 @@ async function changeStartSponsorButton(showStartSponsor, uploadButtonVisible) {
await wait(isSubmitButtonLoaded); await wait(isSubmitButtonLoaded);
//if it isn't visible, there is no data //if it isn't visible, there is no data
let shouldHide = (uploadButtonVisible && !hideDeleteButtonPlayerControls) ? "unset" : "none" let shouldHide = (uploadButtonVisible && !SB.config.hideDeleteButtonPlayerControls) ? "unset" : "none"
document.getElementById("deleteButton").style.display = shouldHide; document.getElementById("deleteButton").style.display = shouldHide;
if (showStartSponsor) { if (showStartSponsor) {
@ -811,7 +700,7 @@ async function changeStartSponsorButton(showStartSponsor, uploadButtonVisible) {
document.getElementById("startSponsorImage").src = chrome.extension.getURL("icons/PlayerStartIconSponsorBlocker256px.png"); document.getElementById("startSponsorImage").src = chrome.extension.getURL("icons/PlayerStartIconSponsorBlocker256px.png");
document.getElementById("startSponsorButton").setAttribute("title", chrome.i18n.getMessage("sponsorStart")); document.getElementById("startSponsorButton").setAttribute("title", chrome.i18n.getMessage("sponsorStart"));
if (document.getElementById("startSponsorImage").style.display != "none" && uploadButtonVisible && !hideInfoButtonPlayerControls) { if (document.getElementById("startSponsorImage").style.display != "none" && uploadButtonVisible && !SB.config.hideInfoButtonPlayerControls) {
document.getElementById("submitButton").style.display = "unset"; document.getElementById("submitButton").style.display = "unset";
} else if (!uploadButtonVisible) { } else if (!uploadButtonVisible) {
//disable submit button //disable submit button
@ -906,28 +795,24 @@ function clearSponsorTimes() {
let currentVideoID = sponsorVideoID; let currentVideoID = sponsorVideoID;
let sponsorTimeKey = 'sponsorTimes' + currentVideoID; let sponsorTimes = SB.config.sponsorTimes.get(currentVideoID);
chrome.storage.sync.get([sponsorTimeKey], function(result) {
let sponsorTimes = result[sponsorTimeKey];
if (sponsorTimes != undefined && sponsorTimes.length > 0) { if (sponsorTimes != undefined && sponsorTimes.length > 0) {
let confirmMessage = chrome.i18n.getMessage("clearThis") + getSponsorTimesMessage(sponsorTimes); let confirmMessage = chrome.i18n.getMessage("clearThis") + getSponsorTimesMessage(sponsorTimes);
confirmMessage += chrome.i18n.getMessage("confirmMSG") confirmMessage += chrome.i18n.getMessage("confirmMSG")
if(!confirm(confirmMessage)) return; if(!confirm(confirmMessage)) return;
//clear the sponsor times //clear the sponsor times
let sponsorTimeKey = "sponsorTimes" + currentVideoID; SB.config.sponsorTimes.delete(currentVideoID);
chrome.storage.sync.set({[sponsorTimeKey]: []});
//clear sponsor times submitting //clear sponsor times submitting
sponsorTimesSubmitting = []; sponsorTimesSubmitting = [];
updatePreviewBar(); updatePreviewBar();
//set buttons to be correct //set buttons to be correct
changeStartSponsorButton(true, false); changeStartSponsorButton(true, false);
} }
});
} }
//if skipNotice is null, it will not affect the UI //if skipNotice is null, it will not affect the UI
@ -949,17 +834,12 @@ function vote(type, UUID, skipNotice) {
sponsorSkipped[sponsorIndex] = false; sponsorSkipped[sponsorIndex] = false;
} }
// Count this as a skip // Count this as a skip
chrome.storage.sync.get(["minutesSaved"], function(result) { SB.config.minutesSaved = SB.config.minutesSaved + factor * (sponsorTimes[sponsorIndex][1] - sponsorTimes[sponsorIndex][0]) / 60;
if (result.minutesSaved === undefined) result.minutesSaved = 0;
SB.config.skipCount = 0;
chrome.storage.sync.set({"minutesSaved": result.minutesSaved + factor * (sponsorTimes[sponsorIndex][1] - sponsorTimes[sponsorIndex][0]) / 60 }); SB.config.skipCount = SB.config.skipCount + factor * 1;
});
chrome.storage.sync.get(["skipCount"], function(result) {
if (result.skipCount === undefined) result.skipCount = 0;
chrome.storage.sync.set({"skipCount": result.skipCount + factor * 1 });
});
} }
chrome.runtime.sendMessage({ chrome.runtime.sendMessage({
@ -997,10 +877,7 @@ function closeAllSkipNotices(){
} }
function dontShowNoticeAgain() { function dontShowNoticeAgain() {
chrome.storage.sync.set({"dontShowNotice": true}); SB.config.dontShowNotice = true;
dontShowNotice = true;
closeAllSkipNotices(); closeAllSkipNotices();
} }
@ -1027,30 +904,27 @@ function submitSponsorTimes() {
let currentVideoID = sponsorVideoID; let currentVideoID = sponsorVideoID;
let sponsorTimeKey = 'sponsorTimes' + currentVideoID; let sponsorTimes = SB.config.sponsorTimes.get(currentVideoID);
chrome.storage.sync.get([sponsorTimeKey], function(result) {
let sponsorTimes = result[sponsorTimeKey];
if (sponsorTimes != undefined && sponsorTimes.length > 0) { if (sponsorTimes != undefined && sponsorTimes.length > 0) {
//check if a sponsor exceeds the duration of the video //check if a sponsor exceeds the duration of the video
for (let i = 0; i < sponsorTimes.length; i++) { for (let i = 0; i < sponsorTimes.length; i++) {
if (sponsorTimes[i][1] > v.duration) { if (sponsorTimes[i][1] > v.duration) {
sponsorTimes[i][1] = v.duration; sponsorTimes[i][1] = v.duration;
}
} }
//update sponsorTimes
chrome.storage.sync.set({[sponsorTimeKey]: sponsorTimes});
//update sponsorTimesSubmitting
sponsorTimesSubmitting = sponsorTimes;
let confirmMessage = chrome.i18n.getMessage("submitCheck") + "\n\n" + getSponsorTimesMessage(sponsorTimes)
+ "\n\n" + chrome.i18n.getMessage("confirmMSG") + "\n\n" + chrome.i18n.getMessage("guildlinesSummary");
if(!confirm(confirmMessage)) return;
sendSubmitMessage();
} }
}); //update sponsorTimes
SB.config.sponsorTimes.set(currentVideoID, sponsorTimes);
//update sponsorTimesSubmitting
sponsorTimesSubmitting = sponsorTimes;
let confirmMessage = chrome.i18n.getMessage("submitCheck") + "\n\n" + getSponsorTimesMessage(sponsorTimes)
+ "\n\n" + chrome.i18n.getMessage("confirmMSG") + "\n\n" + chrome.i18n.getMessage("guildlinesSummary");
if(!confirm(confirmMessage)) return;
sendSubmitMessage();
}
} }
@ -1085,8 +959,7 @@ function sendSubmitMessage(){
submitButton.addEventListener("animationend", animationEndListener); submitButton.addEventListener("animationend", animationEndListener);
//clear the sponsor times //clear the sponsor times
let sponsorTimeKey = "sponsorTimes" + currentVideoID; SB.config.sponsorTimes.delete(currentVideoID);
chrome.storage.sync.set({[sponsorTimeKey]: []});
//add submissions to current sponsors list //add submissions to current sponsors list
sponsorTimes = sponsorTimes.concat(sponsorTimesSubmitting); sponsorTimes = sponsorTimes.concat(sponsorTimesSubmitting);

View file

@ -6,6 +6,7 @@
"description": "__MSG_Description__", "description": "__MSG_Description__",
"content_scripts": [ "content_scripts": [
{ {
"run_at": "document_start",
"matches": [ "matches": [
"https://*.youtube.com/*", "https://*.youtube.com/*",
"https://www.youtube-nocookie.com/embed/*" "https://www.youtube-nocookie.com/embed/*"
@ -13,6 +14,7 @@
"all_frames": true, "all_frames": true,
"js": [ "js": [
"config.js", "config.js",
"SB.js",
"utils/previewBar.js", "utils/previewBar.js",
"utils/skipNotice.js", "utils/skipNotice.js",
"utils.js", "utils.js",
@ -52,6 +54,7 @@
}, },
"background": { "background": {
"scripts":[ "scripts":[
"SB.js",
"utils.js", "utils.js",
"config.js", "config.js",
"background.js" "background.js"

View file

@ -4,6 +4,7 @@
<link href="options.css" rel="stylesheet"/> <link href="options.css" rel="stylesheet"/>
<script src="../utils.js"></script> <script src="../utils.js"></script>
<script src="../SB.js"></script>
<script src="options.js"></script> <script src="options.js"></script>
</head> </head>

View file

@ -3,38 +3,33 @@ window.addEventListener('DOMContentLoaded', init);
async function init() { async function init() {
localizeHtmlPage(); localizeHtmlPage();
await wait(() => SB.config !== undefined);
// Set all of the toggle options to the correct option // Set all of the toggle options to the correct option
let optionsContainer = document.getElementById("options"); let optionsContainer = document.getElementById("options");
let optionsElements = optionsContainer.children; let optionsElements = optionsContainer.children;
// How many checks are left to be done
let checksLeft = 0;
for (let i = 0; i < optionsElements.length; i++) { for (let i = 0; i < optionsElements.length; i++) {
switch (optionsElements[i].getAttribute("option-type")) { switch (optionsElements[i].getAttribute("option-type")) {
case "toggle": case "toggle":
let option = optionsElements[i].getAttribute("sync-option"); let option = optionsElements[i].getAttribute("sync-option");
chrome.storage.sync.get([option], function(result) {
let optionResult = result[option];
if (optionResult != undefined) {
let checkbox = optionsElements[i].querySelector("input");
checkbox.checked = optionResult;
let reverse = optionsElements[i].getAttribute("toggle-type") === "reverse"; let optionResult = SB.config[option];
if (reverse) { let checkbox = optionsElements[i].querySelector("input");
optionsElements[i].querySelector("input").checked = !optionResult; let reverse = optionsElements[i].getAttribute("toggle-type") === "reverse";
}
checkbox.addEventListener("click", () =>{ if (optionResult != undefined) {
setOptionValue(option, reverse ? !checkbox.checked : checkbox.checked) checkbox.checked = optionResult;
});
if (reverse) {
optionsElements[i].querySelector("input").checked = !optionResult;
} }
}
checksLeft--; checkbox.addEventListener("click", () =>{
SB.config[option] = reverse ? !checkbox.checked : checkbox.checked;
}); });
checksLeft++;
break; break;
case "text-change": case "text-change":
let button = optionsElements[i].querySelector(".trigger-button"); let button = optionsElements[i].querySelector(".trigger-button");
@ -49,8 +44,6 @@ async function init() {
} }
} }
await wait(() => checksLeft == 0, 1000, 50);
optionsContainer.classList.remove("hidden"); optionsContainer.classList.remove("hidden");
optionsContainer.classList.add("animated"); optionsContainer.classList.add("animated");
} }
@ -68,21 +61,19 @@ function activateKeybindChange(element) {
let option = element.getAttribute("sync-option"); let option = element.getAttribute("sync-option");
chrome.storage.sync.get([option], function(result) { let currentlySet = SB.config[option] !== null ? chrome.i18n.getMessage("keybindCurrentlySet") : "";
let currentlySet = result[option] !== null ? chrome.i18n.getMessage("keybindCurrentlySet") : "";
let status = element.querySelector(".option-hidden-section > .keybind-status");
status.innerText = chrome.i18n.getMessage("keybindDescription") + currentlySet;
if (result[option] !== null) {
let statusKey = element.querySelector(".option-hidden-section > .keybind-status-key");
statusKey.innerText = result[option];
}
element.querySelector(".option-hidden-section").classList.remove("hidden"); let status = element.querySelector(".option-hidden-section > .keybind-status");
status.innerText = chrome.i18n.getMessage("keybindDescription") + currentlySet;
document.addEventListener("keydown", (e) => keybindKeyPressed(element, e), {once: true});
}); if (SB.config[option] !== null) {
let statusKey = element.querySelector(".option-hidden-section > .keybind-status-key");
statusKey.innerText = SB.config[option];
}
element.querySelector(".option-hidden-section").classList.remove("hidden");
document.addEventListener("keydown", (e) => keybindKeyPressed(element, e), {once: true});
} }
/** /**
@ -97,7 +88,7 @@ function keybindKeyPressed(element, e) {
let option = element.getAttribute("sync-option"); let option = element.getAttribute("sync-option");
chrome.storage.sync.set({[option]: key}); SB.config[option] = key;
let status = element.querySelector(".option-hidden-section > .keybind-status"); let status = element.querySelector(".option-hidden-section > .keybind-status");
status.innerText = chrome.i18n.getMessage("keybindDescriptionComplete"); status.innerText = chrome.i18n.getMessage("keybindDescriptionComplete");
@ -123,23 +114,11 @@ function activateTextChange(element) {
let textBox = element.querySelector(".option-text-box"); let textBox = element.querySelector(".option-text-box");
let option = element.getAttribute("sync-option"); let option = element.getAttribute("sync-option");
textBox.value = SB.config[option];
chrome.storage.sync.get([option], function(result) { let setButton = element.querySelector(".text-change-set");
textBox.value = result[option]; setButton.addEventListener("click", () => {SB.config[option] = textBox.value});
let setButton = element.querySelector(".text-change-set"); element.querySelector(".option-hidden-section").classList.remove("hidden");
setButton.addEventListener("click", () => setOptionValue(option, textBox.value));
element.querySelector(".option-hidden-section").classList.remove("hidden");
});
} }
/**
* Called when an option has been changed.
*
* @param {string} option
* @param {*} value
*/
function setOptionValue(option, value) {
chrome.storage.sync.set({[option]: value});
}

View file

@ -1,6 +1,7 @@
<html> <html>
<head> <head>
<title>__MSG_openPopup__</title> <title>__MSG_openPopup__</title>
<script src="SB.js"></script>
<link id="sponorBlockPopupFont" rel="stylesheet" type="text/css" href="/libs/Source+Sans+Pro.css"/> <link id="sponorBlockPopupFont" rel="stylesheet" type="text/css" href="/libs/Source+Sans+Pro.css"/>
<link id="sponorBlockStyleSheet" rel="stylesheet" type="text/css" href="popup.css"/> <link id="sponorBlockStyleSheet" rel="stylesheet" type="text/css" href="popup.css"/>
</head> </head>

315
popup.js
View file

@ -1,29 +1,27 @@
//make this a function to allow this to run on the content page //make this a function to allow this to run on the content page
function runThePopup() { async function runThePopup() {
localizeHtmlPage(); localizeHtmlPage();
//is it in the popup or content script //is it in the popup or content script
var inPopup = true; var inPopup = true;
if (chrome.tabs == undefined) { if (chrome.tabs == undefined) {
//this is on the content script, use direct communication //this is on the content script, use direct communication
chrome.tabs = {}; chrome.tabs = {};
chrome.tabs.sendMessage = function(id, request, callback) { chrome.tabs.sendMessage = function(id, request, callback) {
messageListener(request, null, callback); messageListener(request, null, callback);
} }
//add a dummy query method //add a dummy query method
chrome.tabs.query = function(config, callback) { chrome.tabs.query = function(config, callback) {
callback([{ callback([{
url: document.URL, url: document.URL,
id: -1 id: -1
}]); }]);
} }
inPopup = false; inPopup = false;
} }
var SB = {}; await wait(() => SB.config !== undefined);
["sponsorStart", ["sponsorStart",
// Top toggles // Top toggles
@ -95,7 +93,7 @@ function runThePopup() {
SB.optionsButton.addEventListener("click", openOptions); SB.optionsButton.addEventListener("click", openOptions);
SB.reportAnIssue.addEventListener("click", reportAnIssue); SB.reportAnIssue.addEventListener("click", reportAnIssue);
SB.hideDiscordButton.addEventListener("click", hideDiscordButton); SB.hideDiscordButton.addEventListener("click", hideDiscordButton);
//if true, the button now selects the end time //if true, the button now selects the end time
let startTimeChosen = false; let startTimeChosen = false;
@ -106,130 +104,113 @@ function runThePopup() {
let currentVideoID = null; let currentVideoID = null;
//see if discord link can be shown //see if discord link can be shown
chrome.storage.sync.get(["hideDiscordLink"], function(result) { let hideDiscordLink = SB.config.hideDiscordLink;
let hideDiscordLink = result.hideDiscordLink; if (hideDiscordLink == undefined || !hideDiscordLink) {
if (hideDiscordLink == undefined || !hideDiscordLink) { let hideDiscordLaunches = SB.config.hideDiscordLaunches;
chrome.storage.sync.get(["hideDiscordLaunches"], function(result) { //only if less than 10 launches
let hideDiscordLaunches = result.hideDiscordLaunches; if (hideDiscordLaunches == undefined || hideDiscordLaunches < 10) {
//only if less than 10 launches SB.discordButtonContainer.style.display = null;
if (hideDiscordLaunches == undefined || hideDiscordLaunches < 10) {
SB.discordButtonContainer.style.display = null; if (hideDiscordLaunches == undefined) {
hideDiscordLaunches = 1;
if (hideDiscordLaunches == undefined) {
hideDiscordLaunches = 1;
}
chrome.storage.sync.set({"hideDiscordLaunches": hideDiscordLaunches + 1});
} }
}); SB.config.hideDiscordLaunches = hideDiscordLaunches + 1;
} }
}); }
//show proper disable skipping button //show proper disable skipping button
chrome.storage.sync.get(["disableSkipping"], function(result) { let disableSkipping = SB.config.disableSkipping;
let disableSkipping = result.disableSkipping; if (disableSkipping != undefined && disableSkipping) {
if (disableSkipping != undefined && disableSkipping) { SB.disableSkipping.style.display = "none";
SB.disableSkipping.style.display = "none"; SB.enableSkipping.style.display = "unset";
SB.enableSkipping.style.display = "unset"; }
}
});
//if the don't show notice again variable is true, an option to //if the don't show notice again variable is true, an option to
// disable should be available // disable should be available
chrome.storage.sync.get(["dontShowNotice"], function(result) { let dontShowNotice = SB.config.dontShowNotice;
let dontShowNotice = result.dontShowNotice; if (dontShowNotice != undefined && dontShowNotice) {
if (dontShowNotice != undefined && dontShowNotice) { SB.showNoticeAgain.style.display = "unset";
SB.showNoticeAgain.style.display = "unset"; }
}
});
//get the amount of times this user has contributed and display it to thank them //get the amount of times this user has contributed and display it to thank them
chrome.storage.sync.get(["sponsorTimesContributed"], function(result) { if (SB.config.sponsorTimesContributed != undefined) {
if (result.sponsorTimesContributed != undefined) { if (SB.config.sponsorTimesContributed > 1) {
if (result.sponsorTimesContributed > 1) { SB.sponsorTimesContributionsDisplayEndWord.innerText = chrome.i18n.getMessage("Sponsors");
SB.sponsorTimesContributionsDisplayEndWord.innerText = chrome.i18n.getMessage("Sponsors"); } else {
} else { SB.sponsorTimesContributionsDisplayEndWord.innerText = chrome.i18n.getMessage("Sponsor");
SB.sponsorTimesContributionsDisplayEndWord.innerText = chrome.i18n.getMessage("Sponsor");
}
SB.sponsorTimesContributionsDisplay.innerText = result.sponsorTimesContributed;
SB.sponsorTimesContributionsContainer.style.display = "unset";
//get the userID
chrome.storage.sync.get(["userID"], function(result) {
let userID = result.userID;
if (userID != undefined) {
//there are probably some views on these submissions then
//get the amount of views from the sponsors submitted
sendRequestToServer("GET", "/api/getViewsForUser?userID=" + userID, function(xmlhttp) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
let viewCount = JSON.parse(xmlhttp.responseText).viewCount;
if (viewCount != 0) {
if (viewCount > 1) {
SB.sponsorTimesViewsDisplayEndWord.innerText = chrome.i18n.getMessage("Segments");
} else {
SB.sponsorTimesViewsDisplayEndWord.innerText = chrome.i18n.getMessage("Segment");
}
SB.sponsorTimesViewsDisplay.innerText = viewCount;
SB.sponsorTimesViewsContainer.style.display = "unset";
}
}
});
//get this time in minutes
sendRequestToServer("GET", "/api/getSavedTimeForUser?userID=" + userID, function(xmlhttp) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
let minutesSaved = JSON.parse(xmlhttp.responseText).timeSaved;
if (minutesSaved != 0) {
if (minutesSaved != 1) {
SB.sponsorTimesOthersTimeSavedEndWord.innerText = chrome.i18n.getMessage("minsLower");
} else {
SB.sponsorTimesOthersTimeSavedEndWord.innerText = chrome.i18n.getMessage("minLower");
}
SB.sponsorTimesOthersTimeSavedDisplay.innerText = getFormattedHours(minutesSaved);
SB.sponsorTimesOthersTimeSavedContainer.style.display = "unset";
}
}
});
}
});
} }
}); SB.sponsorTimesContributionsDisplay.innerText = SB.config.sponsorTimesContributed;
SB.sponsorTimesContributionsContainer.style.display = "unset";
//get the userID
let userID = SB.config.userID;
if (userID != undefined) {
//there are probably some views on these submissions then
//get the amount of views from the sponsors submitted
sendRequestToServer("GET", "/api/getViewsForUser?userID=" + userID, function(xmlhttp) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
let viewCount = JSON.parse(xmlhttp.responseText).viewCount;
if (viewCount != 0) {
if (viewCount > 1) {
SB.sponsorTimesViewsDisplayEndWord.innerText = chrome.i18n.getMessage("Segments");
} else {
SB.sponsorTimesViewsDisplayEndWord.innerText = chrome.i18n.getMessage("Segment");
}
SB.sponsorTimesViewsDisplay.innerText = viewCount;
SB.sponsorTimesViewsContainer.style.display = "unset";
}
}
});
//get this time in minutes
sendRequestToServer("GET", "/api/getSavedTimeForUser?userID=" + userID, function(xmlhttp) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
let minutesSaved = JSON.parse(xmlhttp.responseText).timeSaved;
if (minutesSaved != 0) {
if (minutesSaved != 1) {
SB.sponsorTimesOthersTimeSavedEndWord.innerText = chrome.i18n.getMessage("minsLower");
} else {
SB.sponsorTimesOthersTimeSavedEndWord.innerText = chrome.i18n.getMessage("minLower");
}
SB.sponsorTimesOthersTimeSavedDisplay.innerText = getFormattedHours(minutesSaved);
SB.sponsorTimesOthersTimeSavedContainer.style.display = "unset";
}
}
});
}
}
//get the amount of times this user has skipped a sponsor //get the amount of times this user has skipped a sponsor
chrome.storage.sync.get(["skipCount"], function(result) { if (SB.config.skipCount != undefined) {
if (result.skipCount != undefined) { if (SB.config.skipCount != 1) {
if (result.skipCount != 1) { SB.sponsorTimesSkipsDoneEndWord.innerText = chrome.i18n.getMessage("Sponsors");
SB.sponsorTimesSkipsDoneEndWord.innerText = chrome.i18n.getMessage("Sponsors"); } else {
} else { SB.sponsorTimesSkipsDoneEndWord.innerText = chrome.i18n.getMessage("Sponsor");
SB.sponsorTimesSkipsDoneEndWord.innerText = chrome.i18n.getMessage("Sponsor");
}
SB.sponsorTimesSkipsDoneDisplay.innerText = result.skipCount;
SB.sponsorTimesSkipsDoneContainer.style.display = "unset";
} }
});
SB.sponsorTimesSkipsDoneDisplay.innerText = SB.config.skipCount;
SB.sponsorTimesSkipsDoneContainer.style.display = "unset";
}
//get the amount of time this user has saved. //get the amount of time this user has saved.
chrome.storage.sync.get(["minutesSaved"], function(result) { if (SB.config.minutesSaved != undefined) {
if (result.minutesSaved != undefined) { if (SB.config.minutesSaved != 1) {
if (result.minutesSaved != 1) { SB.sponsorTimeSavedEndWord.innerText = chrome.i18n.getMessage("minsLower");
SB.sponsorTimeSavedEndWord.innerText = chrome.i18n.getMessage("minsLower"); } else {
} else { SB.sponsorTimeSavedEndWord.innerText = chrome.i18n.getMessage("minLower");
SB.sponsorTimeSavedEndWord.innerText = chrome.i18n.getMessage("minLower");
}
SB.sponsorTimeSavedDisplay.innerText = getFormattedHours(result.minutesSaved);
SB.sponsorTimeSavedContainer.style.display = "unset";
} }
});
SB.sponsorTimeSavedDisplay.innerText = getFormattedHours(SB.config.minutesSaved);
SB.sponsorTimeSavedContainer.style.display = "unset";
}
chrome.tabs.query({ chrome.tabs.query({
active: true, active: true,
currentWindow: true currentWindow: true
}, onTabs); }, onTabs);
function onTabs(tabs) { function onTabs(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {message: 'getVideoID'}, function(result) { chrome.tabs.sendMessage(tabs[0].id, {message: 'getVideoID'}, function(result) {
if (result != undefined && result.videoID) { if (result != undefined && result.videoID) {
@ -250,25 +231,24 @@ function runThePopup() {
} }
//load video times for this video //load video times for this video
let sponsorTimeKey = "sponsorTimes" + currentVideoID; console.log( SB.config.sponsorTimes.set)
chrome.storage.sync.get([sponsorTimeKey], function(result) { setTimeout(()=> console.log( SB.config.sponsorTimes.set), 200 )
let sponsorTimesStorage = result[sponsorTimeKey]; let sponsorTimesStorage = SB.config.sponsorTimes.get(currentVideoID);
if (sponsorTimesStorage != undefined && sponsorTimesStorage.length > 0) { if (sponsorTimesStorage != undefined && sponsorTimesStorage.length > 0) {
if (sponsorTimesStorage[sponsorTimesStorage.length - 1] != undefined && sponsorTimesStorage[sponsorTimesStorage.length - 1].length < 2) { if (sponsorTimesStorage[sponsorTimesStorage.length - 1] != undefined && sponsorTimesStorage[sponsorTimesStorage.length - 1].length < 2) {
startTimeChosen = true; startTimeChosen = true;
SB.sponsorStart.innerHTML = chrome.i18n.getMessage("sponsorEnd"); SB.sponsorStart.innerHTML = chrome.i18n.getMessage("sponsorEnd");
}
sponsorTimes = sponsorTimesStorage;
displaySponsorTimes();
//show submission section
SB.submissionSection.style.display = "unset";
showSubmitTimesIfNecessary();
} }
});
sponsorTimes = sponsorTimesStorage;
displaySponsorTimes();
//show submission section
SB.submissionSection.style.display = "unset";
showSubmitTimesIfNecessary();
}
//check if this video's sponsors are known //check if this video's sponsors are known
chrome.tabs.sendMessage( chrome.tabs.sendMessage(
@ -347,10 +327,9 @@ function runThePopup() {
} }
sponsorTimes[sponsorTimesIndex][startTimeChosen ? 1 : 0] = response.time; sponsorTimes[sponsorTimesIndex][startTimeChosen ? 1 : 0] = response.time;
let sponsorTimeKey = "sponsorTimes" + currentVideoID;
let localStartTimeChosen = startTimeChosen; let localStartTimeChosen = startTimeChosen;
chrome.storage.sync.set({[sponsorTimeKey]: sponsorTimes}, function() { SB.config.sponsorTimes.set(currentVideoID, sponsorTimes);
//send a message to the client script //send a message to the client script
if (localStartTimeChosen) { if (localStartTimeChosen) {
chrome.tabs.query({ chrome.tabs.query({
@ -363,7 +342,6 @@ function runThePopup() {
); );
}); });
} }
});
updateStartTimeChosen(); updateStartTimeChosen();
@ -683,8 +661,7 @@ function runThePopup() {
sponsorTimes[index][1] = getSponsorTimeEditTimes("endTime", index); sponsorTimes[index][1] = getSponsorTimeEditTimes("endTime", index);
//save this //save this
let sponsorTimeKey = "sponsorTimes" + currentVideoID; SB.config.sponsorTimes.set(currentVideoID, sponsorTimes);
chrome.storage.sync.set({[sponsorTimeKey]: sponsorTimes}, function() {
chrome.tabs.query({ chrome.tabs.query({
active: true, active: true,
currentWindow: true currentWindow: true
@ -694,7 +671,6 @@ function runThePopup() {
{message: "sponsorDataChanged"} {message: "sponsorDataChanged"}
); );
}); });
});
if (closeEditMode) { if (closeEditMode) {
displaySponsorTimes(); displaySponsorTimes();
@ -724,8 +700,7 @@ function runThePopup() {
sponsorTimes.splice(index, 1); sponsorTimes.splice(index, 1);
//save this //save this
let sponsorTimeKey = "sponsorTimes" + currentVideoID; SB.config.sponsorTimes.set(currentVideoID, sponsorTimes);
chrome.storage.sync.set({[sponsorTimeKey]: sponsorTimes}, function() {
chrome.tabs.query({ chrome.tabs.query({
active: true, active: true,
currentWindow: true currentWindow: true
@ -735,7 +710,6 @@ function runThePopup() {
{message: "sponsorDataChanged"} {message: "sponsorDataChanged"}
); );
}); });
});
//update display //update display
displaySponsorTimes(); displaySponsorTimes();
@ -776,9 +750,8 @@ function runThePopup() {
//reset sponsorTimes //reset sponsorTimes
sponsorTimes = []; sponsorTimes = [];
let sponsorTimeKey = "sponsorTimes" + currentVideoID; SB.config.sponsorTimes.set(currentVideoID, sponsorTimes);
chrome.storage.sync.set({[sponsorTimeKey]: sponsorTimes}, function() {
chrome.tabs.query({ chrome.tabs.query({
active: true, active: true,
currentWindow: true currentWindow: true
@ -788,7 +761,6 @@ function runThePopup() {
{message: "sponsorDataChanged"} {message: "sponsorDataChanged"}
); );
}); });
});
displaySponsorTimes(); displaySponsorTimes();
@ -826,7 +798,7 @@ function runThePopup() {
} }
function showNoticeAgain() { function showNoticeAgain() {
chrome.storage.sync.set({"dontShowNotice": false}); SB.config.dontShowNotice = false;
chrome.tabs.query({ chrome.tabs.query({
active: true, active: true,
@ -875,10 +847,8 @@ function runThePopup() {
//make the options username setting option visible //make the options username setting option visible
function setUsernameButton() { function setUsernameButton() {
//get the userID
chrome.storage.sync.get(["userID"], function(result) {
//get username from the server //get username from the server
sendRequestToServer("GET", "/api/getUsername?userID=" + result.userID, function (xmlhttp, error) { sendRequestToServer("GET", "/api/getUsername?userID=" + SB.config.userID, function (xmlhttp, error) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
SB.usernameInput.value = JSON.parse(xmlhttp.responseText).userName; SB.usernameInput.value = JSON.parse(xmlhttp.responseText).userName;
@ -898,7 +868,6 @@ function runThePopup() {
SB.setUsernameStatus.innerText = getErrorMessage(xmlhttp.status); SB.setUsernameStatus.innerText = getErrorMessage(xmlhttp.status);
} }
}); });
});
} }
//submit the new username //submit the new username
@ -908,8 +877,7 @@ function runThePopup() {
SB.setUsernameStatus.innerText = "Loading..."; SB.setUsernameStatus.innerText = "Loading...";
//get the userID //get the userID
chrome.storage.sync.get(["userID"], function(result) { sendRequestToServer("POST", "/api/setUsername?userID=" + SB.config.userID + "&username=" + SB.usernameInput.value, function (xmlhttp, error) {
sendRequestToServer("POST", "/api/setUsername?userID=" + result.userID + "&username=" + SB.usernameInput.value, function (xmlhttp, error) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//submitted //submitted
SB.submitUsername.style.display = "none"; SB.submitUsername.style.display = "none";
@ -920,7 +888,6 @@ function runThePopup() {
SB.setUsernameStatus.innerText = getErrorMessageI(xmlhttp.status); SB.setUsernameStatus.innerText = getErrorMessageI(xmlhttp.status);
} }
}); });
});
SB.setUsernameContainer.style.display = "none"; SB.setUsernameContainer.style.display = "none";
@ -980,8 +947,7 @@ function runThePopup() {
} }
function hideDiscordButton() { function hideDiscordButton() {
chrome.storage.sync.set({"hideDiscordLink": true}); SB.config.hideDiscordLink = true;
SB.discordButtonContainer.style.display = "none"; SB.discordButtonContainer.style.display = "none";
} }
@ -1010,8 +976,7 @@ function runThePopup() {
{message: 'getChannelURL'}, {message: 'getChannelURL'},
function(response) { function(response) {
//get whitelisted channels //get whitelisted channels
chrome.storage.sync.get(["whitelistedChannels"], function(result) { let whitelistedChannels = SB.config.whitelistedChannels;
let whitelistedChannels = result.whitelistedChannels;
if (whitelistedChannels == undefined) { if (whitelistedChannels == undefined) {
whitelistedChannels = []; whitelistedChannels = [];
} }
@ -1027,7 +992,7 @@ function runThePopup() {
SB.downloadedSponsorMessageTimes.style.fontWeight = "bold"; SB.downloadedSponsorMessageTimes.style.fontWeight = "bold";
//save this //save this
chrome.storage.sync.set({whitelistedChannels: whitelistedChannels}); SB.config.whitelistedChannels = whitelistedChannels;
//send a message to the client //send a message to the client
chrome.tabs.query({ chrome.tabs.query({
@ -1041,7 +1006,6 @@ function runThePopup() {
}); });
} }
); );
});
} }
); );
}); });
@ -1058,8 +1022,7 @@ function runThePopup() {
{message: 'getChannelURL'}, {message: 'getChannelURL'},
function(response) { function(response) {
//get whitelisted channels //get whitelisted channels
chrome.storage.sync.get(["whitelistedChannels"], function(result) { let whitelistedChannels = SB.config.whitelistedChannels;
let whitelistedChannels = result.whitelistedChannels;
if (whitelistedChannels == undefined) { if (whitelistedChannels == undefined) {
whitelistedChannels = []; whitelistedChannels = [];
} }
@ -1076,7 +1039,7 @@ function runThePopup() {
SB.downloadedSponsorMessageTimes.style.fontWeight = "unset"; SB.downloadedSponsorMessageTimes.style.fontWeight = "unset";
//save this //save this
chrome.storage.sync.set({whitelistedChannels: whitelistedChannels}); SB.config.whitelistedChannels = whitelistedChannels;
//send a message to the client //send a message to the client
chrome.tabs.query({ chrome.tabs.query({
@ -1090,7 +1053,6 @@ function runThePopup() {
}); });
} }
); );
});
} }
); );
}); });
@ -1100,7 +1062,7 @@ function runThePopup() {
* Should skipping be disabled (visuals stay) * Should skipping be disabled (visuals stay)
*/ */
function toggleSkipping(disabled) { function toggleSkipping(disabled) {
chrome.storage.sync.set({"disableSkipping": disabled}); SB.config.disableSkipping = disabled;
let hiddenButton = SB.disableSkipping; let hiddenButton = SB.disableSkipping;
let shownButton = SB.enableSkipping; let shownButton = SB.enableSkipping;
@ -1169,7 +1131,6 @@ function runThePopup() {
if (chrome.tabs != undefined) { if (chrome.tabs != undefined) {
//add the width restriction (because Firefox) //add the width restriction (because Firefox)
document.getElementById("sponorBlockStyleSheet").sheet.insertRule('.popupBody { width: 325 }', 0); document.getElementById("sponorBlockStyleSheet").sheet.insertRule('.popupBody { width: 325 }', 0);
//this means it is actually opened in the popup //this means it is actually opened in the popup
runThePopup(); runThePopup();
} }