ryd.background.js 8.8 KB

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