ryd.background.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. const apiUrl = "https://returnyoutubedislikeapi.com";
  2. let api;
  3. if (typeof chrome !== "undefined" && typeof chrome.runtime !== "undefined")
  4. api = chrome;
  5. else if (
  6. typeof browser !== "undefined" &&
  7. typeof browser.runtime !== "undefined"
  8. )
  9. api = browser;
  10. api.runtime.onMessage.addListener((request, sender, sendResponse) => {
  11. if (request.message === "get_auth_token") {
  12. // chrome.identity.getAuthToken({ interactive: true }, function (token) {
  13. // console.log(token);
  14. // chrome.identity.getProfileUserInfo(function (userInfo) {
  15. // console.log(JSON.stringify(userInfo));
  16. // });
  17. // });
  18. } else if (request.message === "log_off") {
  19. // chrome.identity.clearAllCachedAuthTokens(() => console.log("logged off"));
  20. } else if (request.message == "set_state") {
  21. // chrome.identity.getAuthToken({ interactive: true }, function (token) {
  22. let token = "";
  23. fetch(`${apiUrl}/votes?videoId=${request.videoId}&likeCount=${request.likeCount || ''}`, {
  24. method: "GET",
  25. headers: {
  26. Accept: "application/json",
  27. },
  28. })
  29. .then((response) => response.json())
  30. .then((response) => {
  31. sendResponse(response);
  32. })
  33. .catch();
  34. return true;
  35. } else if (request.message == "send_links") {
  36. toSend = toSend.concat(request.videoIds.filter((x) => !sentIds.has(x)));
  37. if (toSend.length >= 20) {
  38. fetch(`${apiUrl}/votes`, {
  39. method: "POST",
  40. headers: {
  41. "Content-Type": "application/json",
  42. },
  43. body: JSON.stringify(toSend),
  44. });
  45. for (const toSendUrl of toSend) {
  46. sentIds.add(toSendUrl);
  47. }
  48. toSend = [];
  49. }
  50. } else if (request.message == "fetch_from_youtube") {
  51. fetch(`https://www.youtube.com/watch?v=${request.videoId}`, {
  52. method: "GET",
  53. })
  54. .then((response) => response.text())
  55. .then((text) => {
  56. let result = getDislikesFromYoutubeResponse(text);
  57. sendUserSubmittedStatisticsToApi({
  58. ...result,
  59. videoId: request.videoId,
  60. });
  61. sendResponse(result);
  62. });
  63. return true;
  64. } else if (request.message == "register") {
  65. register();
  66. return true;
  67. } else if (request.message == "send_vote") {
  68. sendVote(request.videoId, request.vote);
  69. return true;
  70. }
  71. });
  72. async function sendVote(videoId, vote) {
  73. api.storage.sync.get(null, async (storageResult) => {
  74. if (!storageResult.userId || !storageResult.registrationConfirmed) {
  75. register().then(() => sendVote(videoId, vote));
  76. }
  77. fetch(`${apiUrl}/interact/vote`, {
  78. method: "POST",
  79. headers: {
  80. "Content-Type": "application/json",
  81. },
  82. body: JSON.stringify({
  83. userId: storageResult.userId,
  84. videoId,
  85. value: vote,
  86. }),
  87. })
  88. .then((response) => response.json())
  89. .then((response) => {
  90. solvePuzzle(response).then((solvedPuzzle) => {
  91. fetch(`${apiUrl}/interact/confirmVote`, {
  92. method: "POST",
  93. headers: {
  94. "Content-Type": "application/json",
  95. },
  96. body: JSON.stringify({
  97. ...solvedPuzzle,
  98. userId: storageResult.userId,
  99. videoId,
  100. }),
  101. });
  102. });
  103. });
  104. });
  105. }
  106. function register() {
  107. let userId = generateUserID();
  108. api.storage.sync.set({ userId });
  109. return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
  110. method: "GET",
  111. headers: {
  112. Accept: "application/json",
  113. },
  114. })
  115. .then((response) => response.json())
  116. .then((response) => {
  117. return solvePuzzle(response).then((solvedPuzzle) => {
  118. return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
  119. method: "POST",
  120. headers: {
  121. "Content-Type": "application/json",
  122. },
  123. body: JSON.stringify(solvedPuzzle),
  124. }).then((response) =>
  125. response.json().then((result) => {
  126. if (result === true) {
  127. return api.storage.sync.set({ registrationConfirmed: true });
  128. }
  129. })
  130. );
  131. });
  132. })
  133. .catch();
  134. }
  135. api.storage.sync.get(null, (res) => {
  136. if (!res.userId || !res.registrationConfirmed) {
  137. register();
  138. }
  139. });
  140. const sentIds = new Set();
  141. let toSend = [];
  142. function getDislikesFromYoutubeResponse(htmlResponse) {
  143. let start =
  144. htmlResponse.indexOf('"videoDetails":') + '"videoDetails":'.length;
  145. let end =
  146. htmlResponse.indexOf('"isLiveContent":false}', start) +
  147. '"isLiveContent":false}'.length;
  148. if (end < start) {
  149. end =
  150. htmlResponse.indexOf('"isLiveContent":true}', start) +
  151. '"isLiveContent":true}'.length;
  152. }
  153. let jsonStr = htmlResponse.substring(start, end);
  154. let jsonResult = JSON.parse(jsonStr);
  155. let rating = jsonResult.averageRating;
  156. start = htmlResponse.indexOf('"topLevelButtons":[', end);
  157. start =
  158. htmlResponse.indexOf('"accessibilityData":', start) +
  159. '"accessibilityData":'.length;
  160. end = htmlResponse.indexOf("}", start);
  161. let likes = +htmlResponse.substring(start, end).replace(/\D/g, "");
  162. let dislikes = (likes * (5 - rating)) / (rating - 1);
  163. let result = {
  164. likes,
  165. dislikes: Math.abs(Math.round(dislikes)),
  166. rating,
  167. viewCount: +jsonResult.viewCount,
  168. };
  169. return result;
  170. }
  171. function sendUserSubmittedStatisticsToApi(statistics) {
  172. fetch(`${apiUrl}/votes/user-submitted`, {
  173. method: "POST",
  174. headers: {
  175. "Content-Type": "application/json",
  176. },
  177. body: JSON.stringify(statistics),
  178. });
  179. }
  180. function countLeadingZeroes(uInt8View, limit) {
  181. let zeroes = 0;
  182. let value = 0;
  183. for (let i = 0; i < uInt8View.length; i++) {
  184. value = uInt8View[i];
  185. if (value === 0) {
  186. zeroes += 8;
  187. } else {
  188. let count = 1;
  189. if (value >>> 4 === 0) {
  190. count += 4;
  191. value <<= 4;
  192. }
  193. if (value >>> 6 === 0) {
  194. count += 2;
  195. value <<= 2;
  196. }
  197. zeroes += count - (value >>> 7);
  198. break;
  199. }
  200. if (zeroes >= limit) {
  201. break;
  202. }
  203. }
  204. return zeroes;
  205. }
  206. async function solvePuzzle(puzzle) {
  207. let challenge = Uint8Array.from(atob(puzzle.challenge), (c) =>
  208. c.charCodeAt(0)
  209. );
  210. let buffer = new ArrayBuffer(20);
  211. let uInt8View = new Uint8Array(buffer);
  212. let uInt32View = new Uint32Array(buffer);
  213. let maxCount = Math.pow(2, puzzle.difficulty) * 5;
  214. for (let i = 4; i < 20; i++) {
  215. uInt8View[i] = challenge[i - 4];
  216. }
  217. for (let i = 0; i < maxCount; i++) {
  218. uInt32View[0] = i;
  219. let hash = await crypto.subtle.digest("SHA-512", buffer);
  220. let hashUint8 = new Uint8Array(hash);
  221. if (countLeadingZeroes(hashUint8) >= puzzle.difficulty) {
  222. return {
  223. solution: btoa(String.fromCharCode.apply(null, uInt8View.slice(0, 4))),
  224. };
  225. }
  226. }
  227. }
  228. function generateUserID(length = 36) {
  229. const charset =
  230. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  231. let result = "";
  232. if (crypto && crypto.getRandomValues) {
  233. const values = new Uint32Array(length);
  234. crypto.getRandomValues(values);
  235. for (let i = 0; i < length; i++) {
  236. result += charset[values[i] % charset.length];
  237. }
  238. return result;
  239. } else {
  240. for (let i = 0; i < length; i++) {
  241. result += charset[Math.floor(Math.random() * charset.length)];
  242. }
  243. return result;
  244. }
  245. }