ryd.background.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. numberDisplayFormat: "compactShort", // compactShort, compactLong, standard
  12. numberDisplayRoundDown: true, // locale 'de' shows exact numbers by default
  13. numberDisplayReformatLikes: false, // use existing (native) likes number
  14. };
  15. if (isChrome()) api = chrome;
  16. else if (isFirefox()) api = browser;
  17. initExtConfig();
  18. api.runtime.onMessage.addListener((request, sender, sendResponse) => {
  19. if (request.message === "get_auth_token") {
  20. chrome.identity.getAuthToken({ interactive: true }, function (token) {
  21. console.log(token);
  22. chrome.identity.getProfileUserInfo(function (userInfo) {
  23. console.log(JSON.stringify(userInfo));
  24. });
  25. });
  26. } else if (request.message === "log_off") {
  27. // chrome.identity.clearAllCachedAuthTokens(() => console.log("logged off"));
  28. } else if (request.message == "set_state") {
  29. // chrome.identity.getAuthToken({ interactive: true }, function (token) {
  30. let token = "";
  31. fetch(
  32. `${apiUrl}/votes?videoId=${request.videoId}&likeCount=${
  33. request.likeCount || ""
  34. }`,
  35. {
  36. method: "GET",
  37. headers: {
  38. Accept: "application/json",
  39. },
  40. }
  41. )
  42. .then((response) => response.json())
  43. .then((response) => {
  44. sendResponse(response);
  45. })
  46. .catch();
  47. return true;
  48. } else if (request.message == "send_links") {
  49. toSend = toSend.concat(request.videoIds.filter((x) => !sentIds.has(x)));
  50. if (toSend.length >= 20) {
  51. fetch(`${apiUrl}/votes`, {
  52. method: "POST",
  53. headers: {
  54. "Content-Type": "application/json",
  55. },
  56. body: JSON.stringify(toSend),
  57. });
  58. for (const toSendUrl of toSend) {
  59. sentIds.add(toSendUrl);
  60. }
  61. toSend = [];
  62. }
  63. } else if (request.message == "register") {
  64. register();
  65. return true;
  66. } else if (request.message == "send_vote") {
  67. sendVote(request.videoId, request.vote);
  68. return true;
  69. }
  70. });
  71. api.runtime.onInstalled.addListener((details) => {
  72. if (
  73. // No need to show changelog if its was a browser update (and not extension update)
  74. details.reason === "browser_update" ||
  75. // Chromium (e.g., Google Chrome Cannary) uses this name instead of the one above for some reason
  76. details.reason === "chrome_update" ||
  77. // No need to show changelog if developer just reloaded the extension
  78. details.reason === "update"
  79. )
  80. return;
  81. api.tabs.create({
  82. url: api.runtime.getURL("/changelog/3/changelog_3.0.html"),
  83. });
  84. });
  85. // api.storage.sync.get(['lastShowChangelogVersion'], (details) => {
  86. // if (extConfig.showUpdatePopup === true &&
  87. // details.lastShowChangelogVersion !== chrome.runtime.getManifest().version
  88. // ) {
  89. // // keep it inside get to avoid race condition
  90. // api.storage.sync.set({'lastShowChangelogVersion ': chrome.runtime.getManifest().version});
  91. // // wait until async get runs & don't steal tab focus
  92. // api.tabs.create({url: api.runtime.getURL("/changelog/3/changelog_3.0.html"), active: false});
  93. // }
  94. // });
  95. async function sendVote(videoId, vote) {
  96. api.storage.sync.get(null, async (storageResult) => {
  97. if (!storageResult.userId || !storageResult.registrationConfirmed) {
  98. await register();
  99. }
  100. let voteResponse = await fetch(`${apiUrl}/interact/vote`, {
  101. method: "POST",
  102. headers: {
  103. "Content-Type": "application/json",
  104. },
  105. body: JSON.stringify({
  106. userId: storageResult.userId,
  107. videoId,
  108. value: vote,
  109. }),
  110. });
  111. if (voteResponse.status == 401) {
  112. await register();
  113. await sendVote(videoId, vote);
  114. return;
  115. }
  116. const voteResponseJson = await voteResponse.json();
  117. const solvedPuzzle = await solvePuzzle(voteResponseJson);
  118. if (!solvedPuzzle.solution) {
  119. await sendVote(videoId, vote);
  120. return;
  121. }
  122. await fetch(`${apiUrl}/interact/confirmVote`, {
  123. method: "POST",
  124. headers: {
  125. "Content-Type": "application/json",
  126. },
  127. body: JSON.stringify({
  128. ...solvedPuzzle,
  129. userId: storageResult.userId,
  130. videoId,
  131. }),
  132. });
  133. });
  134. }
  135. async function register() {
  136. const userId = generateUserID();
  137. api.storage.sync.set({ userId });
  138. const registrationResponse = await fetch(
  139. `${apiUrl}/puzzle/registration?userId=${userId}`,
  140. {
  141. method: "GET",
  142. headers: {
  143. Accept: "application/json",
  144. },
  145. }
  146. ).then((response) => response.json());
  147. const solvedPuzzle = await solvePuzzle(registrationResponse);
  148. if (!solvedPuzzle.solution) {
  149. await register();
  150. return;
  151. }
  152. const result = await fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
  153. method: "POST",
  154. headers: {
  155. "Content-Type": "application/json",
  156. },
  157. body: JSON.stringify(solvedPuzzle),
  158. }).then((response) => response.json());
  159. if (result === true) {
  160. return api.storage.sync.set({ registrationConfirmed: true });
  161. }
  162. }
  163. api.storage.sync.get(null, async (res) => {
  164. if (!res || !res.userId || !res.registrationConfirmed) {
  165. await register();
  166. }
  167. });
  168. const sentIds = new Set();
  169. let toSend = [];
  170. function countLeadingZeroes(uInt8View, limit) {
  171. let zeroes = 0;
  172. let value = 0;
  173. for (let i = 0; i < uInt8View.length; i++) {
  174. value = uInt8View[i];
  175. if (value === 0) {
  176. zeroes += 8;
  177. } else {
  178. let count = 1;
  179. if (value >>> 4 === 0) {
  180. count += 4;
  181. value <<= 4;
  182. }
  183. if (value >>> 6 === 0) {
  184. count += 2;
  185. value <<= 2;
  186. }
  187. zeroes += count - (value >>> 7);
  188. break;
  189. }
  190. if (zeroes >= limit) {
  191. break;
  192. }
  193. }
  194. return zeroes;
  195. }
  196. async function solvePuzzle(puzzle) {
  197. let challenge = Uint8Array.from(atob(puzzle.challenge), (c) =>
  198. c.charCodeAt(0)
  199. );
  200. let buffer = new ArrayBuffer(20);
  201. let uInt8View = new Uint8Array(buffer);
  202. let uInt32View = new Uint32Array(buffer);
  203. let maxCount = Math.pow(2, puzzle.difficulty) * 3;
  204. for (let i = 4; i < 20; i++) {
  205. uInt8View[i] = challenge[i - 4];
  206. }
  207. for (let i = 0; i < maxCount; i++) {
  208. uInt32View[0] = i;
  209. let hash = await crypto.subtle.digest("SHA-512", buffer);
  210. let hashUint8 = new Uint8Array(hash);
  211. if (countLeadingZeroes(hashUint8) >= puzzle.difficulty) {
  212. return {
  213. solution: btoa(String.fromCharCode.apply(null, uInt8View.slice(0, 4))),
  214. };
  215. }
  216. }
  217. return {};
  218. }
  219. function generateUserID(length = 36) {
  220. const charset =
  221. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  222. let result = "";
  223. if (crypto && crypto.getRandomValues) {
  224. const values = new Uint32Array(length);
  225. crypto.getRandomValues(values);
  226. for (let i = 0; i < length; i++) {
  227. result += charset[values[i] % charset.length];
  228. }
  229. return result;
  230. } else {
  231. for (let i = 0; i < length; i++) {
  232. result += charset[Math.floor(Math.random() * charset.length)];
  233. }
  234. return result;
  235. }
  236. }
  237. function storageChangeHandler(changes, area) {
  238. if (changes.disableVoteSubmission !== undefined) {
  239. handleDisableVoteSubmissionChangeEvent(
  240. changes.disableVoteSubmission.newValue
  241. );
  242. }
  243. if (changes.coloredThumbs !== undefined) {
  244. handleColoredThumbsChangeEvent(changes.coloredThumbs.newValue);
  245. }
  246. if (changes.coloredBar !== undefined) {
  247. handleColoredBarChangeEvent(changes.coloredBar.newValue);
  248. }
  249. if (changes.colorTheme !== undefined) {
  250. handleColorThemeChangeEvent(changes.colorTheme.newValue);
  251. }
  252. if (changes.numberDisplayRoundDown !== undefined) {
  253. handleNumberDisplayRoundDownChangeEvent(
  254. changes.numberDisplayRoundDown.newValue
  255. );
  256. }
  257. if (changes.numberDisplayFormat !== undefined) {
  258. handleNumberDisplayFormatChangeEvent(changes.numberDisplayFormat.newValue);
  259. }
  260. if (changes.numberDisplayReformatLikes !== undefined) {
  261. handleNumberDisplayReformatLikesChangeEvent(
  262. changes.numberDisplayReformatLikes.newValue
  263. );
  264. }
  265. if (changes.showTooltipPercentage !== undefined) {
  266. handleShowTooltipPercentageChangeEvent(
  267. changes.showTooltipPercentage.newValue
  268. );
  269. }
  270. if (changes.numberDisplayReformatLikes !== undefined) {
  271. handleNumberDisplayReformatLikesChangeEvent(
  272. changes.numberDisplayReformatLikes.newValue
  273. );
  274. }
  275. }
  276. function handleDisableVoteSubmissionChangeEvent(value) {
  277. extConfig.disableVoteSubmission = value;
  278. if (value === true) {
  279. changeIcon(voteDisabledIconName);
  280. } else {
  281. changeIcon(defaultIconName);
  282. }
  283. }
  284. function handleNumberDisplayFormatChangeEvent(value) {
  285. extConfig.numberDisplayFormat = value;
  286. }
  287. function handleShowTooltipPercentageChangeEvent(value) {
  288. extConfig.showTooltipPercentage = value;
  289. }
  290. function handleTooltipPercentageModeChangeEvent(value) {
  291. if (!value) {
  292. value = "dash_like";
  293. }
  294. extConfig.tooltipPercentageMode = value;
  295. }
  296. function handleNumberDisplayRoundDownChangeEvent(value) {
  297. extConfig.numberDisplayRoundDown = value;
  298. }
  299. function changeIcon(iconName) {
  300. if (api.action !== undefined)
  301. api.action.setIcon({ path: "/icons/" + iconName });
  302. else if (api.browserAction !== undefined)
  303. api.browserAction.setIcon({ path: "/icons/" + iconName });
  304. else console.log("changing icon is not supported");
  305. }
  306. function handleColoredThumbsChangeEvent(value) {
  307. extConfig.coloredThumbs = value;
  308. }
  309. function handleColoredBarChangeEvent(value) {
  310. extConfig.coloredBar = value;
  311. }
  312. function handleColorThemeChangeEvent(value) {
  313. if (!value) {
  314. value = "classic";
  315. }
  316. extConfig.colorTheme = value;
  317. }
  318. function handleNumberDisplayReformatLikesChangeEvent(value) {
  319. extConfig.numberDisplayReformatLikes = value;
  320. }
  321. api.storage.onChanged.addListener(storageChangeHandler);
  322. function initExtConfig() {
  323. initializeDisableVoteSubmission();
  324. initializeColoredThumbs();
  325. initializeColoredBar();
  326. initializeColorTheme();
  327. initializeNumberDisplayFormat();
  328. initializeNumberDisplayRoundDown();
  329. initializeNumberDisplayReformatLikes();
  330. initializeTooltipPercentage();
  331. initializeTooltipPercentageMode();
  332. }
  333. function initializeDisableVoteSubmission() {
  334. api.storage.sync.get(["disableVoteSubmission"], (res) => {
  335. if (res.disableVoteSubmission === undefined) {
  336. api.storage.sync.set({ disableVoteSubmission: false });
  337. } else {
  338. extConfig.disableVoteSubmission = res.disableVoteSubmission;
  339. if (res.disableVoteSubmission) changeIcon(voteDisabledIconName);
  340. }
  341. });
  342. }
  343. function initializeColoredThumbs() {
  344. api.storage.sync.get(["coloredThumbs"], (res) => {
  345. if (res.coloredThumbs === undefined) {
  346. api.storage.sync.set({ coloredThumbs: false });
  347. } else {
  348. extConfig.coloredThumbs = res.coloredThumbs;
  349. }
  350. });
  351. }
  352. function initializeNumberDisplayRoundDown() {
  353. api.storage.sync.get(["numberDisplayRoundDown"], (res) => {
  354. if (res.numberDisplayRoundDown === undefined) {
  355. api.storage.sync.set({ numberDisplayRoundDown: true });
  356. } else {
  357. extConfig.numberDisplayRoundDown = res.numberDisplayRoundDown;
  358. }
  359. });
  360. }
  361. function initializeColoredBar() {
  362. api.storage.sync.get(["coloredBar"], (res) => {
  363. if (res.coloredBar === undefined) {
  364. api.storage.sync.set({ coloredBar: false });
  365. } else {
  366. extConfig.coloredBar = res.coloredBar;
  367. }
  368. });
  369. }
  370. function initializeColorTheme() {
  371. api.storage.sync.get(["colorTheme"], (res) => {
  372. if (res.colorTheme === undefined) {
  373. api.storage.sync.set({ colorTheme: false });
  374. } else {
  375. extConfig.colorTheme = res.colorTheme;
  376. }
  377. });
  378. }
  379. function initializeNumberDisplayFormat() {
  380. api.storage.sync.get(["numberDisplayFormat"], (res) => {
  381. if (res.numberDisplayFormat === undefined) {
  382. api.storage.sync.set({ numberDisplayFormat: "compactShort" });
  383. } else {
  384. extConfig.numberDisplayFormat = res.numberDisplayFormat;
  385. }
  386. });
  387. }
  388. function initializeTooltipPercentage() {
  389. api.storage.sync.get(["showTooltipPercentage"], (res) => {
  390. if (res.showTooltipPercentage === undefined) {
  391. api.storage.sync.set({ showTooltipPercentage: false });
  392. } else {
  393. extConfig.showTooltipPercentage = res.showTooltipPercentage;
  394. }
  395. });
  396. }
  397. function initializeTooltipPercentageMode() {
  398. api.storage.sync.get(["tooltipPercentageMode"], (res) => {
  399. if (res.tooltipPercentageMode === undefined) {
  400. api.storage.sync.set({ tooltipPercentageMode: "dash_like" });
  401. } else {
  402. extConfig.tooltipPercentageMode = res.tooltipPercentageMode;
  403. }
  404. });
  405. }
  406. function initializeNumberDisplayReformatLikes() {
  407. api.storage.sync.get(["numberDisplayReformatLikes"], (res) => {
  408. if (res.numberDisplayReformatLikes === undefined) {
  409. api.storage.sync.set({ numberDisplayReformatLikes: false });
  410. } else {
  411. extConfig.numberDisplayReformatLikes = res.numberDisplayReformatLikes;
  412. }
  413. });
  414. }
  415. function isChrome() {
  416. return typeof chrome !== "undefined" && typeof chrome.runtime !== "undefined";
  417. }
  418. function isFirefox() {
  419. return (
  420. typeof browser !== "undefined" && typeof browser.runtime !== "undefined"
  421. );
  422. }