ryd.background.js 12 KB

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