ryd.background.js 12 KB

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