Return YouTube Dislike

Return of the YouTube Dislike, Based off https://www.returnyoutubedislike.com/

目前為 2021-12-01 提交的版本,檢視 最新版本

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