ryd.background.js 10 KB

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