ryd.background.js 11 KB

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