ryd.background.js 11 KB

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