ryd.background.js 11 KB

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