AtCoder Editorial Voting

AtCoderの解説に投票します。

目前為 2024-04-22 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name AtCoder Editorial Voting
  3. // @namespace https://atcoder.jp/
  4. // @version 2024-04-22
  5. // @description AtCoderの解説に投票します。
  6. // @license MIT
  7. // @author magurofly
  8. // @match https://atcoder.jp/contests/*/editorial
  9. // @match https://atcoder.jp/contests/*/editorial?*
  10. // @match https://atcoder.jp/contests/*/tasks/*/editorial
  11. // @match https://atcoder.jp/contests/*/tasks/*/editorial?*
  12. // @match https://atcoder.jp/contests/*/editorial/*
  13. // @icon https://www.google.com/s2/favicons?sz=64&domain=atcoder.jp
  14. // @grant unsafeWindow
  15. // @grant GM_getValue
  16. // @grant GM_setValue
  17. // ==/UserScript==
  18.  
  19. // AtCoder で定義されている以下の変数を使用します
  20. // - contestScreenName
  21. // - userScreenName
  22. // 以下のサイトにアクセスします
  23. // - https://atcoder.jp/*
  24. // - https://magurofly.zapto.org/*
  25. (function() {
  26. "use strict";
  27.  
  28. // このスクリプトの機能
  29. // - 解説リンクに投票スコアと投票ボタンを表示する
  30. // - バックエンドにログインする(ため、一時的に所属欄を書き換える)
  31. // - 投票する
  32.  
  33. let token = GM_getValue("token", null);
  34.  
  35. function canonicalizeEditorialLink(url) {
  36. const prefix = "https://atcoder.jp/jump?url=";
  37. if (url.startsWith(prefix)) {
  38. return decodeURIComponent(url.slice(prefix.length));
  39. }
  40. return url;
  41. }
  42.  
  43. function encodeFormData(data) {
  44. return Object.keys(data).map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]) ).join("&");
  45. }
  46.  
  47. async function callApi(name, body) {
  48. const result = await fetch("https://magurofly.zapto.org/" + name, {
  49. method: "POST",
  50. headers: {
  51. "Content-Type": "application/json",
  52. },
  53. body: JSON.stringify(body),
  54. }).then(res => res.json());
  55. if (result.status == "error") {
  56. if (result.reason == "invalid token") {
  57. token = null;
  58. }
  59. throw "Error: " + result.reason;
  60. }
  61. return result;
  62. }
  63.  
  64. async function login() {
  65. // 所属トークンを得る
  66. const affiliationTokenData = await callApi("create-affiliation-token", { atcoder_id: unsafeWindow.userScreenName });
  67. const affiliation_token = affiliationTokenData.affiliation_token;
  68.  
  69. // 設定を得る
  70. const profileSettings = new DOMParser().parseFromString(await fetch("https://atcoder.jp/settings").then(res => res.text()), "text/html");
  71. const data = {};
  72. for (const input of profileSettings.querySelector("#main-container form").elements) {
  73. data[input.name] = input.value;
  74. }
  75. const oldAffiliation = data["ui.Affiliation"];
  76.  
  77. // 所属に所属トークンを設定する
  78. data["ui.Affiliation"] = affiliation_token;
  79. await fetch("https://atcoder.jp/settings", {
  80. method: "POST",
  81. headers: {
  82. "Content-Type": "application/x-www-form-urlencoded",
  83. },
  84. body: encodeFormData(data),
  85. });
  86.  
  87. // 認証する
  88. const tokenData = await callApi("create-token", { atcoder_id: unsafeWindow.userScreenName, affiliation_token });
  89.  
  90. // 所属を元に戻す
  91. data["ui.Affiliation"] = oldAffiliation;
  92. await fetch("https://atcoder.jp/settings", {
  93. method: "POST",
  94. headers: {
  95. "Content-Type": "application/x-www-form-urlencoded",
  96. },
  97. body: encodeFormData(data),
  98. });
  99.  
  100. // トークンを保存する
  101. token = tokenData.token;
  102. GM_setValue("token", token);
  103. }
  104.  
  105. // 投票する
  106. async function sendVote(editorial, vote) {
  107. if (token == null) {
  108. await login();
  109. }
  110.  
  111. callApi("vote", {
  112. token,
  113. contest: unsafeWindow.contestScreenName,
  114. editorial,
  115. vote,
  116. });
  117. }
  118.  
  119. // レート分布を表示するやつ
  120. class HistogramComponent {
  121. constructor() {
  122. this.element = document.createElement("canvas");
  123. this.element.width = 320;
  124. this.element.height = 160;
  125. this.ctx = this.element.getContext("2d");
  126. this.dist = [0, 0, 0, 0, 0, 0, 0, 0];
  127. this.draw();
  128. }
  129.  
  130. setRatingDistribution(dist) {
  131. if (dist) this.dist = dist;
  132. this.draw();
  133. }
  134.  
  135. draw() {
  136. const colors = ["#808080", "#804000", "#008000", "#00C0C0", "#0000FF", "#C0C000", "#FF8000", "#FF0000"];
  137. const vHalf = this.element.height / 2;
  138. const vUnit = (vHalf - 16) / Math.max(4, ...this.dist.map(y => Math.abs(y)));
  139. const hUnit = this.element.width / 8;
  140. this.ctx.clearRect(0, 0, this.element.width, this.element.height);
  141. this.ctx.fillStyle = "#333";
  142. this.ctx.fillRect(0, this.element.height / 2 - 1, hUnit * 8, 2);
  143. this.ctx.font = "12px serif";
  144. this.ctx.textAlign = "center";
  145. for (let i = 0; i < 8; i++) {
  146. const x = hUnit * i;
  147. const value = this.dist[i];
  148. this.ctx.fillStyle = colors[i];
  149. if (value > 0) {
  150. this.ctx.fillRect(x, vHalf - 1 - vUnit * value, hUnit, vUnit * value - 1);
  151. this.ctx.fillStyle = "#333";
  152. this.ctx.fillText(value.toString(), x + hUnit / 2, vHalf - 4 - vUnit * value);
  153. } else if (value < 0) {
  154. this.ctx.fillRect(x, vHalf + 1 + vUnit * -value, hUnit, vUnit * value - 1);
  155. this.ctx.fillStyle = "#333";
  156. this.ctx.fillText(value.toString(), x + hUnit / 2, vHalf + 16 + vUnit * -value);
  157. }
  158. }
  159. }
  160. }
  161.  
  162. // 解説リンクにスコアと投票ボタンを表示する
  163. // ここのデザインは burioden 様に助けていただきました
  164. class VoteComponent {
  165. constructor(editorial) {
  166. this.element = document.createElement("span");
  167.  
  168. this.editorial = canonicalizeEditorialLink(editorial);
  169.  
  170. this.score = 0;
  171. this.vote = 0;
  172. this.dist = [0, 0, 0, 0, 0, 0, 0, 0];
  173. this.scoreView = document.createElement("span");
  174. Object.assign(this.scoreView.style, {
  175. verticalAlign: "middle",
  176. display: "inline-block",
  177. boxSizing: "border-box",
  178. height: "100%",
  179. padding: "1px 5px",
  180. lineHeight: "1.5",
  181. borderTop: "1px solid #aaa",
  182. borderBottom: "1px solid #aaa",
  183. background: "transparent",
  184. color: "#333",
  185. });
  186. this.scoreView.textContent = "0";
  187. this.btnUpVote = document.createElement("button");
  188. this.btnUpVote.className = "btn btn-xs btn-warning";
  189. Object.assign(this.btnUpVote.style, {
  190. border: "1px solid #aaa",
  191. borderRadius: "0 5px 5px 0",
  192. height: "100%",
  193. fontSize: "inherit",
  194. });
  195. this.btnUpVote.type = "button";
  196. this.btnUpVote.textContent = "+";
  197. this.btnUpVote.onclick = this.setVote.bind(this, 1);
  198. this.btnDownVote = document.createElement("button");
  199. this.btnDownVote.className = "btn btn-xs btn-info";
  200. Object.assign(this.btnDownVote.style, {
  201. border: "1px solid #aaa",
  202. borderRadius: "5px 0 0 5px",
  203. height: "100%",
  204. fontSize: "inherit",
  205. });
  206. this.btnDownVote.type = "button";
  207. this.btnDownVote.textContent = "-";
  208. this.btnDownVote.onclick = this.setVote.bind(this, -1);
  209.  
  210. // キャンバスをつくる
  211. this.histogram = new HistogramComponent();
  212. Object.assign(this.histogram.element.style, {
  213. position: "fixed",
  214. zIndex: 9999,
  215. display: "none",
  216. border: "1px solid #aaa",
  217. background: "#fff",
  218. boxShadow: "10px 5px 5px #333",
  219. });
  220. this.scoreView.addEventListener("mouseover", () => {
  221. const bounds = this.scoreView.getBoundingClientRect();
  222. this.histogram.left = `${bounds.x + bounds.width * 0.5}px`;
  223. this.histogram.top = `${bounds.y + bounds.height}px`;
  224. this.histogram.element.style.display = "block";
  225. });
  226. this.scoreView.addEventListener("mouseout", () => {
  227. this.histogram.element.style.display = "none";
  228. });
  229. Object.assign(this.element.style, {
  230. position: "relative",
  231. overflow: "visible",
  232. display: "inline-block",
  233. height: "1.5em",
  234. margin: "0 8px",
  235. fontSize: "12px",
  236. });
  237.  
  238. // 子供を追加
  239. this.element.appendChild(this.btnDownVote);
  240. this.element.appendChild(this.scoreView);
  241. this.element.appendChild(this.btnUpVote);
  242. this.element.appendChild(this.histogram.element);
  243. }
  244.  
  245. setCurrentVote(score, vote, dist) {
  246. this.vote = vote;
  247. this.score = score;
  248. this.dist = dist;
  249. this.scoreView.textContent = score;
  250. this.histogram.setRatingDistribution(dist);
  251. if (vote == 1) {
  252. this.btnUpVote.classList.add("active");
  253. this.btnUpVote.onclick = this.setVote.bind(this, 0);
  254. this.btnDownVote.classList.remove("active");
  255. this.btnDownVote.onclick = this.setVote.bind(this, -1);
  256. } else if (vote == -1) {
  257. this.btnUpVote.classList.remove("active");
  258. this.btnUpVote.onclick = this.setVote.bind(this, 1);
  259. this.btnDownVote.classList.add("active");
  260. this.btnDownVote.onclick = this.setVote.bind(this, 0);
  261. } else {
  262. this.btnUpVote.classList.remove("active");
  263. this.btnUpVote.onclick = this.setVote.bind(this, 1);
  264. this.btnDownVote.classList.remove("active");
  265. this.btnDownVote.onclick = this.setVote.bind(this, -1);
  266. }
  267. }
  268.  
  269. async setVote(vote) {
  270. this.score += vote - this.vote;
  271. this.setCurrentVote(this.score, vote, this.dist);
  272. if (vote == 1) {
  273. await sendVote(this.editorial, "up");
  274. } else if (vote == -1) {
  275. await sendVote(this.editorial, "down");
  276. } else {
  277. await sendVote(this.editorial, "none");
  278. }
  279. }
  280. }
  281.  
  282. const votes = [];
  283. if (/\/editorial$/.test(location.pathname)) {
  284. for (const link of unsafeWindow.document.querySelectorAll("#main-container a[rel=noopener]")) {
  285. const vote = new VoteComponent(link.href);
  286. link.parentElement.insertBefore(vote.element, link);
  287. votes.push(vote);
  288. }
  289. }
  290. if (/\/editorial\/\d+$/.test(location.pathname)) {
  291. const vote = new VoteComponent(location.href);
  292. document.querySelector("#main-container > div.row > div:nth-child(2) > h2").appendChild(vote.element);
  293. votes.push(vote);
  294. }
  295.  
  296. callApi("statuses", { token, editorials: votes.map(v => v.editorial) }).then(res => {
  297. for (let i = 0; i < res.results.length; i++) {
  298. const { score, scores_by_rating, current_vote } = res.results[i];
  299. const vote = current_vote == "up" ? 1 : current_vote == "down" ? -1 : 0;
  300. const dist = [0, 0, 0, 0, 0, 0, 0, 0];
  301. for (const [key, value] of Object.entries(scores_by_rating)) {
  302. const rating = parseInt(key.split("-")[0]);
  303. if (rating < 2800) {
  304. dist[Math.trunc(rating / 400)] += value;
  305. } else {
  306. dist[7] += value;
  307. }
  308. }
  309. votes[i].setCurrentVote(score, vote, dist);
  310. }
  311. });
  312. })();