ryd.background.js 12 KB

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