From c36a0ab58d6ffa1d3dd090fe20d787e1b33bb43e Mon Sep 17 00:00:00 2001 From: Dmitrii Selivanov Date: Mon, 13 Dec 2021 04:55:36 +0300 Subject: [PATCH] FF and chrome are now combined, version 2.0 - votes counting, proof of work --- Extensions/combined/content-style.css | 26 ++ Extensions/combined/icons/icon128.png | Bin 0 -> 3850 bytes Extensions/combined/icons/icon48.png | Bin 0 -> 1632 bytes Extensions/combined/init/init.js | 1 + Extensions/combined/manifest.json | 27 ++ Extensions/combined/manifestv3.json | 41 +++ Extensions/combined/popup.css | 119 +++++++ Extensions/combined/popup.html | 48 +++ Extensions/combined/popup.js | 58 ++++ Extensions/combined/ryd.background.js | 257 ++++++++++++++ Extensions/combined/ryd.content-script.js | 399 ++++++++++++++++++++++ Extensions/combined/ryd.tools.js | 17 + 12 files changed, 993 insertions(+) create mode 100644 Extensions/combined/content-style.css create mode 100644 Extensions/combined/icons/icon128.png create mode 100644 Extensions/combined/icons/icon48.png create mode 100644 Extensions/combined/init/init.js create mode 100644 Extensions/combined/manifest.json create mode 100644 Extensions/combined/manifestv3.json create mode 100644 Extensions/combined/popup.css create mode 100644 Extensions/combined/popup.html create mode 100644 Extensions/combined/popup.js create mode 100644 Extensions/combined/ryd.background.js create mode 100644 Extensions/combined/ryd.content-script.js create mode 100644 Extensions/combined/ryd.tools.js diff --git a/Extensions/combined/content-style.css b/Extensions/combined/content-style.css new file mode 100644 index 0000000..c06b29c --- /dev/null +++ b/Extensions/combined/content-style.css @@ -0,0 +1,26 @@ +#ryd-bar-container { + background: var(--yt-spec-icon-disabled); + border-radius: 2px; +} + +#ryd-bar { + background: var(--yt-spec-text-primary); + border-radius: 2px; + transition: all 0.15s ease-in-out; +} + +.ryd-tooltip { + position: relative; + display: block; + height: 2px; + top: 9px; +} + +.ryd-tooltip-bar-container { + width: 100%; + height: 2px; + position: absolute; + padding-top: 6px; + padding-bottom: 28px; + top: -6px; +} diff --git a/Extensions/combined/icons/icon128.png b/Extensions/combined/icons/icon128.png new file mode 100644 index 0000000000000000000000000000000000000000..3d06eba383eaac85c14c353a8a8b47415a1eed25 GIT binary patch literal 3850 zcmV+l5B2bgP)Px@#7RU!RCr$Po!f65R~f*+bz)l~3MBTpxwwTkpg^G%C~b+jL=^(@55Pk!XhHA- z5-;$8ctN~S!9yj45P}!PzW^0NTm%9tgs1?45T%qts@9kFW#h!z*lVwM(OK`Y&z||d z?_B20%$eC;DN=UlT)*%4-OkLe8;gsJeVDweB>|zaMwlfx>Iy(+8D$;-Q&290W+I`s z0A!L1(K$Z#W#8olfb24~8X;DACIDEeFV;rcv6=u-h;FkhD(Etm11SH}W=)q6!C?|dZBD0tndC78ChXCL& zajvKTsP-bapToYT{p@}%v6U3Ly7)bSpIj%sEG6I#K#`QvyK6;Ft6B zusJhhl=;bC4?ecCGFY=1LyoQfAG`KKlEAImS>yO28ZZEq@2Nhx1^{^CLc+cP0O0F6tO09@VKfiJdN1GlVNq>pk-(2|CaZUG z|Cp;*p?a19-~*0TfLQncDhYsvb(`YF=UXj!WM{|8`l;BAC3CLseZ;#cK#HxZ*85Wi zfcG1!06C62-t{DbJB}W}SN!=TfhJ88*MGRQms5}7QAC`W)GI1AwSW1}`Pq}=vRpTWZHlBd%7X|=SaHzyj z9a{omy6@qlbSgync>v#lL#+7H{yuztQ2O~F{9s8RWwC1MWeN#Y`KONkD+Yjvi6jt< z{W7F1+(D$&C; z{bTQdZde_!K1gE9 z;HlF%9UyL;KQREjmGA&^Ke{&&^K3c;U|n&i8kzy{ADiqcO22O{FCX4e$x!lf9)MCT zcM8b$(L;p#{&@m`sa_8x0N81uZuxTlR^0)3veklj@9Z4in6bH|Cxvrl-3f%3+b9tPz2H|pfRSHU>Qb)d&Yq$Aaw)qPKz+1E&K)QVD3_y&z6%+tIh8GUN``T^z1ajApdg4Zp z=Lax)YUkq8br)|66IkYs9pwC#0pPMl6`*^9n<)TtO2kC1QuLpW{pPUrQx$Hqc$?CY z$_Gqt9;*znKHO)2V*t3%a1MY$b}LD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3P( zQSG$ze*L!*f%^isyJyYRu9^tA#Lkn67=ZNa&5}0-UPa>+gg=-F%#sMi4?|8i&QfKb zqfSEi#uCarNyT!?eQ6RrEax)T zecZ8(Jp=E#7h4_c;7A8db_=xvZxhvLp$*XLtwbJ?CDxRy zqOA0*JPE%8DaY>ImG;T7qzYX+QH5kP*=W+=!C2t@kO&NRu)cpK{9A?5T0(ZW9U=WU zZpxOOfi3@M{Z{Wr+nsYv51jYuyKc?OZ7ivSu>2HkZg(MjUm*mpfLXI)mzG$jF2oYl z1cnM;$P_|gE<8U8o{A#ie-WGB`GAAehP3l85`_?03jHPM&gwsI{)~i**!e;U+zOQn zlp+a55y-R+@%19X7bT&tCGfYkPhYhy8hjxHu7pL?;$|=coz4MAY&gIdLSPPT90zNy zWc2xPfiHx>LO2w_Rk{X@6!=02%n#`AsL@@Qk8&GnAr1_&NVQYkhHRskcd)#>!UsiH z*ml4d5&@ZH8l_jpQ|)y!8cxj*ODiFhcEii#;lYsvUswd(u3Q4w|5gA0^T>UMoC6~V e)xXk3PvAc~^Od(ONImWV0000 + + + + Return YouTube Dislike + + + + + + +
+ Logo +

