ryd.background.js 11 KB

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