Return Youtube Dislike.user.js 8.4 KB

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