Return Youtube Dislike.user.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. // ==UserScript==
  2. // @name Return YouTube Dislike
  3. // @namespace https://www.returnyoutubedislike.com/
  4. // @homepage https://www.returnyoutubedislike.com/
  5. // @version 0.9.0
  6. // @encoding utf-8
  7. // @description Return of the YouTube Dislike, Based off https://www.returnyoutubedislike.com/
  8. // @icon https://github.com/Anarios/return-youtube-dislike/raw/main/Icons/Return%20Youtube%20Dislike%20-%20Transparent.png
  9. // @author Anarios & JRWR
  10. // @match *://*.youtube.com/*
  11. // @exclude *://music.youtube.com/*
  12. // @exclude *://*.music.youtube.com/*
  13. // @compatible chrome
  14. // @compatible firefox
  15. // @compatible opera
  16. // @compatible safari
  17. // @compatible edge
  18. // @downloadURL https://github.com/Anarios/return-youtube-dislike/raw/main/Extensions/UserScript/Return%20Youtube%20Dislike.user.js
  19. // @updateURL https://github.com/Anarios/return-youtube-dislike/raw/main/Extensions/UserScript/Return%20Youtube%20Dislike.user.js
  20. // @grant GM.xmlHttpRequest
  21. // @connect youtube.com
  22. // @grant GM_addStyle
  23. // @run-at document-end
  24. // ==/UserScript==
  25. const LIKED_STATE = "LIKED_STATE";
  26. const DISLIKED_STATE = "DISLIKED_STATE";
  27. const NEUTRAL_STATE = "NEUTRAL_STATE";
  28. let previousState = 3; //1=LIKED, 2=DISLIKED, 3=NEUTRAL
  29. let likesvalue = 0;
  30. let dislikesvalue = 0;
  31. let isMobile = location.hostname == "m.youtube.com";
  32. let mobileDislikes = 0;
  33. function cLog(text, subtext = "") {
  34. subtext = subtext.trim() === "" ? "" : `(${subtext})`;
  35. console.log(`[Return YouTube Dislikes] ${text} ${subtext}`);
  36. }
  37. function getButtons() {
  38. if (isMobile) {
  39. return document.querySelector(".slim-video-action-bar-actions");
  40. }
  41. if (document.getElementById("menu-container")?.offsetParent === null) {
  42. return document.querySelector("ytd-menu-renderer.ytd-watch-metadata > div");
  43. } else {
  44. return document
  45. .getElementById("menu-container")
  46. ?.querySelector("#top-level-buttons-computed");
  47. }
  48. }
  49. function getLikeButton() {
  50. return getButtons().children[0];
  51. }
  52. function getDislikeButton() {
  53. return getButtons().children[1];
  54. }
  55. function isVideoLiked() {
  56. if (isMobile) {
  57. return (
  58. getLikeButton().querySelector("button").getAttribute("aria-label") ==
  59. "true"
  60. );
  61. }
  62. return getLikeButton().classList.contains("style-default-active");
  63. }
  64. function isVideoDisliked() {
  65. if (isMobile) {
  66. return (
  67. getDislikeButton().querySelector("button").getAttribute("aria-label") ==
  68. "true"
  69. );
  70. }
  71. return getDislikeButton().classList.contains("style-default-active");
  72. }
  73. function isVideoNotLiked() {
  74. if (isMobile) {
  75. return !isVideoLiked();
  76. }
  77. return getLikeButton().classList.contains("style-text");
  78. }
  79. function isVideoNotDisliked() {
  80. if (isMobile) {
  81. return !isVideoDisliked();
  82. }
  83. return getDislikeButton().classList.contains("style-text");
  84. }
  85. function checkForUserAvatarButton() {
  86. if (isMobile) {
  87. return;
  88. }
  89. if (document.querySelector('#avatar-btn')) {
  90. return true
  91. } else {
  92. return false
  93. }
  94. }
  95. function getState() {
  96. if (isVideoLiked()) {
  97. return LIKED_STATE;
  98. }
  99. if (isVideoDisliked()) {
  100. return DISLIKED_STATE;
  101. }
  102. return NEUTRAL_STATE;
  103. }
  104. function setLikes(likesCount) {
  105. if (isMobile) {
  106. getButtons().children[0].querySelector(".button-renderer-text").innerText =
  107. likesCount;
  108. return;
  109. }
  110. getButtons().children[0].querySelector("#text").innerText = likesCount;
  111. }
  112. function setDislikes(dislikesCount) {
  113. if (isMobile) {
  114. mobileDislikes = dislikesCount;
  115. return;
  116. }
  117. getButtons().children[1].querySelector("#text").innerText = dislikesCount;
  118. }
  119. (typeof GM_addStyle != "undefined"
  120. ? GM_addStyle
  121. : (styles) => {
  122. let styleNode = document.createElement("style");
  123. styleNode.type = "text/css";
  124. styleNode.innerText = styles;
  125. document.head.appendChild(styleNode);
  126. })(`
  127. #return-youtube-dislike-bar-container {
  128. background: var(--yt-spec-icon-disabled);
  129. border-radius: 2px;
  130. }
  131. #return-youtube-dislike-bar {
  132. background: var(--yt-spec-text-primary);
  133. border-radius: 2px;
  134. transition: all 0.15s ease-in-out;
  135. }
  136. .ryd-tooltip {
  137. position: relative;
  138. display: block;
  139. height: 2px;
  140. top: 9px;
  141. }
  142. .ryd-tooltip-bar-container {
  143. width: 100%;
  144. height: 2px;
  145. position: absolute;
  146. padding-top: 6px;
  147. padding-bottom: 28px;
  148. top: -6px;
  149. }
  150. `);
  151. function createRateBar(likes, dislikes) {
  152. if (isMobile) {
  153. return;
  154. }
  155. let rateBar = document.getElementById("return-youtube-dislike-bar-container");
  156. const widthPx =
  157. getButtons().children[0].clientWidth +
  158. getButtons().children[1].clientWidth +
  159. 8;
  160. const widthPercent =
  161. likes + dislikes > 0 ? (likes / (likes + dislikes)) * 100 : 50;
  162. if (!rateBar) {
  163. document.getElementById("menu-container").insertAdjacentHTML(
  164. "beforeend",
  165. `
  166. <div class="ryd-tooltip" style="width: ${widthPx}px">
  167. <div class="ryd-tooltip-bar-container">
  168. <div
  169. id="return-youtube-dislike-bar-container"
  170. style="width: 100%; height: 2px;"
  171. >
  172. <div
  173. id="return-youtube-dislike-bar"
  174. style="width: ${widthPercent}%; height: 100%"
  175. ></div>
  176. </div>
  177. </div>
  178. <tp-yt-paper-tooltip position="top" id="ryd-dislike-tooltip" class="style-scope ytd-sentiment-bar-renderer" role="tooltip" tabindex="-1">
  179. <!--css-build:shady-->${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}
  180. </tp-yt-paper-tooltip>
  181. </div>
  182. `
  183. );
  184. } else {
  185. document.getElementById(
  186. "return-youtube-dislike-bar-container"
  187. ).style.width = widthPx + "px";
  188. document.getElementById("return-youtube-dislike-bar").style.width =
  189. widthPercent + "%";
  190. document.querySelector(
  191. "#ryd-dislike-tooltip > #tooltip"
  192. ).innerHTML = `${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}`;
  193. }
  194. }
  195. function setState() {
  196. cLog("Fetching votes...");
  197. let statsSet = false;
  198. fetch(
  199. `https://returnyoutubedislikeapi.com/votes?videoId=${getVideoId()}`
  200. ).then((response) => {
  201. response.json().then((json) => {
  202. if (json && !("traceId" in response) && !statsSet) {
  203. const { dislikes, likes } = json;
  204. cLog(`Received count: ${dislikes}`);
  205. likesvalue = likes;
  206. dislikesvalue = dislikes;
  207. setDislikes(numberFormat(dislikes));
  208. createRateBar(likes, dislikes);
  209. }
  210. });
  211. });
  212. }
  213. function likeClicked() {
  214. if (checkForUserAvatarButton() == true) {
  215. if (previousState == 1) {
  216. likesvalue--;
  217. createRateBar(likesvalue, dislikesvalue);
  218. setDislikes(numberFormat(dislikesvalue));
  219. previousState = 3
  220. } else if (previousState == 2) {
  221. likesvalue++;
  222. dislikesvalue--;
  223. setDislikes(numberFormat(dislikesvalue))
  224. createRateBar(likesvalue, dislikesvalue);
  225. previousState = 1
  226. } else if (previousState == 3) {
  227. likesvalue++;
  228. createRateBar(likesvalue, dislikesvalue)
  229. previousState = 1
  230. }
  231. }
  232. }
  233. function dislikeClicked() {
  234. if (checkForUserAvatarButton() == true) {
  235. if (previousState == 3) {
  236. dislikesvalue++;
  237. setDislikes(numberFormat(dislikesvalue));
  238. createRateBar(likesvalue, dislikesvalue);
  239. previousState = 2
  240. } else if (previousState == 2) {
  241. dislikesvalue--;
  242. setDislikes(numberFormat(dislikesvalue));
  243. createRateBar(likesvalue, dislikesvalue);
  244. previousState = 3
  245. } else if (previousState == 1) {
  246. likesvalue--;
  247. dislikesvalue++;
  248. setDislikes(numberFormat(dislikesvalue));
  249. createRateBar(likesvalue, dislikesvalue);
  250. previousState = 2
  251. }
  252. }
  253. }
  254. function setInitialState() {
  255. setState();
  256. }
  257. function getVideoId() {
  258. const urlObject = new URL(window.location.href);
  259. const pathname = urlObject.pathname;
  260. if (pathname.startsWith("/clip")) {
  261. return document.querySelector("meta[itemprop='videoId']").content;
  262. } else {
  263. return urlObject.searchParams.get("v");
  264. }
  265. }
  266. function isVideoLoaded() {
  267. if (isMobile) {
  268. return document.getElementById("player").getAttribute("loading") == "false";
  269. }
  270. const videoId = getVideoId();
  271. return (
  272. document.querySelector(`ytd-watch-flexy[video-id='${videoId}']`) !== null
  273. );
  274. }
  275. function roundDown(num) {
  276. if (num < 1000) return num;
  277. const int = Math.floor(Math.log10(num) - 2);
  278. const decimal = int + (int % 3 ? 1 : 0);
  279. const value = Math.floor(num / 10 ** decimal);
  280. return value * 10 ** decimal;
  281. }
  282. function numberFormat(numberState) {
  283. let localeURL = Array.from(document.querySelectorAll("head > link[rel='search']"))
  284. ?.find((n) => n?.getAttribute("href")?.includes("?locale="))
  285. ?.getAttribute("href");
  286. const userLocales = localeURL ? new URL(localeURL)?.searchParams?.get("locale") : document.body.lang;
  287. const formatter = Intl.NumberFormat(
  288. document.documentElement.lang || userLocales || navigator.language,
  289. {
  290. notation: "compact",
  291. minimumFractionDigits: 1,
  292. maximumFractionDigits: 1,
  293. }
  294. );
  295. return formatter.format(roundDown(numberState)).replace(/\.0|,0/, "");
  296. }
  297. function getDislikesFromYoutubeResponse(htmlResponse) {
  298. let start =
  299. htmlResponse.indexOf('"videoDetails":') + '"videoDetails":'.length;
  300. let end =
  301. htmlResponse.indexOf('"isLiveContent":false}', start) +
  302. '"isLiveContent":false}'.length;
  303. if (end < start) {
  304. end =
  305. htmlResponse.indexOf('"isLiveContent":true}', start) +
  306. '"isLiveContent":true}'.length;
  307. }
  308. let jsonStr = htmlResponse.substring(start, end);
  309. let jsonResult = JSON.parse(jsonStr);
  310. let rating = jsonResult.averageRating;
  311. start = htmlResponse.indexOf('"topLevelButtons":[', end);
  312. start =
  313. htmlResponse.indexOf('"accessibilityData":', start) +
  314. '"accessibilityData":'.length;
  315. end = htmlResponse.indexOf("}", start);
  316. let likes = +htmlResponse.substring(start, end).replace(/\D/g, "");
  317. let dislikes = (likes * (5 - rating)) / (rating - 1);
  318. let result = {
  319. likes,
  320. dislikes: Math.round(dislikes),
  321. rating,
  322. viewCount: +jsonResult.viewCount,
  323. };
  324. return result;
  325. }
  326. function setEventListeners(evt) {
  327. let jsInitChecktimer;
  328. function checkForJS_Finish(check) {
  329. console.log();
  330. if (getButtons()?.offsetParent && isVideoLoaded()) {
  331. clearInterval(jsInitChecktimer);
  332. const buttons = getButtons();
  333. if (!window.returnDislikeButtonlistenersSet) {
  334. cLog("Registering button listeners...");
  335. buttons.children[0].addEventListener("click", likeClicked);
  336. buttons.children[1].addEventListener("click", dislikeClicked);
  337. window.returnDislikeButtonlistenersSet = true;
  338. }
  339. setInitialState();
  340. }
  341. }
  342. if (
  343. window.location.href.indexOf("watch?") >= 0 ||
  344. (isMobile && evt?.indexOf("watch?") >= 0)
  345. ) {
  346. cLog("Setting up...");
  347. jsInitChecktimer = setInterval(checkForJS_Finish, 111);
  348. }
  349. }
  350. (function () {
  351. "use strict";
  352. window.addEventListener("yt-navigate-finish", setEventListeners, true);
  353. setEventListeners();
  354. })();
  355. if (isMobile) {
  356. let originalPush = history.pushState;
  357. history.pushState = function (...args) {
  358. window.returnDislikeButtonlistenersSet = false;
  359. setEventListeners(args[2]);
  360. return originalPush.apply(history, args);
  361. };
  362. setInterval(() => {
  363. getDislikeButton().querySelector(".button-renderer-text").innerText =
  364. mobileDislikes;
  365. }, 1000);
  366. }