Return YouTube Dislike

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

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

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