Return Youtube Dislike.user.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // ==UserScript==
  2. // @name Return YouTube Dislike
  3. // @namespace https://www.returnyoutubedislike.com/
  4. // @version 0.5
  5. // @description Return of the YouTube Dislike, Based off https://www.returnyoutubedislike.com/
  6. // @author Anarios & JRWR
  7. // @match *://*.youtube.com/watch*
  8. // @compatible chrome
  9. // @compatible firefox
  10. // @compatible opera
  11. // @compatible safari
  12. // @compatible edge
  13. // @downloadURL https://github.com/Anarios/return-youtube-dislike/raw/main/Extensions/UserScript/Return%20Youtube%20Dislike.user.js
  14. // @updateURL https://github.com/Anarios/return-youtube-dislike/raw/main/Extensions/UserScript/Return%20Youtube%20Dislike.user.js
  15. // @grant GM.xmlHttpRequest
  16. // ==/UserScript==
  17. function cLog(text, subtext = "") {
  18. subtext = subtext.trim() === "" ? "" : `(${subtext})`;
  19. console.log(`[Return Youtube Dislikes] ${text} ${subtext}`);
  20. }
  21. function doXHR(opts) {
  22. if (typeof GM_xmlhttpRequest === "function") {
  23. return GM_xmlhttpRequest(opts);
  24. }
  25. if (typeof GM !== "undefined") {
  26. /*This will prevent from throwing "Uncaught ReferenceError: GM is not defined"*/ if (
  27. typeof GM.xmlHttpRequest === "function"
  28. ) {
  29. return GM.xmlHttpRequest(opts);
  30. }
  31. }
  32. console.warn(
  33. "Unable to detect UserScript plugin, falling back to native XHR."
  34. );
  35. const xhr = new XMLHttpRequest();
  36. xhr.open(opts.method, opts.url, true);
  37. if (opts.responseType === "text") {
  38. xhr.onload = () =>
  39. opts.onload({
  40. response: xhr.responseText,
  41. });
  42. } else {
  43. xhr.onload = () =>
  44. opts.onload({
  45. response: JSON.parse(xhr.responseText),
  46. });
  47. }
  48. xhr.onerror = (err) => console.error("XHR Failed", err);
  49. xhr.send();
  50. }
  51. function getButtons() {
  52. if (document.getElementById("menu-container").offsetParent === null) {
  53. return document.querySelector("ytd-menu-renderer.ytd-watch-metadata > div");
  54. } else {
  55. return document
  56. .getElementById("menu-container")
  57. ?.querySelector("#top-level-buttons-computed");
  58. }
  59. }
  60. function getLikeButton() {
  61. return getButtons().children[0];
  62. }
  63. function getDislikeButton() {
  64. return getButtons().children[1];
  65. }
  66. function isVideoLiked() {
  67. return getLikeButton().classList.contains("style-default-active");
  68. }
  69. function isVideoDisliked() {
  70. return getDislikeButton().classList.contains("style-default-active");
  71. }
  72. function isVideoNotLiked() {
  73. return getLikeButton().classList.contains("style-text");
  74. }
  75. function isVideoNotDisliked() {
  76. return getDislikeButton().classList.contains("style-text");
  77. }
  78. function getState() {
  79. if (isVideoLiked()) {
  80. return "liked";
  81. }
  82. if (isVideoDisliked()) {
  83. return "disliked";
  84. }
  85. return "neutral";
  86. }
  87. function setLikes(likesCount) {
  88. getButtons().children[0].querySelector("#text").innerText = likesCount;
  89. }
  90. function setDislikes(dislikesCount) {
  91. getButtons().children[1].querySelector("#text").innerText = dislikesCount;
  92. }
  93. function createRateBar(likes, dislikes) {
  94. var rateBar = document.getElementById("return-youtube-dislike-bar-container");
  95. const widthPx =
  96. getButtons().children[0].clientWidth +
  97. getButtons().children[1].clientWidth +
  98. 8;
  99. const widthPercent =
  100. likes + dislikes > 0 ? (likes / (likes + dislikes)) * 100 : 50;
  101. if (!rateBar) {
  102. document.getElementById("menu-container").insertAdjacentHTML(
  103. "beforeend",
  104. `
  105. <div class="ryd-tooltip" style="width: ${widthPx}px">
  106. <div class="ryd-tooltip-bar-container">
  107. <div
  108. id="return-youtube-dislike-bar-container"
  109. style="width: 100%; height: 2px;"
  110. >
  111. <div
  112. id="return-youtube-dislike-bar"
  113. style="width: ${widthPercent}%; height: 100%"
  114. ></div>
  115. </div>
  116. </div>
  117. <tp-yt-paper-tooltip position="top" id="ryd-dislike-tooltip" class="style-scope ytd-sentiment-bar-renderer" role="tooltip" tabindex="-1">
  118. <!--css-build:shady-->${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}
  119. </tp-yt-paper-tooltip>
  120. </div>
  121. `
  122. );
  123. } else {
  124. document.getElementById(
  125. "return-youtube-dislike-bar-container"
  126. ).style.width = widthPx + "px";
  127. document.getElementById("return-youtube-dislike-bar").style.width =
  128. widthPercent + "%";
  129. document.querySelector(
  130. "#ryd-dislike-tooltip > #tooltip"
  131. ).innerHTML = `${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}`;
  132. }
  133. }
  134. function setState() {
  135. cLog("Fetching votes...");
  136. let statsSet = false;
  137. doXHR({
  138. method: "GET",
  139. responseType: "text",
  140. url: `https://www.youtube.com/watch?v=${getVideoId()}`,
  141. onload: function (xhr) {
  142. if (xhr) {
  143. let result = getDislikesFromYoutubeResponse(xhr.response);
  144. if (result) {
  145. cLog("response from youtube:");
  146. cLog(JSON.stringify(result));
  147. if (result.likes || result.dislikes) {
  148. const formattedDislike = numberFormat(result.dislikes);
  149. setDislikes(formattedDislike);
  150. createRateBar(result.likes, result.dislikes);
  151. statsSet = true;
  152. }
  153. }
  154. }
  155. },
  156. });
  157. doXHR({
  158. method: "GET",
  159. responseType: "json",
  160. url:
  161. "https://return-youtube-dislike-api.azurewebsites.net/votes?videoId=" +
  162. getVideoId(),
  163. onload: function (xhr) {
  164. if (xhr != undefined && !statsSet) {
  165. const { dislikes, likes } = xhr.response;
  166. cLog(`Received count: ${dislikes}`);
  167. setDislikes(numberFormat(dislikes));
  168. createRateBar(likes, dislikes);
  169. }
  170. },
  171. });
  172. }
  173. function likeClicked() {
  174. cLog("Like clicked", getState());
  175. setState();
  176. }
  177. function dislikeClicked() {
  178. cLog("Dislike clicked", getState());
  179. setState();
  180. }
  181. function setInitalState() {
  182. setState();
  183. }
  184. function getVideoId() {
  185. const urlParams = new URLSearchParams(window.location.search);
  186. const videoId = urlParams.get("v");
  187. return videoId;
  188. }
  189. function isVideoLoaded() {
  190. const videoId = getVideoId();
  191. return (
  192. document.querySelector(`ytd-watch-flexy[video-id='${videoId}']`) !== null
  193. );
  194. }
  195. function roundDown(num) {
  196. if (num < 1000) return num;
  197. const int = Math.floor(Math.log10(num) - 2);
  198. const decimal = int + (int % 3 ? 1 : 0);
  199. const value = Math.floor(num / 10 ** decimal);
  200. return value * 10 ** decimal;
  201. }
  202. function numberFormat(numberState) {
  203. const userLocales = navigator.language;
  204. const formatter = Intl.NumberFormat(userLocales, {
  205. notation: "compact",
  206. minimumFractionDigits: 1,
  207. maximumFractionDigits: 1,
  208. });
  209. return formatter.format(roundDown(numberState)).replace(/\.0|,0/, "");
  210. }
  211. function getDislikesFromYoutubeResponse(htmlResponse) {
  212. let start =
  213. htmlResponse.indexOf('"videoDetails":') + '"videoDetails":'.length;
  214. let end =
  215. htmlResponse.indexOf('"isLiveContent":false}', start) +
  216. '"isLiveContent":false}'.length;
  217. if (end < start) {
  218. end =
  219. htmlResponse.indexOf('"isLiveContent":true}', start) +
  220. '"isLiveContent":true}'.length;
  221. }
  222. let jsonStr = htmlResponse.substring(start, end);
  223. let jsonResult = JSON.parse(jsonStr);
  224. let rating = jsonResult.averageRating;
  225. start = htmlResponse.indexOf('"topLevelButtons":[', end);
  226. start =
  227. htmlResponse.indexOf('"accessibilityData":', start) +
  228. '"accessibilityData":'.length;
  229. end = htmlResponse.indexOf("}", start);
  230. let likes = +htmlResponse.substring(start, end).replace(/\D/g, "");
  231. let dislikes = (likes * (5 - rating)) / (rating - 1);
  232. let result = {
  233. likes,
  234. dislikes: Math.round(dislikes),
  235. rating,
  236. viewCount: +jsonResult.viewCount,
  237. };
  238. return result;
  239. }
  240. function setEventListeners(evt) {
  241. function checkForJS_Finish() {
  242. if (getButtons()?.offsetParent && isVideoLoaded()) {
  243. clearInterval(jsInitChecktimer);
  244. const buttons = getButtons();
  245. if (!window.returnDislikeButtonlistenersSet) {
  246. cLog("Registering button listeners...");
  247. buttons.children[0].addEventListener("click", likeClicked);
  248. buttons.children[1].addEventListener("click", dislikeClicked);
  249. window.returnDislikeButtonlistenersSet = true;
  250. }
  251. setInitalState();
  252. }
  253. }
  254. if (window.location.href.indexOf("watch?") >= 0) {
  255. cLog("Setting up...");
  256. var jsInitChecktimer = setInterval(checkForJS_Finish, 111);
  257. }
  258. }
  259. (function () {
  260. "use strict";
  261. window.addEventListener("yt-navigate-finish", setEventListeners, true);
  262. setEventListeners();
  263. })();