ryd.background.js 10 KB

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