A Chrome extension that gives you finer control over MyAnimeList.net scores
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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