From 8ce61c874228e56bbc727bbccf61461c59a636ff Mon Sep 17 00:00:00 2001 From: DARKDRAGON532 <69623818+DARKDRAGON532@users.noreply.github.com> Date: Mon, 29 Nov 2021 22:50:28 +0530 Subject: [PATCH 1/4] Added fetch from youtube for userscript --- .../UserScript/Return Youtube Dislike.user.js | 67 +++++++++++++++++-- 1 file changed, 63 insertions(+), 4 deletions(-) diff --git a/Extensions/UserScript/Return Youtube Dislike.user.js b/Extensions/UserScript/Return Youtube Dislike.user.js index d41f36e..91a80c7 100644 --- a/Extensions/UserScript/Return Youtube Dislike.user.js +++ b/Extensions/UserScript/Return Youtube Dislike.user.js @@ -34,9 +34,15 @@ function doXHR(opts) { const xhr = new XMLHttpRequest(); xhr.open(opts.method, opts.url, true); - xhr.onload = () => opts.onload({ - response: JSON.parse(xhr.responseText), - }); + if (opts.responseType === 'text') { + xhr.onload = () => opts.onload({ + response: xhr.responseText, + }); + } else { + xhr.onload = () => opts.onload({ + response: JSON.parse(xhr.responseText), + }); + } xhr.onerror = err => console.error('XHR Failed', err); xhr.send(); } @@ -145,6 +151,28 @@ function createRateBar(likes, dislikes) { function setState() { cLog('Fetching votes...'); + let statsSet = false; + doXHR({ + method: 'GET', + responseType: 'text', + url: `https://www.youtube.com/watch?v=${getVideoId()}`, + onload: function (xhr) { + if (xhr) { + let result = getDislikesFromYoutubeResponse(xhr.response); + if (result) { + cLog("response from youtube:"); + cLog(JSON.stringify(result)); + if (result.likes || result.dislikes) { + const formattedDislike = numberFormat(result.dislikes); + setDislikes(formattedDislike); + createRateBar(result.likes, result.dislikes); + statsSet = true; + } + } + + } + } + }) doXHR({ method: "GET", @@ -153,7 +181,7 @@ function setState() { "https://return-youtube-dislike-api.azurewebsites.net/votes?videoId=" + getVideoId(), onload: function (xhr) { - if (xhr != undefined) { + if (xhr != undefined && !statsSet) { const { dislikes, likes } = xhr.response; cLog(`Received count: ${dislikes}`); setDislikes(numberFormat(dislikes)); @@ -212,6 +240,37 @@ function numberFormat(numberState) { return formatter.format(roundDown(numberState)).replace(/\.0|,0/, ''); } +function getDislikesFromYoutubeResponse(htmlResponse) { + let start = + htmlResponse.indexOf('"videoDetails":') + '"videoDetails":'.length; + let end = + htmlResponse.indexOf('"isLiveContent":false}', start) + + '"isLiveContent":false}'.length; + if (end < start) { + end = + htmlResponse.indexOf('"isLiveContent":true}', start) + + '"isLiveContent":true}'.length; + } + let jsonStr = htmlResponse.substring(start, end); + let jsonResult = JSON.parse(jsonStr); + let rating = jsonResult.averageRating; + + start = htmlResponse.indexOf('"topLevelButtons":[', end); + start = + htmlResponse.indexOf('"accessibilityData":', start) + + '"accessibilityData":'.length; + end = htmlResponse.indexOf("}", start); + let likes = +htmlResponse.substring(start, end).replace(/\D/g, ""); + let dislikes = (likes * (5 - rating)) / (rating - 1); + let result = { + likes, + dislikes: Math.round(dislikes), + rating, + viewCount: +jsonResult.viewCount, + }; + return result; +} + function setEventListeners(evt) { function checkForJS_Finish() { if (getButtons()?.offsetParent && isVideoLoaded()) { From 2a4b1b95d18cf9d6c52f91165149cbf0a4cc3de4 Mon Sep 17 00:00:00 2001 From: DARKDRAGON532 <69623818+DARKDRAGON532@users.noreply.github.com> Date: Mon, 29 Nov 2021 22:52:23 +0530 Subject: [PATCH 2/4] formatted with prettier --- .../UserScript/Return Youtube Dislike.user.js | 81 ++++++++++--------- 1 file changed, 41 insertions(+), 40 deletions(-) diff --git a/Extensions/UserScript/Return Youtube Dislike.user.js b/Extensions/UserScript/Return Youtube Dislike.user.js index 91a80c7..18b6094 100644 --- a/Extensions/UserScript/Return Youtube Dislike.user.js +++ b/Extensions/UserScript/Return Youtube Dislike.user.js @@ -14,44 +14,48 @@ // @updateURL https://github.com/Anarios/return-youtube-dislike/raw/main/Extensions/UserScript/Return%20Youtube%20Dislike.user.js // @grant GM.xmlHttpRequest // ==/UserScript== -function cLog(text, subtext = '') { - subtext = subtext.trim() === '' ? '' : `(${subtext})`; +function cLog(text, subtext = "") { + subtext = subtext.trim() === "" ? "" : `(${subtext})`; console.log(`[Return Youtube Dislikes] ${text} ${subtext}`); } function doXHR(opts) { - if (typeof GM_xmlhttpRequest === 'function') { + if (typeof GM_xmlhttpRequest === "function") { return GM_xmlhttpRequest(opts); } - if (typeof GM !== 'undefined') /*This will prevent from throwing "Uncaught ReferenceError: GM is not defined"*/ { - if (typeof GM.xmlHttpRequest === 'function') { + if (typeof GM !== "undefined") { + /*This will prevent from throwing "Uncaught ReferenceError: GM is not defined"*/ if ( + typeof GM.xmlHttpRequest === "function" + ) { return GM.xmlHttpRequest(opts); } } - console.warn('Unable to detect UserScript plugin, falling back to native XHR.'); + console.warn( + "Unable to detect UserScript plugin, falling back to native XHR." + ); const xhr = new XMLHttpRequest(); xhr.open(opts.method, opts.url, true); - if (opts.responseType === 'text') { - xhr.onload = () => opts.onload({ - response: xhr.responseText, - }); + if (opts.responseType === "text") { + xhr.onload = () => + opts.onload({ + response: xhr.responseText, + }); } else { - xhr.onload = () => opts.onload({ - response: JSON.parse(xhr.responseText), - }); + xhr.onload = () => + opts.onload({ + response: JSON.parse(xhr.responseText), + }); } - xhr.onerror = err => console.error('XHR Failed', err); + xhr.onerror = (err) => console.error("XHR Failed", err); xhr.send(); } function getButtons() { if (document.getElementById("menu-container").offsetParent === null) { - return document.querySelector( - "ytd-menu-renderer.ytd-watch-metadata > div" - ); + return document.querySelector("ytd-menu-renderer.ytd-watch-metadata > div"); } else { return document .getElementById("menu-container") @@ -102,9 +106,7 @@ function setDislikes(dislikesCount) { } function createRateBar(likes, dislikes) { - var rateBar = document.getElementById( - "return-youtube-dislike-bar-container" - ); + var rateBar = document.getElementById("return-youtube-dislike-bar-container"); const widthPx = getButtons().children[0].clientWidth + @@ -150,11 +152,11 @@ function createRateBar(likes, dislikes) { } function setState() { - cLog('Fetching votes...'); + cLog("Fetching votes..."); let statsSet = false; doXHR({ - method: 'GET', - responseType: 'text', + method: "GET", + responseType: "text", url: `https://www.youtube.com/watch?v=${getVideoId()}`, onload: function (xhr) { if (xhr) { @@ -162,17 +164,16 @@ function setState() { if (result) { cLog("response from youtube:"); cLog(JSON.stringify(result)); - if (result.likes || result.dislikes) { - const formattedDislike = numberFormat(result.dislikes); - setDislikes(formattedDislike); - createRateBar(result.likes, result.dislikes); - statsSet = true; - } + if (result.likes || result.dislikes) { + const formattedDislike = numberFormat(result.dislikes); + setDislikes(formattedDislike); + createRateBar(result.likes, result.dislikes); + statsSet = true; + } } - } - } - }) + }, + }); doXHR({ method: "GET", @@ -192,12 +193,12 @@ function setState() { } function likeClicked() { - cLog('Like clicked', getState()); + cLog("Like clicked", getState()); setState(); } function dislikeClicked() { - cLog('Dislike clicked', getState()); + cLog("Dislike clicked", getState()); setState(); } @@ -225,19 +226,19 @@ function roundDown(num) { const int = Math.floor(Math.log10(num) - 2); const decimal = int + (int % 3 ? 1 : 0); const value = Math.floor(num / 10 ** decimal); - return value * (10 ** decimal); + return value * 10 ** decimal; } function numberFormat(numberState) { const userLocales = navigator.language; const formatter = Intl.NumberFormat(userLocales, { - notation: 'compact', + notation: "compact", minimumFractionDigits: 1, - maximumFractionDigits: 1 + maximumFractionDigits: 1, }); - return formatter.format(roundDown(numberState)).replace(/\.0|,0/, ''); + return formatter.format(roundDown(numberState)).replace(/\.0|,0/, ""); } function getDislikesFromYoutubeResponse(htmlResponse) { @@ -278,7 +279,7 @@ function setEventListeners(evt) { const buttons = getButtons(); if (!window.returnDislikeButtonlistenersSet) { - cLog('Registering button listeners...'); + cLog("Registering button listeners..."); buttons.children[0].addEventListener("click", likeClicked); buttons.children[1].addEventListener("click", dislikeClicked); window.returnDislikeButtonlistenersSet = true; @@ -288,7 +289,7 @@ function setEventListeners(evt) { } if (window.location.href.indexOf("watch?") >= 0) { - cLog('Setting up...'); + cLog("Setting up..."); var jsInitChecktimer = setInterval(checkForJS_Finish, 111); } } From ae1072ac675ec65beba882a096009c7f9f715712 Mon Sep 17 00:00:00 2001 From: DARKDRAGON532 <69623818+DARKDRAGON532@users.noreply.github.com> Date: Tue, 30 Nov 2021 21:16:00 +0530 Subject: [PATCH 3/4] fixed userscript --- .../UserScript/Return Youtube Dislike.user.js | 83 +++++-------------- 1 file changed, 20 insertions(+), 63 deletions(-) diff --git a/Extensions/UserScript/Return Youtube Dislike.user.js b/Extensions/UserScript/Return Youtube Dislike.user.js index 18b6094..6a23354 100644 --- a/Extensions/UserScript/Return Youtube Dislike.user.js +++ b/Extensions/UserScript/Return Youtube Dislike.user.js @@ -19,40 +19,6 @@ function cLog(text, subtext = "") { console.log(`[Return Youtube Dislikes] ${text} ${subtext}`); } -function doXHR(opts) { - if (typeof GM_xmlhttpRequest === "function") { - return GM_xmlhttpRequest(opts); - } - if (typeof GM !== "undefined") { - /*This will prevent from throwing "Uncaught ReferenceError: GM is not defined"*/ if ( - typeof GM.xmlHttpRequest === "function" - ) { - return GM.xmlHttpRequest(opts); - } - } - - console.warn( - "Unable to detect UserScript plugin, falling back to native XHR." - ); - - const xhr = new XMLHttpRequest(); - - xhr.open(opts.method, opts.url, true); - if (opts.responseType === "text") { - xhr.onload = () => - opts.onload({ - response: xhr.responseText, - }); - } else { - xhr.onload = () => - opts.onload({ - response: JSON.parse(xhr.responseText), - }); - } - xhr.onerror = (err) => console.error("XHR Failed", err); - xhr.send(); -} - function getButtons() { if (document.getElementById("menu-container").offsetParent === null) { return document.querySelector("ytd-menu-renderer.ytd-watch-metadata > div"); @@ -154,42 +120,33 @@ function createRateBar(likes, dislikes) { function setState() { cLog("Fetching votes..."); let statsSet = false; - doXHR({ - method: "GET", - responseType: "text", - url: `https://www.youtube.com/watch?v=${getVideoId()}`, - onload: function (xhr) { - if (xhr) { - let result = getDislikesFromYoutubeResponse(xhr.response); - if (result) { - cLog("response from youtube:"); - cLog(JSON.stringify(result)); - if (result.likes || result.dislikes) { - const formattedDislike = numberFormat(result.dislikes); - setDislikes(formattedDislike); - createRateBar(result.likes, result.dislikes); - statsSet = true; - } + + fetch(`https://www.youtube.com/watch?v=${getVideoId()}`).then(response => { + response.text().then(text => { + let result = getDislikesFromYoutubeResponse(text) + if (result) { + cLog("response from youtube:"); + cLog(JSON.stringify(result)); + if (result.likes || result.dislikes) { + const formattedDislike = numberFormat(result.dislikes); + setDislikes(formattedDislike); + createRateBar(result.likes, result.dislikes); + statsSet = true; } } - }, - }); + }) + }) - doXHR({ - method: "GET", - responseType: "json", - url: - "https://return-youtube-dislike-api.azurewebsites.net/votes?videoId=" + - getVideoId(), - onload: function (xhr) { - if (xhr != undefined && !statsSet) { - const { dislikes, likes } = xhr.response; + fetch(`https://return-youtube-dislike-api.azurewebsites.net/votes?videoId=${getVideoId()}`).then(response => { + response.json().then(json => { + if (json && !statsSet) { + const { dislikes, likes } = json; cLog(`Received count: ${dislikes}`); setDislikes(numberFormat(dislikes)); createRateBar(likes, dislikes); } - }, - }); + }) + }) } function likeClicked() { From cdb784e387f592bdbf06f5a9c261dc77c5654ef1 Mon Sep 17 00:00:00 2001 From: DARKDRAGON532 <69623818+DARKDRAGON532@users.noreply.github.com> Date: Tue, 30 Nov 2021 21:16:30 +0530 Subject: [PATCH 4/4] formatted with prettier --- .../UserScript/Return Youtube Dislike.user.js | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/Extensions/UserScript/Return Youtube Dislike.user.js b/Extensions/UserScript/Return Youtube Dislike.user.js index 6a23354..1a2d744 100644 --- a/Extensions/UserScript/Return Youtube Dislike.user.js +++ b/Extensions/UserScript/Return Youtube Dislike.user.js @@ -121,9 +121,9 @@ function setState() { cLog("Fetching votes..."); let statsSet = false; - fetch(`https://www.youtube.com/watch?v=${getVideoId()}`).then(response => { - response.text().then(text => { - let result = getDislikesFromYoutubeResponse(text) + fetch(`https://www.youtube.com/watch?v=${getVideoId()}`).then((response) => { + response.text().then((text) => { + let result = getDislikesFromYoutubeResponse(text); if (result) { cLog("response from youtube:"); cLog(JSON.stringify(result)); @@ -134,19 +134,21 @@ function setState() { statsSet = true; } } - }) - }) + }); + }); - fetch(`https://return-youtube-dislike-api.azurewebsites.net/votes?videoId=${getVideoId()}`).then(response => { - response.json().then(json => { + fetch( + `https://return-youtube-dislike-api.azurewebsites.net/votes?videoId=${getVideoId()}` + ).then((response) => { + response.json().then((json) => { if (json && !statsSet) { const { dislikes, likes } = json; cLog(`Received count: ${dislikes}`); setDislikes(numberFormat(dislikes)); createRateBar(likes, dislikes); } - }) - }) + }); + }); } function likeClicked() {