ryd.background.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. const apiUrl = "https://returnyoutubedislikeapi.com";
  2. const voteDisabledIconName = 'icon_hold128.png';
  3. const defaultIconName = 'icon128.png';
  4. let api;
  5. /** stores extension's global config */
  6. let extConfig = {
  7. disableVoteSubmission: false,
  8. // coloredThumbs: false,
  9. // coloredBar: false,
  10. numberDisplayFormat: 'compactShort', // compactShort, compactLong, standard
  11. numberDisplayRoundDown: true, // locale 'de' shows exact numbers by default
  12. };
  13. if (isChrome()) api = chrome;
  14. else if (isFirefox()) api = browser;
  15. initExtConfig()
  16. api.runtime.onMessage.addListener((request, sender, sendResponse) => {
  17. if (request.message === "get_auth_token") {
  18. chrome.identity.getAuthToken({ interactive: true }, function (token) {
  19. console.log(token);
  20. chrome.identity.getProfileUserInfo(function (userInfo) {
  21. console.log(JSON.stringify(userInfo));
  22. });
  23. });
  24. } else if (request.message === "log_off") {
  25. // chrome.identity.clearAllCachedAuthTokens(() => console.log("logged off"));
  26. } else if (request.message == "set_state") {
  27. // chrome.identity.getAuthToken({ interactive: true }, function (token) {
  28. let token = "";
  29. fetch(
  30. `${apiUrl}/votes?videoId=${request.videoId}&likeCount=${
  31. request.likeCount || ""
  32. }`,
  33. {
  34. method: "GET",
  35. headers: {
  36. Accept: "application/json",
  37. },
  38. }
  39. )
  40. .then((response) => response.json())
  41. .then((response) => {
  42. sendResponse(response);
  43. })
  44. .catch();
  45. return true;
  46. } else if (request.message == "send_links") {
  47. toSend = toSend.concat(request.videoIds.filter((x) => !sentIds.has(x)));
  48. if (toSend.length >= 20) {
  49. fetch(`${apiUrl}/votes`, {
  50. method: "POST",
  51. headers: {
  52. "Content-Type": "application/json",
  53. },
  54. body: JSON.stringify(toSend),
  55. });
  56. for (const toSendUrl of toSend) {
  57. sentIds.add(toSendUrl);
  58. }
  59. toSend = [];
  60. }
  61. } else if (request.message == "register") {
  62. register();
  63. return true;
  64. } else if (request.message == "send_vote") {
  65. sendVote(request.videoId, request.vote);
  66. return true;
  67. }
  68. });
  69. async function sendVote(videoId, vote) {
  70. api.storage.sync.get(null, async (storageResult) => {
  71. if (!storageResult.userId || !storageResult.registrationConfirmed) {
  72. await register();
  73. return;
  74. }
  75. fetch(`${apiUrl}/interact/vote`, {
  76. method: "POST",
  77. headers: {
  78. "Content-Type": "application/json",
  79. },
  80. body: JSON.stringify({
  81. userId: storageResult.userId,
  82. videoId,
  83. value: vote,
  84. }),
  85. })
  86. .then(async (response) => {
  87. if (response.status == 401) {
  88. await register();
  89. await sendVote(videoId, vote);
  90. return;
  91. }
  92. return response.json()
  93. })
  94. .then((response) => {
  95. solvePuzzle(response).then((solvedPuzzle) => {
  96. fetch(`${apiUrl}/interact/confirmVote`, {
  97. method: "POST",
  98. headers: {
  99. "Content-Type": "application/json",
  100. },
  101. body: JSON.stringify({
  102. ...solvedPuzzle,
  103. userId: storageResult.userId,
  104. videoId,
  105. }),
  106. });
  107. });
  108. });
  109. });
  110. }
  111. function register() {
  112. let userId = generateUserID();
  113. api.storage.sync.set({ userId });
  114. return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
  115. method: "GET",
  116. headers: {
  117. Accept: "application/json",
  118. },
  119. })
  120. .then((response) => response.json())
  121. .then((response) => {
  122. return solvePuzzle(response).then((solvedPuzzle) => {
  123. return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
  124. method: "POST",
  125. headers: {
  126. "Content-Type": "application/json",
  127. },
  128. body: JSON.stringify(solvedPuzzle),
  129. }).then((response) =>
  130. response.json().then((result) => {
  131. if (result === true) {
  132. return api.storage.sync.set({ registrationConfirmed: true });
  133. }
  134. })
  135. );
  136. });
  137. })
  138. .catch();
  139. }
  140. api.storage.sync.get(null, (res) => {
  141. if (!res || !res.userId || !res.registrationConfirmed) {
  142. register();
  143. }
  144. });
  145. const sentIds = new Set();
  146. let toSend = [];
  147. function sendUserSubmittedStatisticsToApi(statistics) {
  148. fetch(`${apiUrl}/votes/user-submitted`, {
  149. method: "POST",
  150. headers: {
  151. "Content-Type": "application/json",
  152. },
  153. body: JSON.stringify(statistics),
  154. });
  155. }
  156. function countLeadingZeroes(uInt8View, limit) {
  157. let zeroes = 0;
  158. let value = 0;
  159. for (let i = 0; i < uInt8View.length; i++) {
  160. value = uInt8View[i];
  161. if (value === 0) {
  162. zeroes += 8;
  163. } else {
  164. let count = 1;
  165. if (value >>> 4 === 0) {
  166. count += 4;
  167. value <<= 4;
  168. }
  169. if (value >>> 6 === 0) {
  170. count += 2;
  171. value <<= 2;
  172. }
  173. zeroes += count - (value >>> 7);
  174. break;
  175. }
  176. if (zeroes >= limit) {
  177. break;
  178. }
  179. }
  180. return zeroes;
  181. }
  182. async function solvePuzzle(puzzle) {
  183. let challenge = Uint8Array.from(atob(puzzle.challenge), (c) =>
  184. c.charCodeAt(0)
  185. );
  186. let buffer = new ArrayBuffer(20);
  187. let uInt8View = new Uint8Array(buffer);
  188. let uInt32View = new Uint32Array(buffer);
  189. let maxCount = Math.pow(2, puzzle.difficulty) * 5;
  190. for (let i = 4; i < 20; i++) {
  191. uInt8View[i] = challenge[i - 4];
  192. }
  193. for (let i = 0; i < maxCount; i++) {
  194. uInt32View[0] = i;
  195. let hash = await crypto.subtle.digest("SHA-512", buffer);
  196. let hashUint8 = new Uint8Array(hash);
  197. if (countLeadingZeroes(hashUint8) >= puzzle.difficulty) {
  198. return {
  199. solution: btoa(String.fromCharCode.apply(null, uInt8View.slice(0, 4))),
  200. };
  201. }
  202. }
  203. }
  204. function generateUserID(length = 36) {
  205. const charset =
  206. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  207. let result = "";
  208. if (crypto && crypto.getRandomValues) {
  209. const values = new Uint32Array(length);
  210. crypto.getRandomValues(values);
  211. for (let i = 0; i < length; i++) {
  212. result += charset[values[i] % charset.length];
  213. }
  214. return result;
  215. } else {
  216. for (let i = 0; i < length; i++) {
  217. result += charset[Math.floor(Math.random() * charset.length)];
  218. }
  219. return result;
  220. }
  221. }
  222. function storageChangeHandler(changes, area) {
  223. if (changes.disableVoteSubmission !== undefined) {
  224. handleDisableVoteSubmissionChangeEvent(changes.disableVoteSubmission.newValue);
  225. }
  226. if (changes.numberDisplayRoundDown !== undefined) {
  227. handleNumberDisplayRoundDownChangeEvent(
  228. changes.numberDisplayRoundDown.newValue
  229. );
  230. }
  231. if (changes.numberDisplayFormat !== undefined) {
  232. handleNumberDisplayFormatChangeEvent(changes.numberDisplayFormat.newValue);
  233. }
  234. }
  235. function handleDisableVoteSubmissionChangeEvent(value) {
  236. extConfig.disableVoteSubmission = value;
  237. if (value === true) {
  238. changeIcon(voteDisabledIconName);
  239. } else {
  240. changeIcon(defaultIconName);
  241. }
  242. }
  243. function handleNumberDisplayFormatChangeEvent(value) {
  244. extConfig.numberDisplayFormat = value;
  245. }
  246. function handleNumberDisplayRoundDownChangeEvent(value) {
  247. extConfig.numberDisplayRoundDown = value;
  248. }
  249. function changeIcon(iconName) {
  250. if (api.action !== undefined) api.action.setIcon({path: "/icons/" + iconName});
  251. else if (api.browserAction !== undefined) api.browserAction.setIcon({path: "/icons/" + iconName});
  252. else console.log('changing icon is not supported');
  253. }
  254. api.storage.onChanged.addListener(storageChangeHandler);
  255. function initExtConfig() {
  256. initializeDisableVoteSubmission();
  257. initializeNumberDisplayFormat();
  258. initializeNumberDisplayRoundDown();
  259. }
  260. function initializeDisableVoteSubmission() {
  261. api.storage.sync.get(['disableVoteSubmission'], (res) => {
  262. if (res.disableVoteSubmission === undefined) {
  263. api.storage.sync.set({disableVoteSubmission: false});
  264. }
  265. else {
  266. extConfig.disableVoteSubmission = res.disableVoteSubmission;
  267. if (res.disableVoteSubmission) changeIcon(voteDisabledIconName);
  268. }
  269. });
  270. }
  271. function initializeNumberDisplayRoundDown() {
  272. api.storage.sync.get(['numberDisplayRoundDown'], (res) => {
  273. if (res.numberDisplayRoundDown === undefined) {
  274. api.storage.sync.set({numberDisplayRoundDown: true});
  275. } else {
  276. extConfig.numberDisplayRoundDown = res.numberDisplayRoundDown;
  277. }
  278. });
  279. }
  280. function initializeNumberDisplayFormat() {
  281. api.storage.sync.get(['numberDisplayFormat'], (res) => {
  282. if (res.numberDisplayFormat === undefined) {
  283. api.storage.sync.set({ numberDisplayFormat: 'compactShort' });
  284. } else {
  285. extConfig.numberDisplayFormat = res.numberDisplayFormat;
  286. }
  287. });
  288. }
  289. function isChrome() {
  290. return typeof chrome !== "undefined" && typeof chrome.runtime !== "undefined";
  291. }
  292. function isFirefox() {
  293. return typeof browser !== "undefined" && typeof browser.runtime !== "undefined";
  294. }