ryd.background.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. // coloredThumbs: false,
  12. // coloredBar: false,
  13. numberDisplayFormat: "compactShort", // compactShort, compactLong, standard
  14. numberDisplayRoundDown: true, // locale 'de' shows exact numbers by default
  15. };
  16. if (isChrome()) api = chrome;
  17. else if (isFirefox()) api = browser;
  18. initExtConfig();
  19. api.runtime.onMessage.addListener((request, sender, sendResponse) => {
  20. if (request.message === "get_auth_token") {
  21. chrome.identity.getAuthToken({ interactive: true }, function (token) {
  22. console.log(token);
  23. chrome.identity.getProfileUserInfo(function (userInfo) {
  24. console.log(JSON.stringify(userInfo));
  25. });
  26. });
  27. } else if (request.message === "log_off") {
  28. // chrome.identity.clearAllCachedAuthTokens(() => console.log("logged off"));
  29. } else if (request.message == "set_state") {
  30. // chrome.identity.getAuthToken({ interactive: true }, function (token) {
  31. let token = "";
  32. fetch(
  33. `${apiUrl}/votes?videoId=${request.videoId}&likeCount=${
  34. request.likeCount || ""
  35. }`,
  36. {
  37. method: "GET",
  38. headers: {
  39. Accept: "application/json",
  40. },
  41. }
  42. )
  43. .then((response) => response.json())
  44. .then((response) => {
  45. sendResponse(response);
  46. })
  47. .catch();
  48. return true;
  49. } else if (request.message == "send_links") {
  50. toSend = toSend.concat(request.videoIds.filter((x) => !sentIds.has(x)));
  51. if (toSend.length >= 20) {
  52. fetch(`${apiUrl}/votes`, {
  53. method: "POST",
  54. headers: {
  55. "Content-Type": "application/json",
  56. },
  57. body: JSON.stringify(toSend),
  58. });
  59. for (const toSendUrl of toSend) {
  60. sentIds.add(toSendUrl);
  61. }
  62. toSend = [];
  63. }
  64. } else if (request.message == "register") {
  65. register();
  66. return true;
  67. } else if (request.message == "send_vote") {
  68. sendVote(request.videoId, request.vote);
  69. return true;
  70. }
  71. });
  72. api.runtime.onInstalled.addListener((details) => {
  73. if (
  74. // No need to show changelog if its was a browser update (and not extension update)
  75. details.reason === "browser_update" ||
  76. // No need to show changelog if developer just reloaded the extension
  77. (details.reason === "update" &&
  78. details.previousVersion === chrome.runtime.getManifest().version)
  79. )
  80. return;
  81. api.tabs.create({url: api.runtime.getURL("/changelog/3/changelog_3.0.html")});
  82. })
  83. async function sendVote(videoId, vote) {
  84. api.storage.sync.get(null, async (storageResult) => {
  85. if (!storageResult.userId || !storageResult.registrationConfirmed) {
  86. await register();
  87. return;
  88. }
  89. fetch(`${apiUrl}/interact/vote`, {
  90. method: "POST",
  91. headers: {
  92. "Content-Type": "application/json",
  93. },
  94. body: JSON.stringify({
  95. userId: storageResult.userId,
  96. videoId,
  97. value: vote,
  98. }),
  99. })
  100. .then(async (response) => {
  101. if (response.status == 401) {
  102. await register();
  103. await sendVote(videoId, vote);
  104. return;
  105. }
  106. return response.json();
  107. })
  108. .then((response) => {
  109. solvePuzzle(response).then((solvedPuzzle) => {
  110. fetch(`${apiUrl}/interact/confirmVote`, {
  111. method: "POST",
  112. headers: {
  113. "Content-Type": "application/json",
  114. },
  115. body: JSON.stringify({
  116. ...solvedPuzzle,
  117. userId: storageResult.userId,
  118. videoId,
  119. }),
  120. });
  121. });
  122. });
  123. });
  124. }
  125. function register() {
  126. let userId = generateUserID();
  127. api.storage.sync.set({ userId });
  128. return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
  129. method: "GET",
  130. headers: {
  131. Accept: "application/json",
  132. },
  133. })
  134. .then((response) => response.json())
  135. .then((response) => {
  136. return solvePuzzle(response).then((solvedPuzzle) => {
  137. return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
  138. method: "POST",
  139. headers: {
  140. "Content-Type": "application/json",
  141. },
  142. body: JSON.stringify(solvedPuzzle),
  143. }).then((response) =>
  144. response.json().then((result) => {
  145. if (result === true) {
  146. return api.storage.sync.set({ registrationConfirmed: true });
  147. }
  148. })
  149. );
  150. });
  151. })
  152. .catch();
  153. }
  154. api.storage.sync.get(null, (res) => {
  155. if (!res || !res.userId || !res.registrationConfirmed) {
  156. register();
  157. }
  158. });
  159. const sentIds = new Set();
  160. let toSend = [];
  161. function sendUserSubmittedStatisticsToApi(statistics) {
  162. fetch(`${apiUrl}/votes/user-submitted`, {
  163. method: "POST",
  164. headers: {
  165. "Content-Type": "application/json",
  166. },
  167. body: JSON.stringify(statistics),
  168. });
  169. }
  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) * 5;
  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. }
  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.numberDisplayRoundDown !== undefined) {
  252. handleNumberDisplayRoundDownChangeEvent(
  253. changes.numberDisplayRoundDown.newValue
  254. );
  255. }
  256. if (changes.numberDisplayFormat !== undefined) {
  257. handleNumberDisplayFormatChangeEvent(changes.numberDisplayFormat.newValue);
  258. }
  259. }
  260. function handleDisableVoteSubmissionChangeEvent(value) {
  261. extConfig.disableVoteSubmission = value;
  262. if (value === true) {
  263. changeIcon(voteDisabledIconName);
  264. } else {
  265. changeIcon(defaultIconName);
  266. }
  267. }
  268. function handleNumberDisplayFormatChangeEvent(value) {
  269. extConfig.numberDisplayFormat = value;
  270. }
  271. function handleNumberDisplayRoundDownChangeEvent(value) {
  272. extConfig.numberDisplayRoundDown = value;
  273. }
  274. function changeIcon(iconName) {
  275. if (api.action !== undefined)
  276. api.action.setIcon({ path: "/icons/" + iconName });
  277. else if (api.browserAction !== undefined)
  278. api.browserAction.setIcon({ path: "/icons/" + iconName });
  279. else console.log("changing icon is not supported");
  280. }
  281. function handleColoredThumbsChangeEvent(value) {
  282. extConfig.coloredThumbs = value;
  283. }
  284. function handleColoredBarChangeEvent(value) {
  285. extConfig.coloredBar = value;
  286. }
  287. function handleColorThemeChangeEvent(value) {
  288. if (!value) {
  289. value = "classic";
  290. }
  291. extConfig.colorTheme = value;
  292. }
  293. api.storage.onChanged.addListener(storageChangeHandler);
  294. function initExtConfig() {
  295. initializeDisableVoteSubmission();
  296. initializeColoredThumbs();
  297. initializeColoredBar();
  298. initializeColorTheme();
  299. initializeNumberDisplayFormat();
  300. initializeNumberDisplayRoundDown();
  301. }
  302. function initializeDisableVoteSubmission() {
  303. api.storage.sync.get(["disableVoteSubmission"], (res) => {
  304. if (res.disableVoteSubmission === undefined) {
  305. api.storage.sync.set({ disableVoteSubmission: false });
  306. } else {
  307. extConfig.disableVoteSubmission = res.disableVoteSubmission;
  308. if (res.disableVoteSubmission) changeIcon(voteDisabledIconName);
  309. }
  310. });
  311. }
  312. function initializeColoredThumbs() {
  313. api.storage.sync.get(["coloredThumbs"], (res) => {
  314. if (res.coloredThumbs === undefined) {
  315. api.storage.sync.set({ coloredThumbs: false });
  316. } else {
  317. extConfig.coloredThumbs = res.coloredThumbs;
  318. }
  319. });
  320. }
  321. function initializeNumberDisplayRoundDown() {
  322. api.storage.sync.get(["numberDisplayRoundDown"], (res) => {
  323. if (res.numberDisplayRoundDown === undefined) {
  324. api.storage.sync.set({ numberDisplayRoundDown: true });
  325. } else {
  326. extConfig.numberDisplayRoundDown = res.numberDisplayRoundDown;
  327. }
  328. });
  329. }
  330. function initializeColoredBar() {
  331. api.storage.sync.get(["coloredBar"], (res) => {
  332. if (res.coloredBar === undefined) {
  333. api.storage.sync.set({ coloredBar: false });
  334. } else {
  335. extConfig.coloredBar = res.coloredBar;
  336. }
  337. });
  338. }
  339. function initializeColorTheme() {
  340. api.storage.sync.get(["colorTheme"], (res) => {
  341. if (res.colorTheme === undefined) {
  342. api.storage.sync.set({ colorTheme: false });
  343. } else {
  344. extConfig.colorTheme = res.colorTheme;
  345. }
  346. });
  347. }
  348. function initializeNumberDisplayFormat() {
  349. api.storage.sync.get(["numberDisplayFormat"], (res) => {
  350. if (res.numberDisplayFormat === undefined) {
  351. api.storage.sync.set({ numberDisplayFormat: "compactShort" });
  352. } else {
  353. extConfig.numberDisplayFormat = res.numberDisplayFormat;
  354. }
  355. });
  356. }
  357. function isChrome() {
  358. return typeof chrome !== "undefined" && typeof chrome.runtime !== "undefined";
  359. }
  360. function isFirefox() {
  361. return (
  362. typeof browser !== "undefined" && typeof browser.runtime !== "undefined"
  363. );
  364. }