A Chrome extension that gives you finer control over MyAnimeList.net scores
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

660 lines
23 KiB

  1. /* Decimal Scores for MyAnimeList
  2. Copyright (C) 2014 Ben Kurtovic <ben.kurtovic@gmail.com>
  3. Distributed under the terms of the MIT License. See the LICENSE file for
  4. details.
  5. */
  6. /* -------------------------------- Globals -------------------------------- */
  7. var MAX_BUCKETS = 256;
  8. var LOADING_IMG = '<img src="http://cdn.myanimelist.net/images/xmlhttp-loader.gif" align="center">';
  9. var should_sort = window.location.href.indexOf("order=4") != -1;
  10. /* ------------------------ Miscellaneous functions ------------------------ */
  11. /* Note: complaints about modifying objects we don't own are ignored since
  12. these changes are only executed within the context of our own extension. */
  13. String.prototype.contains = function(substr) {
  14. return this.indexOf(substr) != -1;
  15. };
  16. String.prototype.cut_after = function(substr) {
  17. return this.substr(this.indexOf(substr) + substr.length)
  18. };
  19. String.prototype.cut_before = function(substr) {
  20. return this.substr(0, this.indexOf(substr));
  21. };
  22. String.prototype.cut = function(after, before) {
  23. return this.cut_after(after).cut_before(before);
  24. }
  25. function round_score(num) {
  26. num = Math.round(num * 10) / 10;
  27. if (isNaN(num))
  28. return num;
  29. if (num == Math.round(num))
  30. num += ".0";
  31. return num;
  32. }
  33. function get_anime_id_from_href(href) {
  34. var anime_id;
  35. if (href.contains("/anime/"))
  36. anime_id = href.cut_after("/anime/");
  37. else
  38. anime_id = href.cut_after("id=");
  39. if (anime_id.contains("/"))
  40. anime_id = anime_id.cut_before("/");
  41. if (anime_id.contains("&"))
  42. anime_id = anime_id.cut_before("&");
  43. return anime_id;
  44. }
  45. function get_edit_id_from_href(href) {
  46. var anime_id = href.cut_after("id=");
  47. if (anime_id.contains("&"))
  48. anime_id = anime_id.cut_before("&");
  49. return anime_id;
  50. }
  51. function get_score_from_element(elem) {
  52. var score = round_score(elem.val());
  53. if (isNaN(score) || ((score < 1 || score > 10) && score != 0)) {
  54. alert("Invalid score: must be a number between 1.0 and 10.0, or 0.");
  55. return null;
  56. }
  57. return score;
  58. }
  59. function load_score_into_element(data, anime_id, elem) {
  60. var bucket = data[(parseInt(anime_id) % MAX_BUCKETS).toString()];
  61. if (bucket !== undefined && bucket[anime_id] !== undefined)
  62. elem.text(bucket[anime_id] == 0 ? "-" : bucket[anime_id]);
  63. else {
  64. var current = parseInt(elem.text());
  65. if (!isNaN(current))
  66. elem.text(current + ".0");
  67. }
  68. }
  69. function update_shared_row_colors(row, our_pos) {
  70. var our_cell = $(row.find("td")[our_pos]);
  71. var their_cell = $(row.find("td")[our_pos == 1 ? 2 : 1]);
  72. var diff = our_cell.text() - their_cell.text();
  73. if (!diff) {
  74. row.find("td").css("background-color", "#f6f6f6");
  75. our_cell.add(their_cell).find("span").css("color", "");
  76. }
  77. else {
  78. row.find("td").css("background-color", "");
  79. our_cell.css("color", diff > 0 ? "#FF0000" : "#0000FF");
  80. their_cell.css("color", diff > 0 ? "#0000FF" : "#FF0000");
  81. }
  82. }
  83. /* --------------------------- Storage functions --------------------------- */
  84. function save_score(anime_id, score) {
  85. var bucket_id = (parseInt(anime_id) % MAX_BUCKETS).toString();
  86. chrome.storage.sync.get(bucket_id, function(data) {
  87. var bucket = data[bucket_id];
  88. if (bucket === undefined)
  89. bucket = data[bucket_id] = {};
  90. bucket[anime_id] = score;
  91. chrome.storage.sync.set(data);
  92. });
  93. }
  94. function retrieve_scores(anime_id, callback) {
  95. var bucket_id = null;
  96. if (anime_id !== null)
  97. bucket_id = (parseInt(anime_id) % MAX_BUCKETS).toString();
  98. chrome.storage.sync.get(bucket_id, function(data) {
  99. if (anime_id !== null) {
  100. var bucket = data[bucket_id];
  101. if (bucket !== undefined && bucket[anime_id] !== undefined)
  102. callback(bucket[anime_id]);
  103. else
  104. callback(null);
  105. }
  106. else
  107. callback(data);
  108. });
  109. }
  110. function remove_score(anime_id) {
  111. var bucket_id = (parseInt(anime_id) % MAX_BUCKETS).toString();
  112. chrome.storage.sync.get(bucket_id, function(data) {
  113. var bucket = data[bucket_id];
  114. if (bucket === undefined || bucket[anime_id] === undefined)
  115. return;
  116. delete bucket[anime_id];
  117. if ($.isEmptyObject(bucket))
  118. chrome.storage.sync.remove(bucket_id);
  119. else
  120. chrome.storage.sync.set(data);
  121. });
  122. }
  123. function export_scores() {
  124. chrome.storage.sync.get(null, function(dat) {
  125. var blob = new Blob([JSON.stringify(dat)], {type: "application/json"});
  126. $($("<a>")
  127. .attr("href", window.URL.createObjectURL(blob))
  128. .attr("download", "animelist_decimal_scores.json")
  129. .hide()
  130. .appendTo($("body"))[0].click()).remove();
  131. });
  132. }
  133. function validate_score_data(data) {
  134. if (!$.isPlainObject(data))
  135. throw "invalid data type: " + data;
  136. if (JSON.stringify(data).length > chrome.storage.sync.QUOTA_BYTES)
  137. throw "file too large";
  138. for (var bucket_id in data) {
  139. if (data.hasOwnProperty(bucket_id)) {
  140. if (isNaN(parseInt(bucket_id)) || bucket_id >= MAX_BUCKETS)
  141. throw "invalid bucket ID: " + bucket_id;
  142. var bucket = data[bucket_id];
  143. if (!$.isPlainObject(bucket))
  144. throw "invalid bucket type: " + bucket;
  145. for (var anime_id in bucket) {
  146. if (data.hasOwnProperty(anime_id)) {
  147. if (isNaN(parseInt(anime_id)))
  148. throw "invalid anime ID: " + anime_id;
  149. if (parseInt(anime_id) % MAX_BUCKETS != bucket_id)
  150. throw "anime is in the wrong bucket: " + anime_id;
  151. var score = parseFloat(bucket[anime_id]);
  152. if (isNaN(score))
  153. throw "score is not a number: " + score;
  154. if ((score < 1 || score > 10) && score != 0)
  155. throw "score out of range: " + score;
  156. }
  157. }
  158. }
  159. }
  160. }
  161. function import_scores(data, callback) {
  162. validate_score_data(data);
  163. chrome.storage.sync.clear(function() {
  164. chrome.storage.sync.set(data, callback);
  165. });
  166. }
  167. /* ----------------------- Event patches/injections ------------------------ */
  168. function update_list_score(anime_id) {
  169. var new_score = get_score_from_element($("#scoretext" + anime_id));
  170. if (new_score === null)
  171. return;
  172. var payload = {id: anime_id, score: Math.round(new_score)};
  173. $("#scorebutton" + anime_id).prop("disabled", true);
  174. $.post("/includes/ajax.inc.php?t=63", payload, function(data) {
  175. $("#scoreval" + anime_id).text(new_score == 0 ? "-" : new_score);
  176. $("#scoretext" + anime_id).val("");
  177. $("#scorediv" + anime_id).css("display", "none");
  178. $("#scorebutton" + anime_id).prop("disabled", false);
  179. if (should_sort)
  180. sort_list();
  181. update_list_stats();
  182. });
  183. save_score(anime_id, new_score);
  184. }
  185. function update_anime_score(anime_id, is_new) {
  186. var new_score = get_score_from_element($("#myinfo_score"));
  187. if (new_score === null)
  188. return;
  189. var t_id, payload = {score: Math.round(new_score)};
  190. payload["status"] = $("#myinfo_status").val();
  191. payload["epsseen"] = $("#myinfo_watchedeps").val();
  192. if (is_new) {
  193. payload["aid"] = anime_id;
  194. t_id = "61";
  195. }
  196. else {
  197. payload["alistid"] = anime_id;
  198. payload["aid"] = $("#myinfo_anime_id").val();
  199. payload["astatus"] = $("#myinfo_curstatus").val();
  200. t_id = "62";
  201. }
  202. $("#myinfoDisplay").html(LOADING_IMG);
  203. $.post("/includes/ajax.inc.php?t=" + t_id, payload, function(data) {
  204. if (is_new) {
  205. $("#myinfoDisplay").html("");
  206. $("#addtolist").html(data);
  207. }
  208. else
  209. $("#myinfoDisplay").html(data);
  210. });
  211. save_score(anime_id, new_score);
  212. }
  213. function submit_add_form(submit_button) {
  214. var anime_id = $("input[name='series_title']").val();
  215. if (!anime_id)
  216. return submit_button[0].click();
  217. var new_score = get_score_from_element($("#score_input"));
  218. if (new_score === null)
  219. return;
  220. $("select[name='score']").val(Math.round(new_score));
  221. save_score(anime_id, new_score);
  222. submit_button[0].click();
  223. }
  224. function submit_edit_form(anime_id, submit_type, submit_button) {
  225. if (submit_type == 2) {
  226. var new_score = get_score_from_element($("#score_input"));
  227. if (new_score === null)
  228. return;
  229. $("select[name='score']").val(Math.round(new_score));
  230. save_score(anime_id, new_score);
  231. }
  232. else if (submit_type == 3)
  233. remove_score(anime_id);
  234. submit_button[0].click();
  235. }
  236. /* ------------------------ List stats and sorting ------------------------- */
  237. function compare(row1, row2) {
  238. var r1 = $(row1).find("span[id^='scoreval']").text(),
  239. r2 = $(row2).find("span[id^='scoreval']").text();
  240. if (r1 == r2) {
  241. r1 = $(row1).find("a.animetitle span").text();
  242. r2 = $(row2).find("a.animetitle span").text();
  243. return r1 > r2 ? 1 : -1;
  244. }
  245. if (r1 == "-")
  246. return 1;
  247. if (r2 == "-")
  248. return -1;
  249. return r2 - r1;
  250. }
  251. function prepare_list() {
  252. var headers = [".header_cw", ".header_completed", ".header_onhold",
  253. ".header_dropped", ".header_ptw"];
  254. $.each(headers, function(i, header) {
  255. $(header).next()
  256. .nextUntil($(".category_totals").closest("table"))
  257. .wrapAll('<div class="list-chart-group"/>');
  258. });
  259. $(".list-chart-group table").each(function(i, row) {
  260. $(row).add($(row).next())
  261. .wrapAll('<div class="list-chart-row"/>');
  262. });
  263. }
  264. function sort_list() {
  265. $(".list-chart-group").each(function(i, group) {
  266. $(group).find(".list-chart-row").sort(compare).each(function(i, row) {
  267. $(group).append(row);
  268. });
  269. $(group).find(".list-chart-row").each(function(i, row) {
  270. $(row).find("tr").first().children().first().text(i + 1);
  271. $(row).find((i % 2) ? ".td1" : ".td2").toggleClass("td1 td2");
  272. });
  273. });
  274. }
  275. function apply_stats(elem, old_sum, new_sum, nums) {
  276. var old_score = elem.text().cut("Mean Score: ", ",");
  277. var old_dev = elem.text().cut("Score Dev.: ", "\n");
  278. var mean = round_score(new_sum / nums) || "0.0";
  279. var deviation = (new_sum - old_sum) / nums + parseFloat(old_dev) || 0;
  280. deviation = Math.round(deviation * 100) / 100;
  281. elem.text(elem.text()
  282. .replace("Mean Score: " + old_score, "Mean Score: " + mean)
  283. .replace("Score Dev.: " + old_dev, "Score Dev.: " + deviation));
  284. }
  285. function update_list_stats() {
  286. var old_sum_all = 0, new_sum_all = 0, nums_all = 0;
  287. $(".category_totals").each(function(i, totals) {
  288. var group = $(totals).closest("table").prev();
  289. var old_sum = 0, new_sum = 0, nums = 0;
  290. group.find("span[id^='scoreval']").each(function(j, elem) {
  291. if ($(elem).text() != "-") {
  292. old_sum += parseFloat($(elem).next().text());
  293. new_sum += parseFloat($(elem).text());
  294. nums++;
  295. }
  296. });
  297. apply_stats($(totals), old_sum, new_sum, nums);
  298. old_sum_all += old_sum;
  299. new_sum_all += new_sum;
  300. nums_all += nums;
  301. });
  302. if ($("#grand_totals").length > 0)
  303. apply_stats($("#grand_totals"), old_sum_all, new_sum_all, nums_all);
  304. }
  305. /* ---------------------------- Extension hooks ---------------------------- */
  306. function hook_list() {
  307. retrieve_scores(null, function(data) {
  308. $("span[id^='scoreval']").each(function(i, elem) {
  309. var anime_id = elem.id.split("scoreval")[1];
  310. $(elem).after($("<span>").hide().text($(elem).text()));
  311. load_score_into_element(data, anime_id, $(elem));
  312. $("#scorediv" + anime_id)
  313. .after($("<div>")
  314. .attr("id", "scorediv" + anime_id)
  315. .hide()
  316. .append($('<input>')
  317. .attr("type", "text")
  318. .attr("id", "scoretext" + anime_id)
  319. .attr("size", "2")
  320. .keydown(function(a_id) {
  321. return function(ev) {
  322. if ((window.event ? window.event.keyCode : ev.which) == 13)
  323. update_list_score(a_id);
  324. else
  325. return true;
  326. }
  327. }(anime_id)))
  328. .append($("<input>")
  329. .attr("type", "button")
  330. .attr("id", "scorebutton" + anime_id)
  331. .attr("value", "Go")
  332. .click(function(a_id) {
  333. return function() { return update_list_score(a_id); }
  334. }(anime_id))))
  335. .remove();
  336. });
  337. prepare_list();
  338. if (should_sort)
  339. sort_list();
  340. update_list_stats();
  341. });
  342. }
  343. function hook_anime(anime_id) {
  344. retrieve_scores(anime_id, function(score) {
  345. var old_input = $("#myinfo_score");
  346. var old_button = $("input[name='myinfo_submit']");
  347. var is_new = old_button.attr("value") == "Add";
  348. if (!is_new && score === null)
  349. score = parseInt(old_input.val()) + ".0";
  350. old_input.after($("<span> / 10.0</span>"))
  351. .after($("<input>")
  352. .attr("type", "text")
  353. .attr("id", "myinfo_score")
  354. .attr("name", "myinfo_score")
  355. .attr("class", "inputtext")
  356. .attr("value", (score === null || score == 0) ? "" : score)
  357. .attr("size", "3"))
  358. .remove();
  359. old_button.after($("<input>")
  360. .attr("type", "button")
  361. .attr("name", "myinfo_submit")
  362. .attr("value", old_button.attr("value"))
  363. .attr("class", "inputButton")
  364. .click(function(a_id, is_new) {
  365. return function() { return update_anime_score(a_id, is_new); }
  366. }(anime_id, is_new)))
  367. .remove();
  368. });
  369. }
  370. function hook_add() {
  371. var old_input = $("select[name='score']");
  372. var old_submit = $("input[type='button'][onclick='checkValidSubmit(1)']");
  373. old_input.after($("<span> / 10.0</span>"))
  374. .after($("<input>")
  375. .attr("type", "text")
  376. .attr("id", "score_input")
  377. .attr("class", "inputtext")
  378. .attr("size", "3"))
  379. .hide();
  380. old_submit.after($("<input>")
  381. .attr("type", "button")
  382. .attr("class", "inputButton")
  383. .attr("style", old_submit.attr("style"))
  384. .attr("value", old_submit.attr("value"))
  385. .click(function(button) {
  386. return function() { return submit_add_form(button); }
  387. }(old_submit)))
  388. .hide();
  389. }
  390. function hook_edit(anime_id) {
  391. retrieve_scores(anime_id, function(score) {
  392. var old_input = $("select[name='score']");
  393. var old_edit = $("input[type='button'][onclick='checkValidSubmit(2)']");
  394. var old_delete = $("input[type='button'][onclick='checkValidSubmit(3)']");
  395. if (score === null)
  396. score = parseInt(old_input.val()) + ".0";
  397. old_input.after($("<span> / 10.0</span>"))
  398. .after($("<input>")
  399. .attr("type", "text")
  400. .attr("id", "score_input")
  401. .attr("class", "inputtext")
  402. .attr("value", score == 0 ? "" : score)
  403. .attr("size", "3"))
  404. .hide();
  405. old_edit.after($("<input>")
  406. .attr("type", "button")
  407. .attr("class", "inputButton")
  408. .attr("style", old_edit.attr("style"))
  409. .attr("value", old_edit.attr("value"))
  410. .click(function(a_id, button) {
  411. return function() { return submit_edit_form(a_id, 2, button); }
  412. }(anime_id, old_edit)))
  413. .hide();
  414. old_delete.after($("<input>")
  415. .attr("type", "button")
  416. .attr("class", "inputButton")
  417. .attr("value", old_delete.attr("value"))
  418. .click(function(a_id, button) {
  419. return function() { return submit_edit_form(a_id, 3, button); }
  420. }(anime_id, old_delete)))
  421. .hide();
  422. });
  423. }
  424. function hook_shared() {
  425. var our_profile = $("#nav a:first").attr("href"), our_pos;
  426. var profile_links = $("#content h2:first").find("a").slice(1);
  427. var shared_table = $("#content h2:first").next(), unique_table;
  428. var shared_means = shared_table.find("tr:nth-last-child(2)");
  429. var mean_score, mean_diff;
  430. if ($(profile_links[0]).attr("href") == our_profile)
  431. our_pos = 1;
  432. else if ($(profile_links[1]).attr("href") == our_profile)
  433. our_pos = 2;
  434. else
  435. return;
  436. retrieve_scores(null, function(data) {
  437. var score_sum = 0, diff_sum = 0, score_nums = 0, diff_nums = 0;
  438. shared_table.find("tr").slice(1, -2).each(function(i, row) {
  439. var anime_id = $(row).find("a").attr("href").cut("/anime/", "/");
  440. var our_cell = $($(row).find("td")[our_pos]).find("span");
  441. var their_cell = $($(row).find("td")[our_pos == 1 ? 2 : 1]);
  442. var diff_cell = $($(row).find("td")[3]);
  443. load_score_into_element(data, anime_id, our_cell);
  444. if (our_cell.text() != "-") {
  445. score_sum += parseFloat(our_cell.text());
  446. score_nums++;
  447. }
  448. if (our_cell.text() != "-" && their_cell.text() != "-") {
  449. var diff = Math.abs(our_cell.text() - their_cell.text());
  450. diff_sum += diff;
  451. diff_cell.text(round_score(diff));
  452. diff_nums++;
  453. update_shared_row_colors($(row), our_pos);
  454. }
  455. });
  456. unique_table = $($("#content h2")[our_pos]).next();
  457. unique_table.find("tr").slice(1, -1).each(function(i, row) {
  458. var anime_id = $(row).find("a").attr("href").cut("/anime/", "/");
  459. var cell = $(row).find("td:nth(1)").find("span");
  460. load_score_into_element(data, anime_id, cell);
  461. });
  462. mean_score = round_score(score_sum / score_nums);
  463. if (!isNaN(mean_score)) {
  464. $(shared_means.find("td")[our_pos]).find("span").text(mean_score);
  465. update_shared_row_colors(shared_means, our_pos);
  466. }
  467. mean_diff = Math.round(diff_sum / diff_nums * 100) / 100;
  468. if (!isNaN(mean_diff))
  469. $(shared_means.find("td")[3]).text(mean_diff);
  470. });
  471. }
  472. function hook_addtolist() {
  473. /* TODO: this entry point is unimplemented - it's rarely used and difficult
  474. to inject into, so I'm avoiding it for now. */
  475. $("<p><b>Note:</b> For the time being, anime added through this " +
  476. "interface cannot be given scores on the 10.0-point scale (the old " +
  477. "10-point system is used).</p><p>To give a more specific number, " +
  478. "simply add the anime here, then go to its own page or to your list " +
  479. "page, and update the score.</p>").insertAfter($("#stype").parent());
  480. }
  481. function hook_export() {
  482. chrome.storage.sync.getBytesInUse(null, function(usage) {
  483. usage = Math.round(usage / 1024 * 10) / 10;
  484. usage += " kB / " + chrome.storage.sync.QUOTA_BYTES / 1024 + " kB";
  485. $("#dialog td")
  486. .append($("<hr>")
  487. .css("border", "none")
  488. .css("background-color", "#AAA")
  489. .css("height", "1px"))
  490. .append($("<p>")
  491. .html("The regular list export above will only include " +
  492. "rounded scores. You can export your decimal scores " +
  493. "separately and " +
  494. '<a href="http://myanimelist.net/import.php">import ' +
  495. "them</a> later."))
  496. .append($("<div>")
  497. .attr("class", "spaceit")
  498. .html("Chrome Sync usage: " + usage))
  499. .append($("<input>")
  500. .attr("type", "submit")
  501. .attr("value", "Export Decimal Scores")
  502. .attr("class", "inputButton")
  503. .click(export_scores));
  504. });
  505. }
  506. function hook_import() {
  507. $("#content").append($("<hr>")
  508. .css("border", "none")
  509. .css("background-color", "#AAA")
  510. .css("height", "1px"))
  511. .append($("<p>")
  512. .html("You can also import decimal scores here. Doing so will " +
  513. "erase any existing decimal scores."))
  514. .append($("<div>")
  515. .attr("class", "spaceit")
  516. .append($("<input>")
  517. .attr("id", "decimal-file")
  518. .attr("size", "60")
  519. .attr("type", "file")
  520. .attr("class", "inputtext")))
  521. .append($("<input>")
  522. .attr("id", "decimal-submit")
  523. .attr("type", "submit")
  524. .attr("value", "Import Decimal Scores")
  525. .attr("class", "inputButton")
  526. .click(function() {
  527. var filelist = $("#decimal-file")[0].files, file, reader;
  528. if (filelist.length != 1)
  529. return;
  530. file = filelist[0];
  531. if (file.type != "application/json") {
  532. alert("Invalid file type: must be .json.");
  533. return;
  534. }
  535. reader = new FileReader();
  536. reader.onload = function() {
  537. try {
  538. import_scores(JSON.parse(reader.result), function() {
  539. $("#decimal-file").after("<p>Success!</p>")
  540. .remove();
  541. $("#decimal-submit").remove();
  542. });
  543. } catch (exc) {
  544. if (typeof exc === "object")
  545. alert("The file could not be parsed as JSON.");
  546. else
  547. alert("Error validating data: " + exc);
  548. }
  549. };
  550. reader.readAsText(file);
  551. }));
  552. }
  553. /* ------------------------------- Main hook ------------------------------- */
  554. $(document).ready(function() {
  555. var href = window.location.href;
  556. if (href.contains("/animelist/")) {
  557. var list_info = $("#mal_cs_otherlinks div:first");
  558. if (list_info.text() == "You are viewing your anime list")
  559. hook_list();
  560. }
  561. else if ($("#malLogin").length == 0) {
  562. if (href.contains("/anime/") || href.contains("/anime.php"))
  563. hook_anime(get_anime_id_from_href(href));
  564. else if (href.contains("/panel.php") && href.contains("go=add"))
  565. hook_add();
  566. else if (href.contains("/editlist.php") && href.contains("type=anime"))
  567. hook_edit(get_edit_id_from_href(href));
  568. else if (href.contains("/shared.php") && !href.contains("type=manga"))
  569. hook_shared();
  570. else if (href.contains("/addtolist.php"))
  571. hook_addtolist();
  572. else if (href.contains("/panel.php") && href.contains("go=export"))
  573. hook_export();
  574. else if (href.contains("/import.php"))
  575. hook_import();
  576. }
  577. });