ryd.background.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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({
  82. url: api.runtime.getURL("/changelog/3/changelog_3.0.html"),
  83. });
  84. });
  85. async function sendVote(videoId, vote) {
  86. api.storage.sync.get(null, async (storageResult) => {
  87. if (!storageResult.userId || !storageResult.registrationConfirmed) {
  88. await register();
  89. return;
  90. }
  91. fetch(`${apiUrl}/interact/vote`, {
  92. method: "POST",
  93. headers: {
  94. "Content-Type": "application/json",
  95. },
  96. body: JSON.stringify({
  97. userId: storageResult.userId,
  98. videoId,
  99. value: vote,
  100. }),
  101. })
  102. .then(async (response) => {
  103. if (response.status == 401) {
  104. await register();
  105. await sendVote(videoId, vote);
  106. return;
  107. }
  108. return response.json();
  109. })
  110. .then((response) => {
  111. solvePuzzle(response).then((solvedPuzzle) => {
  112. fetch(`${apiUrl}/interact/confirmVote`, {
  113. method: "POST",
  114. headers: {
  115. "Content-Type": "application/json",
  116. },
  117. body: JSON.stringify({
  118. ...solvedPuzzle,
  119. userId: storageResult.userId,
  120. videoId,
  121. }),
  122. });
  123. });
  124. });
  125. });
  126. }
  127. function register() {
  128. let userId = generateUserID();
  129. api.storage.sync.set({ userId });
  130. return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
  131. method: "GET",
  132. headers: {
  133. Accept: "application/json",
  134. },
  135. })
  136. .then((response) => response.json())
  137. .then((response) => {
  138. return solvePuzzle(response).then((solvedPuzzle) => {
  139. return fetch(`${apiUrl}/puzzle/registration?userId=${userId}`, {
  140. method: "POST",
  141. headers: {
  142. "Content-Type": "application/json",
  143. },
  144. body: JSON.stringify(solvedPuzzle),
  145. }).then((response) =>
  146. response.json().then((result) => {
  147. if (result === true) {
  148. return api.storage.sync.set({ registrationConfirmed: true });
  149. }
  150. })
  151. );
  152. });
  153. })
  154. .catch();
  155. }
  156. api.storage.sync.get(null, (res) => {
  157. if (!res || !res.userId || !res.registrationConfirmed) {
  158. register();
  159. }
  160. });
  161. const sentIds = new Set();
  162. let toSend = [];
  163. function sendUserSubmittedStatisticsToApi(statistics) {
  164. fetch(`${apiUrl}/votes/user-submitted`, {
  165. method: "POST",
  166. headers: {
  167. "Content-Type": "application/json",
  168. },
  169. body: JSON.stringify(statistics),
  170. });
  171. }
  172. function countLeadingZeroes(uInt8View, limit) {
  173. let zeroes = 0;
  174. let value = 0;
  175. for (let i = 0; i < uInt8View.length; i++) {
  176. value = uInt8View[i];
  177. if (value === 0) {
  178. zeroes += 8;
  179. } else {
  180. let count = 1;
  181. if (value >>> 4 === 0) {
  182. count += 4;
  183. value <<= 4;
  184. }
  185. if (value >>> 6 === 0) {
  186. count += 2;
  187. value <<= 2;
  188. }
  189. zeroes += count - (value >>> 7);
  190. break;
  191. }
  192. if (zeroes >= limit) {
  193. break;
  194. }
  195. }
  196. return zeroes;
  197. }
  198. async function solvePuzzle(puzzle) {
  199. let challenge = Uint8Array.from(atob(puzzle.challenge), (c) =>
  200. c.charCodeAt(0)
  201. );
  202. let buffer = new ArrayBuffer(20);
  203. let uInt8View = new Uint8Array(buffer);
  204. let uInt32View = new Uint32Array(buffer);
  205. let maxCount = Math.pow(2, puzzle.difficulty) * 5;
  206. for (let i = 4; i < 20; i++) {
  207. uInt8View[i] = challenge[i - 4];
  208. }
  209. for (let i = 0; i < maxCount; i++) {
  210. uInt32View[0] = i;
  211. let hash = await crypto.subtle.digest("SHA-512", buffer);
  212. let hashUint8 = new Uint8Array(hash);
  213. if (countLeadingZeroes(hashUint8) >= puzzle.difficulty) {
  214. return {
  215. solution: btoa(String.fromCharCode.apply(null, uInt8View.slice(0, 4))),
  216. };
  217. }
  218. }
  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.numberDisplayRoundDown !== undefined) {
  254. handleNumberDisplayRoundDownChangeEvent(
  255. changes.numberDisplayRoundDown.newValue
  256. );
  257. }
  258. if (changes.numberDisplayFormat !== undefined) {
  259. handleNumberDisplayFormatChangeEvent(changes.numberDisplayFormat.newValue);
  260. }
  261. }
  262. function handleDisableVoteSubmissionChangeEvent(value) {
  263. extConfig.disableVoteSubmission = value;
  264. if (value === true) {
  265. changeIcon(voteDisabledIconName);
  266. } else {
  267. changeIcon(defaultIconName);
  268. }
  269. }
  270. function handleNumberDisplayFormatChangeEvent(value) {
  271. extConfig.numberDisplayFormat = value;
  272. }
  273. function handleNumberDisplayRoundDownChangeEvent(value) {
  274. extConfig.numberDisplayRoundDown = value;
  275. }
  276. function changeIcon(iconName) {
  277. if (api.action !== undefined)
  278. api.action.setIcon({ path: "/icons/" + iconName });
  279. else if (api.browserAction !== undefined)
  280. api.browserAction.setIcon({ path: "/icons/" + iconName });
  281. else console.log("changing icon is not supported");
  282. }
  283. function handleColoredThumbsChangeEvent(value) {
  284. extConfig.coloredThumbs = value;
  285. }
  286. function handleColoredBarChangeEvent(value) {
  287. extConfig.coloredBar = value;
  288. }
  289. function handleColorThemeChangeEvent(value) {
  290. if (!value) {
  291. value = "classic";
  292. }
  293. extConfig.colorTheme = value;
  294. }
  295. api.storage.onChanged.addListener(storageChangeHandler);
  296. function initExtConfig() {
  297. initializeDisableVoteSubmission();
  298. initializeColoredThumbs();
  299. initializeColoredBar();
  300. initializeColorTheme();
  301. initializeNumberDisplayFormat();
  302. initializeNumberDisplayRoundDown();
  303. }
  304. function initializeDisableVoteSubmission() {
  305. api.storage.sync.get(["disableVoteSubmission"], (res) => {
  306. if (res.disableVoteSubmission === undefined) {
  307. api.storage.sync.set({ disableVoteSubmission: false });
  308. } else {
  309. extConfig.disableVoteSubmission = res.disableVoteSubmission;
  310. if (res.disableVoteSubmission) changeIcon(voteDisabledIconName);
  311. }
  312. });
  313. }
  314. function initializeColoredThumbs() {
  315. api.storage.sync.get(["coloredThumbs"], (res) => {
  316. if (res.coloredThumbs === undefined) {
  317. api.storage.sync.set({ coloredThumbs: false });
  318. } else {
  319. extConfig.coloredThumbs = res.coloredThumbs;
  320. }
  321. });
  322. }
  323. function initializeNumberDisplayRoundDown() {
  324. api.storage.sync.get(["numberDisplayRoundDown"], (res) => {
  325. if (res.numberDisplayRoundDown === undefined) {
  326. api.storage.sync.set({ numberDisplayRoundDown: true });
  327. } else {
  328. extConfig.numberDisplayRoundDown = res.numberDisplayRoundDown;
  329. }
  330. });
  331. }
  332. function initializeColoredBar() {
  333. api.storage.sync.get(["coloredBar"], (res) => {
  334. if (res.coloredBar === undefined) {
  335. api.storage.sync.set({ coloredBar: false });
  336. } else {
  337. extConfig.coloredBar = res.coloredBar;
  338. }
  339. });
  340. }
  341. function initializeColorTheme() {
  342. api.storage.sync.get(["colorTheme"], (res) => {
  343. if (res.colorTheme === undefined) {
  344. api.storage.sync.set({ colorTheme: false });
  345. } else {
  346. extConfig.colorTheme = res.colorTheme;
  347. }
  348. });
  349. }
  350. function initializeNumberDisplayFormat() {
  351. api.storage.sync.get(["numberDisplayFormat"], (res) => {
  352. if (res.numberDisplayFormat === undefined) {
  353. api.storage.sync.set({ numberDisplayFormat: "compactShort" });
  354. } else {
  355. extConfig.numberDisplayFormat = res.numberDisplayFormat;
  356. }
  357. });
  358. }
  359. function isChrome() {
  360. return typeof chrome !== "undefined" && typeof chrome.runtime !== "undefined";
  361. }
  362. function isFirefox() {
  363. return (
  364. typeof browser !== "undefined" && typeof browser.runtime !== "undefined"
  365. );
  366. }