Return YouTube Dislike

+

by Dmitrii Selivanov & Community

+ + + + + +

+ +
+ +
+ +
+ +
+ +
+ Settings + +
+ +
+
+ + + diff --git a/Extensions/combined/popup.js b/Extensions/combined/popup.js new file mode 100644 index 0000000..002cba2 --- /dev/null +++ b/Extensions/combined/popup.js @@ -0,0 +1,58 @@ +/* Config */ +const config = { + advanced: false, + showAdvancedMessage: "Show Settings", + hideAdvancedMessage: "Hide Settings", + + links: { + website: "https://returnyoutubedislike.com", + github: "https://github.com/Anarios/return-youtube-dislike", + discord: "https://discord.gg/mYnESY4Md5", + donate: 'https://returnyoutubedislike.com/donate' + }, +}; + +/* Links */ +document.getElementById("link_website").addEventListener("click", () => { + chrome.tabs.create({ url: config.links.website }); +}); + +document.getElementById("link_github").addEventListener("click", () => { + chrome.tabs.create({ url: config.links.github }); +}); + +document.getElementById("link_discord").addEventListener("click", () => { + chrome.tabs.create({ url: config.links.discord }); +}); + +document.getElementById("link_donate").addEventListener("click", () => { + chrome.tabs.create({ url: config.links.donate }); +}); + +/* Advanced Toggle */ +/* Not currently used in this version +const advancedToggle = document.getElementById("advancedToggle"); +advancedToggle.addEventListener("click", () => { + const adv = document.getElementById("advancedSettings"); + if (config.advanced) { + adv.style.display = "none"; + advancedToggle.innerHTML = config.showAdvancedMessage; + config.advanced = false; + } else { + adv.style.display = "block"; + advancedToggle.innerHTML = config.hideAdvancedMessage; + config.advanced = true; + } +}); +*/ + +/* popup-script.js +document.querySelector('#login') +.addEventListener('click', function () { + chrome.runtime.sendMessage({ message: 'get_auth_token' }); +}); + +document.querySelector("#log_off").addEventListener("click", function () { + chrome.runtime.sendMessage({ message: "log_off" }); +}); +*/ diff --git a/Extensions/combined/ryd.background.js b/Extensions/combined/ryd.background.js new file mode 100644 index 0000000..5e3e117 --- /dev/null +++ b/Extensions/combined/ryd.background.js @@ -0,0 +1,257 @@ +const apiUrl = "https://returnyoutubedislikeapi.com"; +let api; +if (typeof chrome !== "undefined" && typeof chrome.runtime !== "undefined") + api = chrome; +else if ( + typeof browser !== "undefined" && + typeof browser.runtime !== "undefined" +) + api = browser; + +api.runtime.onMessage.addListener((request, sender, sendResponse) => { + if (request.message === "get_auth_token") { + // chrome.identity.getAuthToken({ interactive: true }, function (token) { + // console.log(token); + // chrome.identity.getProfileUserInfo(function (userInfo) { + // console.log(JSON.stringify(userInfo)); + // }); + // }); + } else if (request.message === "log_off") { + // chrome.identity.clearAllCachedAuthTokens(() => console.log("logged off")); + } else if (request.message == "set_state") { + // chrome.identity.getAuthToken({ interactive: true }, function (token) { + let token = ""; + fetch(`${apiUrl}/votes?videoId=${request.videoId}&likeCount=${request.likeCount || ''}`, { + method: "GET", + headers: { + Accept: "application/json", + }, + }) + .then((response) => response.json()) + .then((response) => { + sendResponse(response); + }) + .catch(); + return true; + } else if (request.message == "send_links") { + toSend = toSend.concat(request.videoIds.filter((x) => !sentIds.has(x))); + if (toSend.length >= 20) { + fetch(`${apiUrl}/votes`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(toSend), + }); + for (const toSendUrl of toSend) { + sentIds.add(toSendUrl); + } + toSend = []; + } + } else if (request.message == "fetch_from_youtube") { + fetch(`https://www.youtube.com/watch?v=${request.videoId}`, { + method: "GET", + }) + .then((response) => response.text()) + .then((text) => { + let result = getDislikesFromYoutubeResponse(text); + sendUserSubmittedStatisticsToApi({ + ...result, + videoId: request.videoId, + }); + sendResponse(result); + }); + return true; + } else if (request.message == "register") { + register(); + return true; + } else if (request.message == "send_vote") { + sendVote(request.videoId, request.vote); + return true; + } +}); + +async function sendVote(videoId, vote) { + api.storage.sync.get(null, async (storageResult) => { + if (!storageResult.userId || !storageResult.registrationConfirmed) { + register().then(() => sendVote(videoId, vote)); + } + fetch(`${apiUrl}/interact/vote`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + userId: storageResult.userId, + videoId, + value: vote, + }), + }) + .then((response) => response.json()) + .then((response) => { + solvePuzzle(response).then((solvedPuzzle) => { + fetch(`${apiUrl}/interact/confirmVote`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + ...solvedPuzzle, + userId: storageResult.userId, + videoId, + }), + }); + }); + }); + }); +} + +function register() { + let userId = generateUserID(); + api.storage.sync.set({ userId }); + return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, { + method: "GET", + headers: { + Accept: "application/json", + }, + }) + .then((response) => response.json()) + .then((response) => { + return solvePuzzle(response).then((solvedPuzzle) => { + return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(solvedPuzzle), + }).then((response) => + response.json().then((result) => { + if (result === true) { + return api.storage.sync.set({ registrationConfirmed: true }); + } + }) + ); + }); + }) + .catch(); +} + +api.storage.sync.get(null, (res) => { + if (!res.userId || !res.registrationConfirmed) { + register(); + } +}); + +const sentIds = new Set(); +let toSend = []; + +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 sendUserSubmittedStatisticsToApi(statistics) { + fetch(`${apiUrl}/votes/user-submitted`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(statistics), + }); +} + +function countLeadingZeroes(uInt8View, limit) { + let zeroes = 0; + let value = 0; + for (let i = 0; i < uInt8View.length; i++) { + value = uInt8View[i]; + if (value === 0) { + zeroes += 8; + } else { + let count = 1; + if (value >>> 4 === 0) { + count += 4; + value <<= 4; + } + if (value >>> 6 === 0) { + count += 2; + value <<= 2; + } + zeroes += count - (value >>> 7); + break; + } + if (zeroes >= limit) { + break; + } + } + return zeroes; +} + +async function solvePuzzle(puzzle) { + let challenge = Uint8Array.from(atob(puzzle.challenge), (c) => + c.charCodeAt(0) + ); + let buffer = new ArrayBuffer(20); + let uInt8View = new Uint8Array(buffer); + let uInt32View = new Uint32Array(buffer); + let maxCount = Math.pow(2, puzzle.difficulty) * 5; + for (let i = 4; i < 20; i++) { + uInt8View[i] = challenge[i - 4]; + } + + for (let i = 0; i < maxCount; i++) { + uInt32View[0] = i; + let hash = await crypto.subtle.digest("SHA-512", buffer); + let hashUint8 = new Uint8Array(hash); + if (countLeadingZeroes(hashUint8) >= puzzle.difficulty) { + return { + solution: btoa(String.fromCharCode.apply(null, uInt8View.slice(0, 4))), + }; + } + } +} + +function generateUserID(length = 36) { + const charset = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + let result = ""; + if (crypto && crypto.getRandomValues) { + const values = new Uint32Array(length); + crypto.getRandomValues(values); + for (let i = 0; i < length; i++) { + result += charset[values[i] % charset.length]; + } + return result; + } else { + for (let i = 0; i < length; i++) { + result += charset[Math.floor(Math.random() * charset.length)]; + } + return result; + } +} diff --git a/Extensions/combined/ryd.content-script.js b/Extensions/combined/ryd.content-script.js new file mode 100644 index 0000000..dcfa7c6 --- /dev/null +++ b/Extensions/combined/ryd.content-script.js @@ -0,0 +1,399 @@ +function RYD() { + const LIKED_STATE = "LIKED_STATE"; + const DISLIKED_STATE = "DISLIKED_STATE"; + const NEUTRAL_STATE = "NEUTRAL_STATE"; + + let storedData = { + likes: 0, + dislikes: 0, + previousState: NEUTRAL_STATE, + }; + + function cLog(message, writer) { + message = `[return youtube dislike]: ${message}`; + if (writer) { + writer(message); + } else { + console.log(message); + } + } + + function isMobile() { + return location.hostname == "m.youtube.com"; + } + + function getButtons() { + if (isMobile()) { + return document.querySelector(".slim-video-action-bar-actions"); + } + //--- If Menu Element Is Displayed: ---// + if (document.getElementById("menu-container")?.offsetParent === null) { + return document.querySelector( + "ytd-menu-renderer.ytd-watch-metadata > div" + ); + //--- If Menu Element Isnt Displayed: ---// + } else { + return document + .getElementById("menu-container") + ?.querySelector("#top-level-buttons-computed"); + } + } + + function getLikeButton() { + return getButtons().children[0]; + } + + function getDislikeButton() { + return getButtons().children[1]; + } + + function isVideoLiked() { + if (isMobile()) { + return ( + getLikeButton().querySelector("button").getAttribute("aria-label") == + "true" + ); + } + return getLikeButton().classList.contains("style-default-active"); + } + + function isVideoDisliked() { + if (isMobile()) { + return ( + getDislikeButton().querySelector("button").getAttribute("aria-label") == + "true" + ); + } + return getDislikeButton().classList.contains("style-default-active"); + } + + function isVideoNotLiked() { + return getLikeButton().classList.contains("style-text"); + } + + function isVideoNotDisliked() { + return getDislikeButton().classList.contains("style-text"); + } + + function checkForSignInButton() { + if ( + document.querySelector( + "a[href^='https://accounts.google.com/ServiceLogin']" + ) + ) { + return true; + } else { + return false; + } + } + + function getState() { + if (isVideoLiked()) { + return { current: LIKED_STATE, previous: storedData.previousState }; + } + if (isVideoDisliked()) { + return { current: DISLIKED_STATE, previous: storedData.previousState }; + } + return { current: NEUTRAL_STATE, previous: storedData.previousState }; + } + + //--- Sets The Likes And Dislikes Values ---// + function setLikes(likesCount) { + getButtons().children[0].querySelector("#text").innerText = likesCount; + } + + function setDislikes(dislikesCount) { + if (isMobile()) { + getButtons().children[1].querySelector( + ".button-renderer-text" + ).innerText = dislikesCount; + return; + } + getButtons().children[1].querySelector("#text").innerText = dislikesCount; + } + + function getLikeCountFromButton() { + let likesStr = getLikeButton() + .querySelector("button") + .getAttribute("aria-label") + .replace(/\D/g, ""); + return likesStr.length > 0 ? parseInt(likesStr) : false; + } + + function processResponse(response) { + const formattedDislike = numberFormat(response.dislikes); + setDislikes(formattedDislike); + storedData.dislikes = parseInt(response.dislikes); + storedData.likes = getLikeCountFromButton() || parseInt(response.likes); + createRateBar(storedData.likes, storedData.dislikes); + } + + function setState() { + storedData.previousState = isVideoDisliked() + ? DISLIKED_STATE + : isVideoLiked() + ? LIKED_STATE + : NEUTRAL_STATE; + let statsSet = false; + RYDTools.getBrowser().runtime.sendMessage( + { + message: "fetch_from_youtube", + videoId: getVideoId(window.location.href), + }, + function (response) { + if (response !== undefined) { + cLog("response from youtube:"); + cLog(JSON.stringify(response)); + try { + if ( + "likes" in response && + "dislikes" in response && + response.dislikes !== null + ) { + processResponse(response); + statsSet = true; + } + } catch (e) {} + } + } + ); + + RYDTools.getBrowser().runtime.sendMessage( + { + message: "set_state", + videoId: getVideoId(window.location.href), + state: getState().current, + likeCount: getLikeCountFromButton() || null + }, + function (response) { + cLog("response from api:"); + cLog(JSON.stringify(response)); + if (response !== undefined && !("traceId" in response) && !statsSet) { + processResponse(response); + } else { + } + } + ); + } + + function sendVote(vote) { + RYDTools.getBrowser().runtime.sendMessage({ + message: "send_vote", + vote: vote, + videoId: getVideoId(window.location.href) + }); + } + + function likeClicked() { + if (checkForSignInButton() === false) { + if (storedData.previousState === DISLIKED_STATE) { + sendVote(1); + storedData.dislikes--; + storedData.likes++; + createRateBar(storedData.likes, storedData.dislikes); + setDislikes(numberFormat(storedData.dislikes)); + storedData.previousState = LIKED_STATE; + } else if (storedData.previousState === NEUTRAL_STATE) { + sendVote(1); + storedData.likes++; + createRateBar(storedData.likes, storedData.dislikes); + storedData.previousState = LIKED_STATE; + } else if ((storedData.previousState = LIKED_STATE)) { + sendVote(0); + storedData.likes--; + createRateBar(storedData.likes, storedData.dislikes); + storedData.previousState = NEUTRAL_STATE; + } + } + } + + function dislikeClicked() { + if (checkForSignInButton() == false) { + if (storedData.previousState === NEUTRAL_STATE) { + sendVote(-1); + storedData.dislikes++; + setDislikes(numberFormat(storedData.dislikes)); + createRateBar(storedData.likes, storedData.dislikes); + storedData.previousState = DISLIKED_STATE; + } else if (storedData.previousState === DISLIKED_STATE) { + sendVote(0); + storedData.dislikes--; + setDislikes(numberFormat(storedData.dislikes)); + createRateBar(storedData.likes, storedData.dislikes); + storedData.previousState = NEUTRAL_STATE; + } else if (storedData.previousState === LIKED_STATE) { + sendVote(-1); + storedData.likes--; + storedData.dislikes++; + setDislikes(numberFormat(storedData.dislikes)); + createRateBar(storedData.likes, storedData.dislikes); + storedData.previousState = DISLIKED_STATE; + } + } + } + + function setInitialState() { + setState(); + setTimeout(() => { + sendVideoIds(); + }, 1500); + } + + function getVideoId(url) { + const urlObject = new URL(url); + const pathname = urlObject.pathname; + if (pathname.startsWith("/clip")) { + return document.querySelector("meta[itemprop='videoId']").content; + } else { + return urlObject.searchParams.get("v"); + } + } + + function isVideoLoaded() { + const videoId = getVideoId(window.location.href); + return ( + document.querySelector(`ytd-watch-flexy[video-id='${videoId}']`) !== + null || + // mobile: no video-id attribute + document.querySelector('#player[loading="false"]:not([hidden])') !== null + ); + } + + function roundDown(num) { + if (num < 1000) return 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; + } + + function numberFormat(numberState) { + let userLocales; + try { + userLocales = new URL( + Array.from(document.querySelectorAll("head > link[rel='search']")) + ?.find((n) => n?.getAttribute("href")?.includes("?locale=")) + ?.getAttribute("href") + )?.searchParams?.get("locale"); + } catch {} + const formatter = Intl.NumberFormat( + document.documentElement.lang || userLocales || navigator.language, + { + notation: "compact", + } + ); + + return formatter.format(roundDown(numberState)); + } + + let jsInitChecktimer = null; + + function setEventListeners(evt) { + function checkForJS_Finish() { + if (getButtons()?.offsetParent && isVideoLoaded()) { + clearInterval(jsInitChecktimer); + jsInitChecktimer = null; + const buttons = getButtons(); + if (!window.returnDislikeButtonlistenersSet) { + buttons.children[0].addEventListener("click", likeClicked); + buttons.children[1].addEventListener("click", dislikeClicked); + window.returnDislikeButtonlistenersSet = true; + } + setInitialState(); + } + } + + if (window.location.href.indexOf("watch?") >= 0) { + jsInitChecktimer = setInterval(checkForJS_Finish, 111); + } + } + + function createRateBar(likes, dislikes) { + let rateBar = document.getElementById("ryd-bar-container"); + + const widthPx = + getButtons().children[0].clientWidth + + getButtons().children[1].clientWidth + + 8; + + const widthPercent = + likes + dislikes > 0 ? (likes / (likes + dislikes)) * 100 : 50; + + if (!rateBar) { + ( + document.getElementById("menu-container") || + document.querySelector("ytm-slim-video-action-bar-renderer") + ).insertAdjacentHTML( + "beforeend", + ` +
+
+
+
+
+
+ + ${likes.toLocaleString()} / ${dislikes.toLocaleString()} + +
+ ` + ); + } else { + document.getElementById("ryd-bar-container").style.width = widthPx + "px"; + document.getElementById("ryd-bar").style.width = widthPercent + "%"; + + document.querySelector( + "#ryd-dislike-tooltip > #tooltip" + ).innerHTML = `${likes.toLocaleString()} / ${dislikes.toLocaleString()}`; + } + } + + function sendVideoIds() { + let links = Array.from( + document.getElementsByClassName( + "yt-simple-endpoint ytd-compact-video-renderer" + ) + ).concat( + Array.from( + document.getElementsByClassName("yt-simple-endpoint ytd-thumbnail") + ) + ); + // Also try mobile + if (links.length < 1) + links = Array.from( + document.querySelectorAll( + ".large-media-item-metadata > a, a.large-media-item-thumbnail-container" + ) + ); + const ids = links + .filter((x) => x.href && x.href.indexOf("/watch?v=") > 0) + .map((x) => getVideoId(x.href)); + RYDTools.getBrowser().runtime.sendMessage({ + message: "send_links", + videoIds: ids, + }); + } + + setEventListeners(); + + document.addEventListener("yt-navigate-finish", function (event) { + if (jsInitChecktimer !== null) clearInterval(jsInitChecktimer); + window.returnDislikeButtonlistenersSet = false; + setEventListeners(); + }); + + setTimeout(() => sendVideoIds(), 2500); + + this.init = function () {}; +} + +RYD.getInstance = function () { + if (typeof RYD.instance == "undefined") RYD.instance = new RYD(); + return RYD.instance; +}; diff --git a/Extensions/combined/ryd.tools.js b/Extensions/combined/ryd.tools.js new file mode 100644 index 0000000..b6d9817 --- /dev/null +++ b/Extensions/combined/ryd.tools.js @@ -0,0 +1,17 @@ +RYDTools = {}; + +RYDTools.getBrowser = function () { + if (typeof chrome !== "undefined" && typeof chrome.runtime !== "undefined") { + return chrome; + } else if ( + typeof browser !== "undefined" && + typeof browser.runtime !== "undefined" + ) { + return browser; + } else { + console.log("browser is not supported"); + return false; + } +}; + +