Return Youtube Dislike.user.js 8.3 KB

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