ryd.background.js 12 KB

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