Merge pull request #358 from ajayyy/react

Categories Improvements
This commit is contained in:
Ajay Ramachandran 2020-06-02 19:40:11 -04:00 committed by GitHub
commit 28cddf92d5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 144 additions and 138 deletions

View file

@ -1,7 +1,7 @@
{
"name": "__MSG_fullName__",
"short_name": "__MSG_Name__",
"version": "1.2.29",
"version": "1.2.30",
"default_locale": "en",
"description": "__MSG_Description__",
"content_scripts": [{

View file

@ -104,9 +104,6 @@
"voted": {
"message": "Voted!"
},
"voteFail": {
"message": "You have already voted this way before."
},
"serverDown": {
"message": "It seems the server is down. Contact the dev immediately."
},
@ -496,7 +493,7 @@
"message": "Interaction Reminder (Subscribe)"
},
"category_selfpromo": {
"message": "Self-Promotion and Merchandise"
"message": "Unpaid/Self Promotion"
},
"category_music_offtopic": {
"message": "Music: Non-Music Section"

View file

@ -1,4 +1,4 @@
import * as Types from "./types";
import * as CompileConfig from "../config.json";
import Config from "./config";
// Make the config public for debugging purposes
@ -30,7 +30,17 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) {
switch(request.message) {
case "openConfig":
chrome.runtime.openOptionsPage();
return
return;
case "sendRequest":
sendRequestToCustomServer(request.type, request.url, request.data).then(async (response) => {
callback({
responseText: await response.text(),
status: response.status,
ok: response.ok
});
});
return true;
case "addSponsorTime":
addSponsorTime(request.time, request.videoID, callback);
@ -47,7 +57,7 @@ chrome.runtime.onMessage.addListener(function (request, sender, callback) {
//this allows the callback to be called later
return true;
case "submitVote":
submitVote(request.type, request.UUID, request.category, callback);
submitVote(request.type, request.UUID, request.category).then(callback);
//this allows the callback to be called later
return true;
@ -147,7 +157,7 @@ function addSponsorTime(time, videoID, callback) {
});
}
function submitVote(type, UUID, category, callback) {
async function submitVote(type: number, UUID: string, category: string) {
let userID = Config.config.userID;
if (userID == undefined || userID === "undefined") {
@ -159,24 +169,60 @@ function submitVote(type, UUID, category, callback) {
let typeSection = (type !== undefined) ? "&type=" + type : "&category=" + category;
//publish this vote
utils.sendRequestToServer("POST", "/api/voteOnSponsorTime?UUID=" + UUID + "&userID=" + userID + typeSection, function(xmlhttp, error) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback({
successType: 1
});
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 405) {
//duplicate vote
callback({
successType: 0,
statusCode: xmlhttp.status
});
} else if (error) {
//error while connect
callback({
successType: -1,
statusCode: xmlhttp.status
});
let response = await asyncRequestToServer("POST", "/api/voteOnSponsorTime?UUID=" + UUID + "&userID=" + userID + typeSection);
if (response.ok) {
return {
successType: 1
};
} else if (response.status == 405) {
//duplicate vote
return {
successType: 0,
statusCode: response.status
};
} else {
//error while connect
return {
successType: -1,
statusCode: response.status
};
}
}
async function asyncRequestToServer(type: string, address: string, data = {}) {
let serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress;
return await (sendRequestToCustomServer(type, serverAddress + address, data));
}
/**
* Sends a request to the specified url
*
* @param type The request type "GET", "POST", etc.
* @param address The address to add to the SponsorBlock server address
* @param callback
*/
async function sendRequestToCustomServer(type: string, url: string, data = {}) {
// If GET, convert JSON to parameters
if (type.toLowerCase() === "get") {
for (const key in data) {
let seperator = url.includes("?") ? "&" : "?";
let value = (typeof(data[key]) === "string") ? data[key]: JSON.stringify(data[key]);
url += seperator + key + "=" + value;
}
data = null;
}
const response = await fetch(url, {
method: type,
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
body: data ? JSON.stringify(data) : null
});
return response;
}

View file

@ -268,7 +268,7 @@ async function migrateOldFormats() {
let response = await utils.asyncRequestToCustomServer("GET", "https://sponsor.ajay.app/invidious/api/v1/channels/" + item.split("/")[2] + "?fields=authorId");
if (response.ok) {
newChannelList.push((await response.json()).authorId);
newChannelList.push((JSON.parse(response.responseText)).authorId);
} else {
// Add it at the beginning so it gets converted later
newChannelList.unshift(item);

View file

@ -1,6 +1,6 @@
import Config from "./config";
import { SponsorTime, CategorySkipOption, CategorySelection, VideoID, SponsorHideType } from "./types";
import { SponsorTime, CategorySkipOption, CategorySelection, VideoID, SponsorHideType, FetchResponse } from "./types";
import { ContentContainer } from "./types";
import Utils from "./utils";
@ -64,10 +64,6 @@ var channelWhitelisted = false;
// create preview bar
var previewBar: PreviewBar = null;
// When not null, a sponsor is currently being previewed and auto skip should be enabled.
// This is set to a timeout function when that happens that will reset it after 3 seconds.
var previewResetter: NodeJS.Timeout = null;
//the player controls on the YouTube player
var controls = null;
@ -164,14 +160,7 @@ function messageListener(request: any, sender: any, sendResponse: (response: any
video.play();
}
// Start preview resetter
if (previewResetter !== null){
clearTimeout(previewResetter);
}
previewResetter = setTimeout(() => previewResetter = null, 4000);
return
return;
case "getCurrentTime":
sendResponse({
currentTime: getRealCurrentTime()
@ -628,9 +617,9 @@ function sponsorsLookup(id: string) {
utils.asyncRequestToServer('GET', "/api/skipSegments", {
videoID: id,
categories
}).then(async (response: Response) => {
if (response.status === 200) {
let recievedSegments: SponsorTime[] = await response.json();
}).then(async (response: FetchResponse) => {
if (response.ok) {
let recievedSegments: SponsorTime[] = JSON.parse(response.responseText);
if (!recievedSegments.length) {
console.error("[SponsorBlock] Server returned malformed response: " + JSON.stringify(recievedSegments));
return;
@ -866,7 +855,7 @@ function getNextSkipIndex(currentTime: number, includeIntersectingSegments: bool
let endTimeIndex = getLatestEndTimeIndex(sponsorTimes, minSponsorTimeIndex);
let previewSponsorStartTimes = getStartTimes(sponsorTimesSubmitting, includeIntersectingSegments);
let previewSponsorStartTimesAfterCurrentTime = getStartTimes(sponsorTimesSubmitting, includeIntersectingSegments, currentTime, true, false);
let previewSponsorStartTimesAfterCurrentTime = getStartTimes(sponsorTimesSubmitting, includeIntersectingSegments, currentTime, false, false);
let minPreviewSponsorTimeIndex = previewSponsorStartTimes.indexOf(Math.min(...previewSponsorStartTimesAfterCurrentTime));
let previewEndTimeIndex = getLatestEndTimeIndex(sponsorTimesSubmitting, minPreviewSponsorTimeIndex);
@ -970,13 +959,6 @@ function previewTime(time: number) {
if (video.paused){
video.play();
}
// Start preview resetter
if (previewResetter !== null){
clearTimeout(previewResetter);
}
previewResetter = setTimeout(() => previewResetter = null, 4000);
}
//skip from the start time to the end time for a certain index sponsor time
@ -984,7 +966,7 @@ function skipToTime(v: HTMLVideoElement, skipTime: number[], skippingSegments: S
// There will only be one submission if it is manual skip
let autoSkip: boolean = utils.getCategorySelection(skippingSegments[0].category).option === CategorySkipOption.AutoSkip;
if (autoSkip || previewResetter !== null) {
if (autoSkip || sponsorTimesSubmitting.includes(skippingSegments[0])) {
v.currentTime = skipTime[1];
}
@ -993,30 +975,30 @@ function skipToTime(v: HTMLVideoElement, skipTime: number[], skippingSegments: S
if (!Config.config.dontShowNotice || !autoSkip) {
let skipNotice = new SkipNotice(skippingSegments, autoSkip, skipNoticeContentContainer);
}
}
//send telemetry that a this sponsor was skipped
if (Config.config.trackViewCount && autoSkip) {
let alreadySkipped = false;
let isPreviewSegment = false;
//send telemetry that a this sponsor was skipped
if (Config.config.trackViewCount && autoSkip) {
let alreadySkipped = false;
let isPreviewSegment = false;
for (const segment of skippingSegments) {
let index = sponsorTimes.indexOf(segment);
if (index !== -1 && !sponsorSkipped[index]) {
utils.sendRequestToServer("POST", "/api/viewedVideoSponsorTime?UUID=" + segment.UUID);
for (const segment of skippingSegments) {
let index = sponsorTimes.indexOf(segment);
if (index !== -1 && !sponsorSkipped[index]) {
utils.asyncRequestToServer("POST", "/api/viewedVideoSponsorTime?UUID=" + segment.UUID);
sponsorSkipped[index] = true;
} else if (sponsorSkipped[index]) {
alreadySkipped = true;
}
if (index !== -1) isPreviewSegment = true;
sponsorSkipped[index] = true;
} else if (sponsorSkipped[index]) {
alreadySkipped = true;
}
// Count this as a skip
if (!alreadySkipped && !isPreviewSegment) {
Config.config.minutesSaved = Config.config.minutesSaved + (skipTime[1] - skipTime[0]) / 60;
Config.config.skipCount = Config.config.skipCount + 1;
}
if (index === -1) isPreviewSegment = true;
}
// Count this as a skip
if (!alreadySkipped && !isPreviewSegment) {
Config.config.minutesSaved = Config.config.minutesSaved + (skipTime[1] - skipTime[0]) / 60;
Config.config.skipCount = Config.config.skipCount + 1;
}
}
}
@ -1395,10 +1377,6 @@ function vote(type: number, UUID: string, category?: string, skipNotice?: SkipNo
if (response.successType == 1 || (response.successType == -1 && response.statusCode == 429)) {
//success (treat rate limits as a success)
skipNotice.afterVote.bind(skipNotice)(utils.getSponsorTimeFromUUID(sponsorTimes, UUID), type, category);
} else if (response.successType == 0) {
//failure: duplicate vote
skipNotice.setNoticeInfoMessage.bind(skipNotice)(chrome.i18n.getMessage("voteFail"))
skipNotice.resetVoteButtonInfo.bind(skipNotice)();
} else if (response.successType == -1) {
skipNotice.setNoticeInfoMessage.bind(skipNotice)(utils.getErrorMessage(response.statusCode))
skipNotice.resetVoteButtonInfo.bind(skipNotice)();
@ -1525,7 +1503,7 @@ async function sendSubmitMessage(){
document.getElementById("submitButton").style.animation = "unset";
(<HTMLImageElement> document.getElementById("submitImage")).src = chrome.extension.getURL("icons/PlayerUploadFailedIconSponsorBlocker256px.png");
alert(utils.getErrorMessage(response.status) + "\n\n" + (await response.text()));
alert(utils.getErrorMessage(response.status) + "\n\n" + (response.responseText));
}
}

View file

@ -168,9 +168,9 @@ async function runThePopup(messageListener?: MessageListener) {
if (userID != undefined) {
//there are probably some views on these submissions then
//get the amount of views from the sponsors submitted
utils.sendRequestToServer("GET", "/api/getViewsForUser?userID=" + userID, function(xmlhttp) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
let viewCount = JSON.parse(xmlhttp.responseText).viewCount;
utils.sendRequestToServer("GET", "/api/getViewsForUser?userID=" + userID, function(response) {
if (response.status == 200) {
let viewCount = JSON.parse(response.responseText).viewCount;
if (viewCount != 0) {
if (viewCount > 1) {
PageElements.sponsorTimesViewsDisplayEndWord.innerText = chrome.i18n.getMessage("Segments");
@ -185,9 +185,9 @@ async function runThePopup(messageListener?: MessageListener) {
});
//get this time in minutes
utils.sendRequestToServer("GET", "/api/getSavedTimeForUser?userID=" + userID, function(xmlhttp) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
let minutesSaved = JSON.parse(xmlhttp.responseText).timeSaved;
utils.sendRequestToServer("GET", "/api/getSavedTimeForUser?userID=" + userID, function(response) {
if (response.status == 200) {
let minutesSaved = JSON.parse(response.responseText).timeSaved;
if (minutesSaved != 0) {
if (minutesSaved != 1) {
PageElements.sponsorTimesOthersTimeSavedEndWord.innerText = chrome.i18n.getMessage("minsLower");
@ -797,9 +797,9 @@ async function runThePopup(messageListener?: MessageListener) {
//make the options username setting option visible
function setUsernameButton() {
//get username from the server
utils.sendRequestToServer("GET", "/api/getUsername?userID=" + Config.config.userID, function (xmlhttp, error) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
PageElements.usernameInput.value = JSON.parse(xmlhttp.responseText).userName;
utils.sendRequestToServer("GET", "/api/getUsername?userID=" + Config.config.userID, function (response) {
if (response.status == 200) {
PageElements.usernameInput.value = JSON.parse(response.responseText).userName;
PageElements.submitUsername.style.display = "unset";
PageElements.usernameInput.style.display = "unset";
@ -808,13 +808,13 @@ async function runThePopup(messageListener?: MessageListener) {
PageElements.setUsername.style.display = "unset";
PageElements
PageElements.setUsernameStatusContainer.style.display = "none";
} else if (xmlhttp.readyState == 4) {
} else {
PageElements.setUsername.style.display = "unset";
PageElements.submitUsername.style.display = "none";
PageElements.usernameInput.style.display = "none";
PageElements.setUsernameStatusContainer.style.display = "unset";
PageElements.setUsernameStatus.innerText = utils.getErrorMessage(xmlhttp.status);
PageElements.setUsernameStatus.innerText = utils.getErrorMessage(response.status);
}
});
}
@ -826,15 +826,15 @@ async function runThePopup(messageListener?: MessageListener) {
PageElements.setUsernameStatus.innerText = "Loading...";
//get the userID
utils.sendRequestToServer("POST", "/api/setUsername?userID=" + Config.config.userID + "&username=" + PageElements.usernameInput.value, function (xmlhttp, error) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
utils.sendRequestToServer("POST", "/api/setUsername?userID=" + Config.config.userID + "&username=" + PageElements.usernameInput.value, function (response) {
if (response.status == 200) {
//submitted
PageElements.submitUsername.style.display = "none";
PageElements.usernameInput.style.display = "none";
PageElements.setUsernameStatus.innerText = chrome.i18n.getMessage("success");
} else if (xmlhttp.readyState == 4) {
PageElements.setUsernameStatus.innerText = utils.getErrorMessage(xmlhttp.status);
} else {
PageElements.setUsernameStatus.innerText = utils.getErrorMessage(response.status);
}
});
@ -883,9 +883,6 @@ async function runThePopup(messageListener?: MessageListener) {
if (response.successType == 1 || (response.successType == -1 && response.statusCode == 429)) {
//success (treat rate limits as a success)
addVoteMessage(chrome.i18n.getMessage("voted"), UUID)
} else if (response.successType == 0) {
//failure: duplicate vote
addVoteMessage(chrome.i18n.getMessage("voteFail"), UUID)
} else if (response.successType == -1) {
addVoteMessage(utils.getErrorMessage(response.statusCode), UUID)
}

View file

@ -22,6 +22,12 @@ interface ContentContainer {
}
}
interface FetchResponse {
responseText: string,
status: number,
ok: boolean
}
interface VideoDurationResponse {
duration: number;
}
@ -55,6 +61,7 @@ interface SponsorTime {
type VideoID = string;
export {
FetchResponse,
VideoDurationResponse,
ContentContainer,
CategorySelection,

View file

@ -1,5 +1,5 @@
import Config from "./config";
import { CategorySelection, SponsorTime } from "./types";
import { CategorySelection, SponsorTime, FetchResponse } from "./types";
import * as CompileConfig from "../config.json";
@ -276,29 +276,18 @@ class Utils {
* @param address The address to add to the SponsorBlock server address
* @param callback
*/
async asyncRequestToCustomServer(type: string, url: string, data = {}) {
// If GET, convert JSON to parameters
if (type.toLowerCase() === "get") {
for (const key in data) {
let seperator = url.includes("?") ? "&" : "?";
let value = (typeof(data[key]) === "string") ? data[key]: JSON.stringify(data[key]);
url += seperator + key + "=" + value;
}
data = null;
}
const response = await fetch(url, {
method: type,
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
body: data ? JSON.stringify(data) : null
});
return response;
async asyncRequestToCustomServer(type: string, url: string, data = {}): Promise<FetchResponse> {
return new Promise((resolve) => {
// Ask the background script to do the work
chrome.runtime.sendMessage({
message: "sendRequest",
type,
url,
data
}, (response) => {
resolve(response);
});
})
}
/**
@ -308,7 +297,7 @@ class Utils {
* @param address The address to add to the SponsorBlock server address
* @param callback
*/
async asyncRequestToServer(type: string, address: string, data = {}) {
async asyncRequestToServer(type: string, address: string, data = {}): Promise<FetchResponse> {
let serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress;
return await (this.asyncRequestToCustomServer(type, serverAddress + address, data));
@ -321,25 +310,17 @@ class Utils {
* @param address The address to add to the SponsorBlock server address
* @param callback
*/
sendRequestToServer(type: string, address: string, callback?: (xmlhttp: XMLHttpRequest, err: boolean) => any) {
let xmlhttp = new XMLHttpRequest();
sendRequestToServer(type: string, address: string, callback?: (response: FetchResponse) => void) {
let serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress;
xmlhttp.open(type, serverAddress + address, true);
if (callback != undefined) {
xmlhttp.onreadystatechange = function () {
callback(xmlhttp, false);
};
xmlhttp.onerror = function(ev) {
callback(xmlhttp, true);
};
}
//submit this request
xmlhttp.send();
// Ask the background script to do the work
chrome.runtime.sendMessage({
message: "sendRequest",
type,
url: serverAddress + address
}, (response) => {
callback(response);
});
}
getFormattedMinutes(seconds: number) {