ryd.background.js 10 KB

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