ryd.background.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 == "register") {
  51. register();
  52. return true;
  53. } else if (request.message == "send_vote") {
  54. sendVote(request.videoId, request.vote);
  55. return true;
  56. }
  57. });
  58. async function sendVote(videoId, vote) {
  59. api.storage.sync.get(null, async (storageResult) => {
  60. if (!storageResult.userId || !storageResult.registrationConfirmed) {
  61. register().then(() => sendVote(videoId, vote));
  62. }
  63. fetch(`${apiUrl}/interact/vote`, {
  64. method: "POST",
  65. headers: {
  66. "Content-Type": "application/json",
  67. },
  68. body: JSON.stringify({
  69. userId: storageResult.userId,
  70. videoId,
  71. value: vote,
  72. }),
  73. })
  74. .then((response) => response.json())
  75. .then((response) => {
  76. solvePuzzle(response).then((solvedPuzzle) => {
  77. fetch(`${apiUrl}/interact/confirmVote`, {
  78. method: "POST",
  79. headers: {
  80. "Content-Type": "application/json",
  81. },
  82. body: JSON.stringify({
  83. ...solvedPuzzle,
  84. userId: storageResult.userId,
  85. videoId,
  86. }),
  87. });
  88. });
  89. });
  90. });
  91. }
  92. function register() {
  93. let userId = generateUserID();
  94. api.storage.sync.set({ userId });
  95. return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
  96. method: "GET",
  97. headers: {
  98. Accept: "application/json",
  99. },
  100. })
  101. .then((response) => response.json())
  102. .then((response) => {
  103. return solvePuzzle(response).then((solvedPuzzle) => {
  104. return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
  105. method: "POST",
  106. headers: {
  107. "Content-Type": "application/json",
  108. },
  109. body: JSON.stringify(solvedPuzzle),
  110. }).then((response) =>
  111. response.json().then((result) => {
  112. if (result === true) {
  113. return api.storage.sync.set({ registrationConfirmed: true });
  114. }
  115. })
  116. );
  117. });
  118. })
  119. .catch();
  120. }
  121. api.storage.sync.get(null, (res) => {
  122. if (!res.userId || !res.registrationConfirmed) {
  123. register();
  124. }
  125. });
  126. const sentIds = new Set();
  127. let toSend = [];
  128. function getDislikesFromYoutubeResponse(htmlResponse) {
  129. let start =
  130. htmlResponse.indexOf('"videoDetails":') + '"videoDetails":'.length;
  131. let end =
  132. htmlResponse.indexOf('"isLiveContent":false}', start) +
  133. '"isLiveContent":false}'.length;
  134. if (end < start) {
  135. end =
  136. htmlResponse.indexOf('"isLiveContent":true}', start) +
  137. '"isLiveContent":true}'.length;
  138. }
  139. let jsonStr = htmlResponse.substring(start, end);
  140. let jsonResult = JSON.parse(jsonStr);
  141. let rating = jsonResult.averageRating;
  142. start = htmlResponse.indexOf('"topLevelButtons":[', end);
  143. start =
  144. htmlResponse.indexOf('"accessibilityData":', start) +
  145. '"accessibilityData":'.length;
  146. end = htmlResponse.indexOf("}", start);
  147. let likes = +htmlResponse.substring(start, end).replace(/\D/g, "");
  148. let dislikes = (likes * (5 - rating)) / (rating - 1);
  149. let result = {
  150. likes,
  151. dislikes: Math.abs(Math.round(dislikes)),
  152. rating,
  153. viewCount: +jsonResult.viewCount,
  154. };
  155. return result;
  156. }
  157. function sendUserSubmittedStatisticsToApi(statistics) {
  158. fetch(`${apiUrl}/votes/user-submitted`, {
  159. method: "POST",
  160. headers: {
  161. "Content-Type": "application/json",
  162. },
  163. body: JSON.stringify(statistics),
  164. });
  165. }
  166. function countLeadingZeroes(uInt8View, limit) {
  167. let zeroes = 0;
  168. let value = 0;
  169. for (let i = 0; i < uInt8View.length; i++) {
  170. value = uInt8View[i];
  171. if (value === 0) {
  172. zeroes += 8;
  173. } else {
  174. let count = 1;
  175. if (value >>> 4 === 0) {
  176. count += 4;
  177. value <<= 4;
  178. }
  179. if (value >>> 6 === 0) {
  180. count += 2;
  181. value <<= 2;
  182. }
  183. zeroes += count - (value >>> 7);
  184. break;
  185. }
  186. if (zeroes >= limit) {
  187. break;
  188. }
  189. }
  190. return zeroes;
  191. }
  192. async function solvePuzzle(puzzle) {
  193. let challenge = Uint8Array.from(atob(puzzle.challenge), (c) =>
  194. c.charCodeAt(0)
  195. );
  196. let buffer = new ArrayBuffer(20);
  197. let uInt8View = new Uint8Array(buffer);
  198. let uInt32View = new Uint32Array(buffer);
  199. let maxCount = Math.pow(2, puzzle.difficulty) * 5;
  200. for (let i = 4; i < 20; i++) {
  201. uInt8View[i] = challenge[i - 4];
  202. }
  203. for (let i = 0; i < maxCount; i++) {
  204. uInt32View[0] = i;
  205. let hash = await crypto.subtle.digest("SHA-512", buffer);
  206. let hashUint8 = new Uint8Array(hash);
  207. if (countLeadingZeroes(hashUint8) >= puzzle.difficulty) {
  208. return {
  209. solution: btoa(String.fromCharCode.apply(null, uInt8View.slice(0, 4))),
  210. };
  211. }
  212. }
  213. }
  214. function generateUserID(length = 36) {
  215. const charset =
  216. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  217. let result = "";
  218. if (crypto && crypto.getRandomValues) {
  219. const values = new Uint32Array(length);
  220. crypto.getRandomValues(values);
  221. for (let i = 0; i < length; i++) {
  222. result += charset[values[i] % charset.length];
  223. }
  224. return result;
  225. } else {
  226. for (let i = 0; i < length; i++) {
  227. result += charset[Math.floor(Math.random() * charset.length)];
  228. }
  229. return result;
  230. }
  231. }