Codeforces Better!

Codeforces界面汉化、题目翻译,markdown视图,一键复制题目

当前为 2023-05-28 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.29
  5. // @description Codeforces界面汉化、题目翻译,markdown视图,一键复制题目
  6. // @author 北极小狐
  7. // @match https://*.codeforces.com/*
  8. // @connect www2.deepl.com
  9. // @connect m.youdao.com
  10. // @connect openai.api2d.net
  11. // @connect api.openai.com
  12. // @grant GM_xmlhttpRequest
  13. // @grant GM_info
  14. // @grant GM_setValue
  15. // @grant GM_getValue
  16. // @connect greasyfork.org
  17. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  18. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  19. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  20. // @license MIT
  21. // ==/UserScript==
  22. // 样式
  23. function loadCssCode(code) {
  24. var style = document.createElement('style');
  25. style.type = 'text/css';
  26. style.rel = 'stylesheet';
  27. style.appendChild(document.createTextNode(code));
  28. var head = document.getElementsByTagName('head')[0];
  29. head.appendChild(style);
  30. }
  31. loadCssCode(`
  32. span.mdViewContent {
  33. white-space: pre-wrap;
  34. }
  35. /*翻译div*/
  36. .translate-problem-statement {
  37. display: grid;
  38. justify-items: start;
  39. white-space: pre-wrap;
  40. letter-spacing: 1.4px;
  41. border: 1px dashed #00aeeccc;
  42. border-radius: 0.3rem;
  43. padding: 5px;
  44. margin: 10px 0px;
  45. font-size: 13px;
  46. }
  47. .translate-problem-statement a {
  48. color: #4d87c7;
  49. background: 0 0;
  50. text-decoration: none;
  51. }
  52. .translate-problem-statement a:hover {
  53. background-color: #800;
  54. color: #fff;
  55. text-decoration: none;
  56. }
  57. .html2md-panel {
  58. display: flex;
  59. justify-content: flex-end;
  60. }
  61. button.html2mdButton {
  62. cursor: pointer;
  63. background-color: #e6e6e6;
  64. color: #727378;
  65. height: 22px;
  66. width: auto;
  67. font-size: 13px;
  68. border-radius: 0.3rem;
  69. border: none;
  70. padding: 1px 5px;
  71. margin: 5px;
  72. box-shadow: 0 0 1px #0000004d;
  73. }
  74. button.html2mdButton.copied {
  75. background-color: #07e65196;
  76. color: #104f2b;
  77. }
  78. button.html2mdButton.mdViewed {
  79. background-color: #ff980057;
  80. color: #5a3a0c;
  81. }
  82. button.translated {
  83. cursor: not-allowed;
  84. background-color: #2a6dc296;
  85. color: #fffdfd;
  86. }
  87. button.html2mdButton.reTranslation {
  88. background-color: #faebd7;
  89. }
  90. .translate-problem-statement table {
  91. border: 1px #ccc solid;
  92. border-collapse: collapse;
  93. margin: 1.3571em 0 0;
  94. color: #222;
  95. }
  96. .translate-problem-statement table td {
  97. border-right: 1px solid #ccc;
  98. border-top: 1px solid #ccc;
  99. padding: 0.7143em 0.5em;
  100. }
  101. .translate-problem-statement table th {
  102. padding: 0.7143em 0.5em;
  103. }
  104. .translate-problem-statement p:not(:first-child) {
  105. margin: 1.5em 0 0;
  106. }
  107. /*设置面板*/
  108. button.html2mdButton.CFBetter_setting {
  109. float: right;
  110. height: 30px;
  111. background: #60a5fa;
  112. color: white;
  113. box-shadow: 0px 0px 1px 1px #0000004d;
  114. margin: 10px;
  115. }
  116. #CFBetter_setting_menu {
  117. z-index: 9999;
  118. border-radius: 0.5rem;
  119. box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  120. display: grid;
  121. position: fixed;
  122. top: 50%;
  123. left: 50%;
  124. width: 270px;
  125. transform: translate(-50%, -50%);
  126. border-radius: 16px;
  127. background-color: #ecf0ff;
  128. border: 6px solid #ffffff;
  129. color: #697e91;
  130. padding: 10px 20px 20px 20px;
  131. }
  132.  
  133. /*设置面板-关闭按钮*/
  134. #CFBetter_setting_menu .tool-box {
  135. position: absolute;
  136. display: flex;
  137. align-items: center;
  138. justify-content: center;
  139. width: 2.5rem;
  140. height: 2.5rem;
  141. top: 3px;
  142. right: 3px;
  143. }
  144.  
  145. #CFBetter_setting_menu .btn-close {
  146. display: flex;
  147. align-items: center;
  148. justify-content: center;
  149. text-align: center;
  150. padding: 10px;
  151. width: 2rem;
  152. height: 2rem;
  153. color: transparent;
  154. font-size: 0;
  155. cursor: pointer;
  156. background-color: #ff000080;
  157. border: none;
  158. border-radius: 10px;
  159. transition: .2s ease all;
  160. }
  161.  
  162. #CFBetter_setting_menu .btn-close:hover {
  163. width: 2rem;
  164. height: 2rem;
  165. font-size: 1rem;
  166. color: #ffffff;
  167. background-color: #ff0000cc;
  168. box-shadow: 0 5px 5px 0 #00000026;
  169. }
  170.  
  171. #CFBetter_setting_menu .btn-close:active {
  172. width: .9rem;
  173. height: .9rem;
  174. font-size: .9rem;
  175. color: #ffffffde;
  176. --shadow-btn-close: 0 3px 3px 0 #00000026;
  177. box-shadow: var(--shadow-btn-close);
  178. }
  179.  
  180. /*设置面板-checkbox*/
  181. #CFBetter_setting_menu input[type=checkbox]:focus {
  182. outline: 0px;
  183. }
  184.  
  185. #CFBetter_setting_menu input[type="checkbox"] {
  186. margin: 0px;
  187. appearance: none;
  188. width: 48px;
  189. height: 24px;
  190. border: 2px solid #6b8092;
  191. border-radius: 20px;
  192. background: #f1e1e1;
  193. position: relative;
  194. box-sizing: border-box;
  195. }
  196.  
  197. #CFBetter_setting_menu input[type="checkbox"]::before {
  198. content: "";
  199. width: 16px;
  200. height: 16px;
  201. background: #6b80927a;
  202. border: 2px solid #6b8092;
  203. border-radius: 50%;
  204. position: absolute;
  205. top: 0;
  206. left: 0;
  207. transform: translate(0%, 0%);
  208. transition: all 0.3s ease-in-out;
  209. }
  210.  
  211. #CFBetter_setting_menu input[type="checkbox"]::after {
  212. content: url("data:image/svg+xml,%3Csvg xmlns='://www.w3.org/2000/svg' width='23' height='23' viewBox='0 0 23 23' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M6.55021 5.84315L17.1568 16.4498L16.4497 17.1569L5.84311 6.55026L6.55021 5.84315Z' fill='%23EA0707' fill-opacity='0.89'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M17.1567 6.55021L6.55012 17.1568L5.84302 16.4497L16.4496 5.84311L17.1567 6.55021Z' fill='%23EA0707' fill-opacity='0.89'/%3E%3C/svg%3E");
  213. position: absolute;
  214. top: 0;
  215. left: 24px;
  216. }
  217.  
  218. #CFBetter_setting_menu input[type="checkbox"]:checked {
  219. border: 2px solid #02c202;
  220. background: #e2f1e1;
  221. }
  222.  
  223. #CFBetter_setting_menu input[type="checkbox"]:checked::before {
  224. background: rgba(2, 194, 2, 0.5);
  225. border: 2px solid #02c202;
  226. transform: translate(119%, 0%);
  227. transition: all 0.3s ease-in-out;
  228. }
  229.  
  230. #CFBetter_setting_menu input[type="checkbox"]:checked::after {
  231. content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='15' height='13' viewBox='0 0 15 13' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M14.8185 0.114533C15.0314 0.290403 15.0614 0.605559 14.8855 0.818454L5.00187 12.5L0.113036 6.81663C-0.0618274 6.60291 -0.0303263 6.2879 0.183396 6.11304C0.397119 5.93817 0.71213 5.96967 0.886994 6.18339L5.00187 11L14.1145 0.181573C14.2904 -0.0313222 14.6056 -0.0613371 14.8185 0.114533Z' fill='%2302C202' fill-opacity='0.9'/%3E%3C/svg%3E");
  232. position: absolute;
  233. top: 3px;
  234. left: 4px;
  235. }
  236.  
  237. #CFBetter_setting_menu input[type="checkbox"] + label {
  238. margin: 0px 0px 0px 10px !important;
  239. font-size: 16px;
  240. }
  241.  
  242. .CFBetter_setting_list {
  243. display: flex;
  244. align-items: center;
  245. margin-bottom: 18px;
  246. }
  247.  
  248. /*设置面板-radio*/
  249. #CFBetter_setting_menu>label {
  250. display: flex;
  251. list-style-type: none;
  252. padding-inline-start: 0px;
  253. overflow-x: auto;
  254. max-width: 100%;
  255. margin: 0px;
  256. align-items: center;
  257. margin: 3px 0px;
  258. }
  259.  
  260. .CFBetter_setting_menu_label_text {
  261. border: 1px dashed #00aeeccc;
  262. display: block;
  263. height: 20px;
  264. width: 100%;
  265. color: gray;
  266. font-weight: 300;
  267. font-size: 14px;
  268. letter-spacing: 2px;
  269. padding: 7px;
  270. }
  271.  
  272. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  273. background: #41e49930;
  274. border: 1px solid green;
  275. color: green;
  276. font-weight: 500;
  277. }
  278.  
  279. #CFBetter_setting_menu>label input[type="radio"] {
  280. -webkit-appearance: none;
  281. appearance: none;
  282. list-style: none;
  283. margin: 0px;
  284. }
  285.  
  286. #CFBetter_setting_menu input[type="text"] {
  287. display: block;
  288. height: 25px;
  289. background-color: #ffffff;
  290. color: #727378;
  291. font-size: 10px;
  292. border-radius: 0.3rem;
  293. padding: 1px 5px;
  294. margin: 5px 0px 5px 0px;
  295. border: 1px solid #00aeeccc;
  296. box-shadow: 0 0 1px #0000004d;
  297. }
  298.  
  299. .CFBetter_setting_menu_input {
  300. width: 100%;
  301. display: grid;
  302. justify-content: start;
  303. }
  304.  
  305. #CFBetter_setting_menu #save {
  306. cursor: pointer;
  307. display: inline-flex;
  308. padding: 0.5rem 1rem;
  309. background-color: #1aa06d;
  310. color: #ffffff;
  311. font-size: 1rem;
  312. line-height: 1.5rem;
  313. font-weight: 500;
  314. justify-content: center;
  315. width: 100%;
  316. border-radius: 0.375rem;
  317. border: none;
  318. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  319. }
  320.  
  321. #CFBetter_setting_menu span.tip {
  322. color: red;
  323. font-size: 2px;
  324. font-weight: 500;
  325. padding: 0px 0px 10px 0px;
  326. }
  327. /*更新检查*/
  328. div#update_panel {
  329. position: fixed;
  330. top: 50%;
  331. left: 50%;
  332. width: 240px;
  333. transform: translate(-50%, -50%);
  334. background-color: #fdfdfd;
  335. border: 1px solid #00aeeccc;
  336. border-radius: 5px;
  337. box-shadow: 2px 2px 3px 1px #0000004d;
  338. padding: 10px 20px 20px 20px;
  339. color: #444242;
  340. background-color: #ecf0ff;
  341. border: 6px solid #ffffff;
  342. border-radius: 16px;
  343. }
  344. div#update_panel #updating {
  345. cursor: pointer;
  346. display: inline-flex;
  347. padding: 0px;
  348. background-color: #1aa06d;
  349. color: #ffffff;
  350. font-size: 1rem;
  351. line-height: 1.5rem;
  352. font-weight: 500;
  353. justify-content: center;
  354. width: 100%;
  355. border-radius: 0.375rem;
  356. border: none;
  357. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  358. }
  359. div#update_panel #updating a {
  360. text-decoration: none;
  361. color: white;
  362. display: flex;
  363. position: inherit;
  364. top: 0;
  365. left: 0;
  366. width: 100%;
  367. height: 22px;
  368. font-size: 14px;
  369. justify-content: center;
  370. align-items: center;
  371. }
  372. `);
  373.  
  374. // 更新检查
  375. (function checkScriptVersion() {
  376. function compareVersions(version1 = "0", version2 = "0") {
  377. const v1Array = String(version1).split(".");
  378. const v2Array = String(version2).split(".");
  379. const minLength = Math.min(v1Array.length, v2Array.length);
  380. let result = 0;
  381. for (let i = 0; i < minLength; i++) {
  382. const curV1 = Number(v1Array[i]);
  383. const curV2 = Number(v2Array[i]);
  384. if (curV1 > curV2) {
  385. result = 1;
  386. break;
  387. } else if (curV1 < curV2) {
  388. result = -1;
  389. break;
  390. }
  391. }
  392. if (result === 0 && v1Array.length !== v2Array.length) {
  393. const v1IsBigger = v1Array.length > v2Array.length;
  394. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  395. for (let i = minLength; i < maxLenArray.length; i++) {
  396. const curVersion = Number(maxLenArray[i]);
  397. if (curVersion > 0) {
  398. v1IsBigger ? result = 1 : result = -1;
  399. break;
  400. }
  401. }
  402. }
  403. return result;
  404. }
  405.  
  406. GM_xmlhttpRequest({
  407. method: "GET",
  408. url: "https://greasyfork.org/zh-CN/scripts/465777.json",
  409. timeout: 10 * 1e3,
  410. onload: function (response) {
  411. const scriptData = JSON.parse(response.responseText);
  412. if (scriptData.name === GM_info.script.name && compareVersions(scriptData.version, GM_info.script.version) === 1) {
  413. $("body").append(`
  414. <div id='update_panel'>
  415. <h3>${GM_info.script.name}有新版本!</h3>
  416. <hr>
  417. <div class='update_panel_menu'>
  418. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  419. </div>
  420. <br>
  421. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  422. </div>
  423. `);
  424. }
  425. }
  426. });
  427. })();
  428.  
  429. // 汉化替换
  430. (function () {
  431. if (GM_getValue("bottomZh_CN") === ''||GM_getValue("bottomZh_CN") === undefined) GM_setValue("bottomZh_CN", true);
  432. if (GM_getValue("bottomZh_CN") != true) return;
  433. // 设置语言为zh
  434. var htmlTag = document.getElementsByTagName("html")[0];
  435. htmlTag.setAttribute("lang", "zh-CN");
  436.  
  437. // 文本节点遍历替换
  438. $(document).ready(function () {
  439. function traverseTextNodes(node, rules) {
  440. if (!node) return;
  441. if (node.nodeType === Node.TEXT_NODE) {
  442. rules.forEach(rule => {
  443. const regex = new RegExp(rule.match, 'g');
  444. node.textContent = node.textContent.replace(regex, rule.replace);
  445. });
  446. } else {
  447. $(node).contents().each((_, child) => traverseTextNodes(child, rules));
  448. }
  449. }
  450. const rules1 = [
  451. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  452. { match: 'Enter', replace: '进入' },
  453. { match: 'Current standings', replace: '当前榜单' },
  454. { match: 'Final standings', replace: '最终榜单' },
  455. { match: 'Preliminary results', replace: '初步结果' },
  456. { match: 'open hacking:', replace: '公开黑客攻击中(即尝试提交数据加强,对已通过的代码重测)' },
  457. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  458. { match: 'Official School Contest', replace: '学校官方比赛' },
  459. { match: 'Training Contest', replace: '训练赛' },
  460. { match: 'Training Camp Contest', replace: '训练营比赛' },
  461. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  462. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  463. { match: 'China', replace: '中国' },
  464. { match: 'Statements', replace: '题目描述' },
  465. { match: 'in Chinese', replace: '中文' },
  466. { match: 'Trainings', replace: '训练' },
  467. { match: 'Prepared by', replace: '编写人' },
  468. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  469. { match: 'Past contests', replace: '过去的比赛' },
  470. { match: 'Exclusions', replace: '排除' },
  471. { match: 'Before start', replace: '还有' },
  472. { match: 'Before registration', replace: '报名还有' },
  473. { match: 'Until closing ', replace: '距报名结束还有' },
  474. { match: 'Register', replace: '报名' },
  475. { match: 'Registration completed', replace: '已报名' },
  476. { match: 'Problems', replace: '问题集' },
  477. { match: 'Questions about problems', replace: '关于问题的提问' },
  478. { match: 'Contest status', replace: '比赛状态' },
  479. ];
  480. traverseTextNodes($('.datatable'), rules1);
  481.  
  482. const rules2 = [
  483. { match: 'Home', replace: '主页' },
  484. { match: 'Top', replace: '热门' },
  485. { match: 'Catalog', replace: '指南目录' },
  486. { match: 'Contests', replace: '比赛' },
  487. { match: 'Gym', replace: '训练营(过去的大型比赛)' },
  488. { match: 'Problemset', replace: '题单' },
  489. { match: 'Groups', replace: '团体' },
  490. { match: 'Rating', replace: '积分榜' },
  491. { match: 'Edu', replace: '培训' },
  492. { match: 'Calendar', replace: '日历' },
  493. { match: 'Help', replace: '帮助' }
  494. ];
  495. traverseTextNodes($('.menu-list.main-menu-list'), rules2);
  496.  
  497. const rules3 = [
  498. { match: 'Settings', replace: '设置' },
  499. { match: 'Blog', replace: '博客' },
  500. { match: 'Teams', replace: '队伍' },
  501. { match: 'Submissions', replace: '提交' },
  502. { match: 'Favourites', replace: '收藏' },
  503. { match: 'Talks', replace: '私信' },
  504. { match: 'Contests', replace: '比赛' },
  505. ];
  506. traverseTextNodes($('.nav-links'), rules3);
  507.  
  508. const rules4 = [
  509. { match: 'Before contest', replace: '即将进行的比赛' },
  510. { match: 'Contest is running', replace: '比赛进行中' },
  511. ];
  512. traverseTextNodes($('.contest-state-phase'), rules4);
  513.  
  514. const rules5 = [
  515. { match: 'has extra registration', replace: '有额外的报名时期' },
  516. { match: 'If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes.', replace: '如果您在比赛开始前5分钟前还未报名,您可以在额外的报名期间稍后报名。额外的报名将在比赛开始后10分钟开放,并持续25分钟。' },
  517. ];
  518. traverseTextNodes($('.notice'), rules5);
  519.  
  520. const rules6 = [
  521. { match: 'Contribution', replace: '贡献' },
  522. ];
  523. traverseTextNodes($('.propertyLinks'), rules6);
  524.  
  525. const rules7 = [
  526. { match: 'Contest history', replace: '比赛历史' },
  527. ];
  528. traverseTextNodes($('.contests-table'), rules7);
  529.  
  530. const rules8 = [
  531. { match: 'Register now', replace: '现在报名' },
  532. ];
  533. traverseTextNodes($('.roundbox.sidebox.borderTopRound '), rules8);
  534.  
  535. const rules9 = [
  536. { match: 'Add to exclusions', replace: '添加到排除列表' },
  537. ];
  538. traverseTextNodes($('.icon-eye-close.icon-large'), rules9);
  539.  
  540. const rules10 = [
  541. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  542. ];
  543. traverseTextNodes($("._ContestFilterExclusionsManageFrame_addExclusionLink"), rules10);
  544.  
  545. const rules11 = [
  546. { match: 'Announcement', replace: '公告' },
  547. { match: 'Statements', replace: '统计报表' },
  548. { match: 'Tutorial', replace: '题解' },
  549. ];
  550. traverseTextNodes($('.roundbox.sidebox.sidebar-menu.borderTopRound '), rules11);
  551.  
  552. const rules12 = [
  553. { match: 'Problems', replace: '问题' },
  554. { match: 'Submit Code', replace: '提交代码' },
  555. { match: 'My Submissions', replace: '我的提交' },
  556. { match: 'Status', replace: '状态' },
  557. { match: 'Standings', replace: '榜单' },
  558. { match: 'Custom Invocation', replace: '自定义调试' },
  559. { match: 'Common standings', replace: '全部排行' },
  560. { match: 'Friends standings', replace: '只看朋友' },
  561. { match: 'Submit', replace: '提交' },
  562. { match: 'Hacks', replace: '黑客' },
  563. { match: 'Room', replace: '房间' },
  564. { match: 'Custom test', replace: '自定义测试' },
  565. { match: 'Blog', replace: '博客' },
  566. { match: 'Teams', replace: '队伍' },
  567. { match: 'Submissions', replace: '提交' },
  568. { match: 'Groups', replace: '团体' },
  569. { match: 'Favourites', replace: '收藏' },
  570. { match: 'Contests', replace: '比赛' },
  571. { match: '问题etting', replace: '参与编写的问题' },
  572. { match: 'Gym', replace: '训练营' },
  573. { match: 'Mashups', replace: '组合混搭' },
  574. { match: 'Posts', replace: '帖子' },
  575. { match: '>Comments<', replace: '>回复<' },
  576. { match: 'Main', replace: '主要' },
  577. { match: 'Settings', replace: '设置' },
  578. { match: 'Lists', replace: '列表' },
  579. { match: 'General', replace: '基本' },
  580. { match: 'Sidebar', replace: '侧边栏' },
  581. { match: 'Social', replace: '社会信息' },
  582. { match: 'Address', replace: '地址' },
  583. { match: 'Wallets', replace: '钱包' },
  584. { match: 'Talks', replace: '对话' },
  585. { match: 'Dialogues', replace: '对话' },
  586. ];
  587. traverseTextNodes($('.second-level-menu'), rules12);
  588.  
  589. const rules13 = [
  590. { match: 'Expand', replace: '展开' }
  591. ];
  592. traverseTextNodes($('.topic-toggle-collapse'), rules13);
  593.  
  594. const rules14 = [
  595. { match: 'Full text and comments', replace: '阅读全文/评论' }
  596. ];
  597. traverseTextNodes($('.topic-read-more'), rules14);
  598.  
  599. const rules15 = [
  600. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' }
  601. ];
  602. traverseTextNodes($('.toggleEditorCheckboxLabel'), rules15);
  603.  
  604. const rules16 = [
  605. { match: 'Registration for the contest', replace: '比赛报名' }
  606. ];
  607. traverseTextNodes($('.submit'), rules16);
  608.  
  609. const rules17 = [
  610. { match: 'Difficulty:', replace: '难度:' },
  611. ];
  612. traverseTextNodes($('._FilterByTagsFrame_difficulty'), rules17);
  613.  
  614. const rules18 = [
  615. { match: 'Add tag', replace: '添加标签' }
  616. ];
  617. traverseTextNodes($('._FilterByTagsFrame_addTagLink'), rules18);
  618.  
  619. const rules19 = [
  620. { match: 'Reminder: in case of any technical issues, you can use the lightweight website', replace: '提醒:如果出现任何技术问题,您可以使用轻量网站' }
  621. ];
  622. traverseTextNodes($('.alert'), rules19);
  623.  
  624. const rules20 = [
  625. { match: 'Enter', replace: '登录' },
  626. { match: 'Register', replace: '注册' },
  627. { match: 'Logout', replace: '退出登录' }
  628. ];
  629. traverseTextNodes($('.lang-chooser'), rules20);
  630. });
  631. // 元素选择替换
  632. // 侧栏titled汉化
  633. (function () {
  634. var translations = {
  635. "Pay attention": "→ 注意",
  636. "Top rated": "→ 评级排行",
  637. "Top contributors": "→ 贡献者排行",
  638. "Find user": "→ 查找用户",
  639. "Recent actions": "→ 最新动态",
  640. "Training filter": "→ 过滤筛选",
  641. "Find training": "→ 搜索比赛/问题",
  642. "Virtual participation": "→ 什么是虚拟参赛",
  643. "Contest materials": "→ 比赛相关资料",
  644. "Settings": "→ 设置",
  645. "Clone Contest to Mashup": "→ Clone比赛到组合混搭",
  646. "Submit": "→ 提交",
  647. "Practice": "→ 练习",
  648. "Problem tags": "→ 问题标签",
  649. "Filter Problems": "→ 过滤问题",
  650. "Attention": "→ 注意",
  651. "About Contest": "→ 关于比赛",
  652. "Last submissions": "→ 提交历史",
  653. "Streams": "→ 直播",
  654. "Coach rights": "→ 教练权限",
  655. "Advices to fill address": "→ 填写地址的建议",
  656. "Hacks filter": "→ 黑客过滤器",
  657. "Score table": "→ 评分表",
  658. "Login into Codeforces": "登录 Codeforces",
  659. };
  660.  
  661. $(".caption.titled").each(function () {
  662. var tag = $(this).text();
  663. for (var property in translations) {
  664. if (tag.match(property)) {
  665. $(this).addClass(property);
  666. $(this).text(translations[property]);
  667. break;
  668. }
  669. }
  670. });
  671. })();
  672. // 题目Tag汉化
  673. (function () {
  674. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  675. var selectElement = parentElement.find('select');
  676. var translations = {
  677. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  678. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  679. "2-sat": "二分图可满足性问题(2-sat)",
  680. "binary search": "二分搜索(binary search)",
  681. "bitmasks": "位掩码(bitmasks)",
  682. "brute force": "暴力枚举(brute force)",
  683. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  684. "combinatorics": "组合数学(combinatorics)",
  685. "constructive algorithms": "构造算法(constructive algorithms)",
  686. "data structures": "数据结构(data structures)",
  687. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  688. "divide and conquer": "分治算法(divide and conquer)",
  689. "dp": "动态规划(dp)",
  690. "dsu": "并查集(dsu)",
  691. "expression parsing": "表达式解析(expression parsing)",
  692. "fft": "快速傅里叶变换(fft)",
  693. "flows": "流(flows)",
  694. "games": "博弈论(games)",
  695. "geometry": "计算几何(geometry)",
  696. "graph matchings": "图匹配(graph matchings)",
  697. "graphs": "图论(graphs)",
  698. "greedy": "贪心策略(greedy)",
  699. "hashing": "哈希表(hashing)",
  700. "implementation": "实现问题,编程技巧,模拟(implementation)",
  701. "interactive": "交互性问题(interactive)",
  702. "math": "数学(math)",
  703. "matrices": "矩阵(matrices)",
  704. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  705. "number theory": "数论(number theory)",
  706. "probabilities": "概率论(probabilities)",
  707. "schedules": "调度算法(schedules)",
  708. "shortest paths": "最短路算法(shortest paths)",
  709. "sortings": "排序算法(sortings)",
  710. "string suffix structures": "字符串后缀结构(string suffix structures)",
  711. "strings": "字符串处理(strings)",
  712. "ternary search": "三分搜索(ternary search)",
  713. "trees": "树形结构(trees)",
  714. "two pointers": "双指针算法(two pointers)"
  715. };
  716. selectElement.find("option").each(function () {
  717. var optionValue = $(this).val();
  718. if (translations[optionValue]) {
  719. $(this).text(translations[optionValue]);
  720. }
  721. });
  722. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  723. var tag = $(this).text();
  724. if (tag in translations) {
  725. $(this).text(translations[tag]);
  726. }
  727. });
  728. $(".notice").each(function () {
  729. var tag = $(this).text();
  730. if (tag in translations) {
  731. $(this).text(translations[tag]);
  732. }
  733. });
  734. $(".tag-box").each(function () {
  735. var tag = $(this).text();
  736. for (var property in translations) {
  737. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  738. if (tag.match(property)) {
  739. $(this).text(translations[property]);
  740. break;
  741. }
  742. }
  743. });
  744. })();
  745. // 题目过滤器选项汉化
  746. (function () {
  747. var parentElement = $('#gym-filter-form');
  748. var selectElement = parentElement.find('div');
  749. var translations = {
  750. "Contest type:": "比赛类型:",
  751. "ICPC region:": "ICPC地区:",
  752. "Contest format:": "比赛形式:",
  753. "Order by:": "排序方式:",
  754. "Secondary order by:": "次要排序方式:",
  755. "Hide, if participated:": "隐藏我参加过的:",
  756. };
  757. selectElement.find("label").each(function () {
  758. var optionValue = $(this).text();
  759. if (translations[optionValue]) {
  760. $(this).text(translations[optionValue]);
  761. }
  762. });
  763. translations = {
  764. "Season:": "时间范围(年度)",
  765. "Duration, hours:": "持续时间(小时):",
  766. "Difficulty:": "难度:"
  767. };
  768. selectElement.each(function () {
  769. var optionValue = $(this).text();
  770. if (translations[optionValue]) {
  771. $(this).text(translations[optionValue]);
  772. }
  773. });
  774. })();
  775. (function () {
  776. var parentElement = $('.setting-value');
  777. var selectElement = parentElement.find('select');
  778. var translations = {
  779. "Official ACM-ICPC Contest": "ICPC官方比赛",
  780. "Official School Contest": "学校官方比赛",
  781. "Opencup Contest": "Opencup比赛",
  782. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  783. "Training Camp Contest": "训练营比赛",
  784. "Official International Personal Contest": "官方国际个人赛",
  785. "Training Contest": "训练比赛",
  786. "ID_ASC": "创建时间(升序)",
  787. "ID_DESC": "创建时间(降序)",
  788. "RATING_ASC": "评分(升序)",
  789. "RATING_DESC": "评分(降序)",
  790. "DIFFICULTY_ASC": "难度(升序)",
  791. "DIFFICULTY_DESC": "难度(降序)",
  792. "START_TIME_ASC": "开始时间(升序)",
  793. "START_TIME_DESC": "开始时间(降序)",
  794. "DURATION_ASC": "持续时间(升序)",
  795. "DURATION_DESC": "持续时间(降序)",
  796. "POPULARITY_ASC": "热度(升序)",
  797. "POPULARITY_DESC": "热度(降序)",
  798. "UPDATE_TIME_ASC": "更新时间(升序)",
  799. "UPDATE_TIME_DESC": "更新时间(降序)"
  800. };
  801. selectElement.find("option").each(function () {
  802. var optionValue = $(this).val();
  803. if (translations[optionValue]) {
  804. $(this).text(translations[optionValue]);
  805. }
  806. });
  807. parentElement = $('.setting-last-value');
  808. selectElement = parentElement.find('select');
  809. selectElement.find("option").each(function () {
  810. var optionValue = $(this).val();
  811. if (translations[optionValue]) {
  812. $(this).text(translations[optionValue]);
  813. }
  814. });
  815. })();
  816. // 右侧sidebox通用汉化
  817. (function () {
  818. var parentElement = $('.sidebox');
  819. var selectElement = parentElement.find('div');
  820. var translations = {
  821. "Show tags for unsolved problems": "显示未解决问题的标签",
  822. "Hide solved problems": "隐藏已解决的问题",
  823. };
  824. selectElement.find("label").each(function () {
  825. var optionValue = $(this).text();
  826. if (translations[optionValue]) {
  827. $(this).text(translations[optionValue]);
  828. }
  829. });
  830. })();
  831. // 表单字段名汉化
  832. (function () {
  833. var translations = {
  834. "Problem:": "题目:",
  835. "Language:": "语言:",
  836. "Source code:": "源代码:",
  837. "Or choose file:": "或者选择文件:",
  838. "Choose file:": "选择文件:",
  839. "Notice:": "注意:",
  840. "virtual participation:": "虚拟参与:",
  841. "Registration for the contest:": "比赛报名:",
  842. "Take part:": "参与:",
  843. "as individual participant:": "作为个人参与者:",
  844. "as a team member:": "作为团队成员:",
  845. "Virtual start time:": "虚拟开始时间:",
  846. "Complete problemset:": "完整的问题集:",
  847. "First name (English)": "名字(英文)",
  848. "Last name (English)": "姓氏(英文)",
  849. "First name (Native)": "名字(本地语言)",
  850. "Last name (Native)": "姓氏(本地语言)",
  851. "Birth date": "出生日期",
  852. "Country": "国家",
  853. "City": "城市",
  854. "Organization": "组织",
  855. "Handle/Email": "账号/邮箱",
  856. "Password": "密码",
  857. };
  858. $(".field-name").each(function () {
  859. var optionValue = $(this).text();
  860. if (translations[optionValue]) {
  861. $(this).text(translations[optionValue]);
  862. }
  863. });
  864. })();
  865. (function () {
  866. var translations = {
  867. "Terms of agreement:": "协议条款:",
  868. "Choose team:": "选择团队:"
  869. };
  870. $(".field-name label").each(function () {
  871. var optionValue = $(this).text();
  872. if (translations[optionValue]) {
  873. $(this).text(translations[optionValue]);
  874. }
  875. });
  876. })();
  877. (function () {
  878. var translations = {
  879. "Hide sidebar block \"Find user\"": "隐藏侧边栏块“查找用户”",
  880. "Hide sidebar block \"Current user\"": "隐藏侧边栏块“当前用户”",
  881. "Hide sidebar block \"Recent аctions\"": "隐藏侧边栏块“最新动态”",
  882. "Hide sidebar block \"Favourite groups\"": "隐藏侧边栏块“收藏组”",
  883. "Hide sidebar block \"Top contributors\"": "隐藏侧边栏块“贡献者排行”",
  884. "Hide sidebar block \"Top rated\"": "隐藏侧边栏块“评级排行”",
  885. "Hide sidebar block \"Streams\"": "隐藏侧边栏块“直播”",
  886. "Old password": "旧密码",
  887. "New password": "新密码",
  888. "Confirm new password": "确认新密码",
  889. "Contest email notification": "比赛邮件通知",
  890. "Send email on new user talk": "在有新用户对话时发送电子邮件",
  891. "Send email on new comment": "在有新评论时发送电子邮件",
  892. "Hide contact information": "隐藏联系人信息",
  893. "Remember me by Gmail, Facebook and etc": "通过 Gmail、Facebook 等记住我",
  894. "Show tags for unsolved problems": "显示未解决问题的标签",
  895. "Hide solved problems from problemset": "从问题集中隐藏已解决的问题",
  896. "Hide low rated blogs": "隐藏评级较低的博客",
  897. "Offer to publish great rating rises": "提供展示Rating显著提升的机会",
  898. "Enforce https": "强制 HTTPS",
  899. "Show private activity in the profile": "在个人资料中显示私人活动",
  900. "Show diagnostics": "显示诊断信息"
  901. };
  902. $(".field-name").each(function () {
  903. var tag = $(this).text();
  904. for (var property in translations) {
  905. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  906. if (tag.match(property)) {
  907. $(this).text(translations[property]);
  908. break;
  909. }
  910. }
  911. });
  912. })();
  913. (function () {
  914. var translations = {
  915. "Postal/zip code": "邮政编码/邮编",
  916. "Country (English)": "国家(英文)",
  917. "State (English)": "州/省份(英文)",
  918. "City (English)": "城市(英文)",
  919. "Address (English)": "地址(英文)",
  920. "Recipient (English)": "收件人姓名(英文)",
  921. "Country (Native)": "国家(本地语言)",
  922. "State (Native)": "州/省份(本地语言)",
  923. "City (Native)": "城市(本地语言)",
  924. "Address (Native)": "地址(本地语言)",
  925. "Recipient (Native)": "收件人姓名(本地语言)",
  926. "Phone": "电话",
  927. "TON Wallet:": "TON 钱包:",
  928. "Secret Code:": "验证码:"
  929. };
  930. $("td.field-name label").each(function () {
  931. var optionValue = $(this).text();
  932. if (translations[optionValue]) {
  933. $(this).text(translations[optionValue]);
  934. }
  935. });
  936. })();
  937.  
  938. // 按钮汉化input[type="submit"]
  939. (function () {
  940. var translations = {
  941. "Register for virtual participation": "报名虚拟参赛",
  942. "Apply": "应用",
  943. "Register": "报名",
  944. "Login": "登录"
  945. };
  946. $('input[type="submit"]').each(function () {
  947. var optionValue = $(this).val();
  948. if (translations[optionValue]) {
  949. $(this).val(translations[optionValue]);
  950. }
  951. });
  952. })();
  953. (function () {
  954. var translations = {
  955. "Reset": "重置",
  956. };
  957. $('input[type="button"]').each(function () {
  958. var optionValue = $(this).val();
  959. if (translations[optionValue]) {
  960. $(this).val(translations[optionValue]);
  961. }
  962. });
  963. })();
  964.  
  965. // 选项汉化input[type="radio"]
  966. (function () {
  967. var translations = {
  968. "as individual participant": "个人",
  969. "as a team member": "作为一个团队成员",
  970. };
  971. $('input[type="radio"]').each(function () {
  972. var tag = $(this).parent().contents().filter(function() {
  973. return this.nodeType === Node.TEXT_NODE;
  974. });
  975. for (var i = 0; i < tag.length; i++) {
  976. var text = tag[i].textContent.trim();
  977. if (translations.hasOwnProperty(text)) {
  978. $(this).addClass(text);
  979. tag[i].replaceWith(translations[text]);
  980. break;
  981. }
  982. }
  983. });
  984. })();
  985.  
  986.  
  987. // 杂项汉化
  988. (function () {
  989. var translations = {
  990. "(standard input\/output)": "标准输入/输出",
  991. };
  992. $("div.notice").each(function () {
  993. var tag = $(this).children().eq(0).text();
  994. for (var property in translations) {
  995. if (tag.match(property)) {
  996. $(this).children().eq(0).text(translations[property]);
  997. break;
  998. }
  999. }
  1000. });
  1001. })();
  1002. (function () {
  1003. var translations = {
  1004. "Ask a question": "提一个问题",
  1005. };
  1006. $(".ask-question-link").each(function () {
  1007. var optionValue = $(this).text();
  1008. if (translations[optionValue]) {
  1009. $(this).text(translations[optionValue]);
  1010. }
  1011. });
  1012. })();
  1013. })();
  1014.  
  1015. // 设置面板
  1016.  
  1017. $("div[class='lang-chooser']").each(function () {
  1018. $(this).before(
  1019. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  1020. );
  1021. });
  1022. $(document).ready(function () {
  1023. $(".CFBetter_setting").click(function () {
  1024. $(".CFBetter_setting").attr("disabled", true);
  1025. $(".CFBetter_setting").css("background-color", "#e6e6e6");
  1026. $(".CFBetter_setting").css("color", "#727378");
  1027. $(".CFBetter_setting").css("cursor", "not-allowed");
  1028. $("body").append(`
  1029. <div id='CFBetter_setting_menu'>
  1030. <div class="tool-box">
  1031. <button class="btn-close">×</button>
  1032. </div>
  1033. <h3>基本设置</h3>
  1034. <hr>
  1035. <div class='CFBetter_setting_list'>
  1036. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN" checked>
  1037. <label for="bottomZh_CN">界面汉化</label>
  1038. </div>
  1039. <h3>翻译设置</h3>
  1040. <hr>
  1041. <label>
  1042. <input type='radio' name='translation' value='deepl'>
  1043. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  1044. </label>
  1045. <label>
  1046. <input type='radio' name='translation' value='youdao'>
  1047. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  1048. </label>
  1049. <label>
  1050. <input type='radio' name='translation' value='openai'>
  1051. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)</span>
  1052. </label>
  1053. <label>
  1054. <input type='radio' name='translation' value='api2d'>
  1055. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)</span>
  1056. </label><br>
  1057. <div class='CFBetter_setting_menu_input' id='baidu' style='display: none;'>
  1058. <label for='baidu_uid'>APP ID:</label><input type='text' id='baidu_uid'>
  1059. <label for='baidu_key'>KEY:</label><input type='text' id='baidu_key'>
  1060. </div>
  1061. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  1062. <span class ='tip'>提示:<br>请确保你能够正常访问OpenAIapi<br></span>
  1063. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成,</span>
  1064. <span class ='tip'>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></span>
  1065. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  1066. </div>
  1067. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  1068. <span class ='tip'>提示:<br>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳<br></span>
  1069. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成<br></span>
  1070. <span class ='tip'>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></span>
  1071. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  1072. </div>
  1073. <br>
  1074. <button id='save'>保存</button>
  1075. </div>
  1076. `);
  1077. var translation = GM_getValue("translation");
  1078. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  1079. if (!translation) {
  1080. GM_setValue("translation", "deepl");
  1081. $("input[name='translation'][value='deepl']").prop("checked", true);
  1082. } else {
  1083. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  1084. $("input[name='translation']").css("color", "gray");
  1085. if (translation == "baidu") {
  1086. $("#baidu").show();
  1087. $("#baidu_uid").val(GM_getValue("baidu_uid"));
  1088. $("#baidu_key").val(GM_getValue("baidu_key"));
  1089. $("#baidu_uid").css("color", "gray");
  1090. $("#baidu_key").css("color", "gray");
  1091. } else if (translation == "openai") {
  1092. $("#openai").show();
  1093. $("#openai_key").val(GM_getValue("openai_key"));
  1094. $("#openai_key").css("color", "gray");
  1095. } else if (translation == "api2d") {
  1096. $("#api2d").show();
  1097. $("#api2d_key").val(GM_getValue("api2d_key"));
  1098. $("#api2d_key").css("color", "gray");
  1099. }
  1100. }
  1101.  
  1102.  
  1103. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  1104. $("input[name='translation']").change(function () {
  1105. var selected = $(this).val(); // 获取当前选中的值
  1106. if (selected === "baidu") {
  1107. $("#baidu").show();
  1108. $("#baidu_uid").val(GM_getValue("baidu_uid"));
  1109. $("#baidu_key").val(GM_getValue("baidu_key"));
  1110. $("#openai, #api2d").hide();
  1111. } else if (selected === "openai") {
  1112. $("#openai").show();
  1113. $("#openai_key").val(GM_getValue("openai_key"));
  1114. $("#baidu, #api2d").hide();
  1115. } else if (selected === "api2d") {
  1116. $("#api2d").show();
  1117. $("#api2d_key").val(GM_getValue("api2d_key"));
  1118. $("#baidu, #openai").hide();
  1119. } else {
  1120. $("#baidu, #openai, #api2d").hide();
  1121. }
  1122. });
  1123.  
  1124.  
  1125. $("#save").click(function () {
  1126. var translation = $("input[name='translation']:checked").val();
  1127. var baidu_uid = $("#baidu_uid").val();
  1128. var baidu_key = $("#baidu_key").val();
  1129. var openai_key = $("#openai_key").val();
  1130. var api2d_key = $("#api2d_key").val();
  1131. GM_setValue("translation", translation);
  1132. if (translation == "baidu") {
  1133. GM_setValue("baidu_uid", baidu_uid);
  1134. GM_setValue("baidu_key", baidu_key);
  1135. } else if (translation == "openai") {
  1136. GM_setValue("openai_key", openai_key);
  1137. } else if (translation == "api2d") {
  1138. GM_setValue("api2d_key", api2d_key);
  1139. }
  1140. GM_setValue("bottomZh_CN", $("#bottomZh_CN").prop("checked"));
  1141. location.reload();
  1142.  
  1143. /* 切换汉化
  1144. if(JSON.parse(GM_getValue("bottomZh_CN")) != $("#bottomZh_CN").prop("checked")){
  1145. GM_setValue("bottomZh_CN", $("#bottomZh_CN").prop("checked"), 3650);
  1146. location.reload();
  1147. }else{
  1148. $("#CFBetter_setting_menu .btn-close").click();
  1149. }*/
  1150. });
  1151.  
  1152. // 关闭
  1153. $("#CFBetter_setting_menu .btn-close").click(function () {
  1154. $("#CFBetter_setting_menu").remove();
  1155. $(".CFBetter_setting").attr("disabled", false);
  1156. $(".CFBetter_setting").css("background-color", "#60a5fa");
  1157. $(".CFBetter_setting").css("color", "white");
  1158. $(".CFBetter_setting").css("cursor", "pointer");
  1159. });
  1160. });
  1161. });
  1162.  
  1163. // 是否为旧的latex渲染
  1164. var is_oldLatex = false;
  1165. if ($('.tex-span').length) {
  1166. is_oldLatex = true;
  1167. var newElement = $("<div></div>").addClass("alert alert-warning").html(`
  1168. 注意:当前页面存在使用非 MathJax 库渲染为 HTML Latex 公式(这通常是一道古老的题目),这导致 CodeforcesBetter 无法将其还原回 Latex,因此当前页面部分功能不适用。
  1169. <br>此外当前页面的翻译功能采用了特别的实现方式,因此可能会出现排版错位的情况。
  1170. `).css({
  1171. "margin": "1em",
  1172. "text-align": "center",
  1173. "position": "relative"
  1174. });
  1175. $(".menu-box:first").next().after(newElement);
  1176. }
  1177.  
  1178. // md2html转换/处理规则
  1179. var turndownService = new TurndownService({bulletListMarker: '-'});
  1180. var turndown = turndownService.turndown;
  1181.  
  1182. // 保留原始
  1183. turndownService.keep(['del']);
  1184.  
  1185. // 丢弃
  1186. turndownService.addRule('ignore-sample-tests', {
  1187. filter: function (node) {
  1188. return node.classList.contains('sample-tests') || node.classList.contains('header');
  1189. },
  1190. replacement: function (content, node) {
  1191. return "";
  1192. }
  1193. });
  1194. turndownService.addRule('remove-script', {
  1195. filter: function (node, options) {
  1196. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  1197. },
  1198. replacement: function (content, node) {
  1199. return "";
  1200. }
  1201. });
  1202.  
  1203. // inline math
  1204. turndownService.addRule('inline-math', {
  1205. filter: function (node, options) {
  1206. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  1207. },
  1208. replacement: function (content, node) {
  1209. return "$ " + $(node).next().text() + " $";
  1210. }
  1211. });
  1212.  
  1213. // block math
  1214. turndownService.addRule('block-math', {
  1215. filter: function (node, options) {
  1216. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  1217. },
  1218. replacement: function (content, node) {
  1219. return "\n$$\n" + $(node).next().text() + "\n$$\n";
  1220. }
  1221. });
  1222.  
  1223. // 表格
  1224. turndownService.addRule('bordertable', {
  1225. filter: 'table',
  1226. replacement: function (content, node) {
  1227. if (node.classList.contains('bordertable')) {
  1228. var output = [],
  1229. thead = '',
  1230. trs = node.querySelectorAll('tr');
  1231. if (trs.length > 0) {
  1232. var ths = trs[0].querySelectorAll('th');
  1233. if (ths.length > 0) {
  1234. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1235. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1236. }
  1237. }
  1238. var rows = node.querySelectorAll('tr');
  1239. Array.from(rows).forEach(function (row, i) {
  1240. if (i > 0) {
  1241. var cells = row.querySelectorAll('td,th');
  1242. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1243. output.push(trow);
  1244. }
  1245. });
  1246. return thead + output.join('\n');
  1247. } else {
  1248. return content;
  1249. }
  1250. }
  1251. });
  1252.  
  1253. // 题目markdown转换/翻译面板
  1254. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1255. if (type === "upper_level_2" || type === "problem") {
  1256. $(parent).children(':eq(1)').before(
  1257. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  1258. } else if (is_simple) {
  1259. $(parent).before(
  1260. "<div class='html2md-panel'><button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  1261. } else {
  1262. $(parent).before(
  1263. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  1264. }
  1265. }
  1266. function addButtonWithHTML2MD(parent, suffix, type) {
  1267. if(is_oldLatex){
  1268. $(".html2md-view" + suffix).css({
  1269. "cursor": "not-allowed",
  1270. "background-color": "#e6e6e638",
  1271. "color": "#72737896",
  1272. });
  1273. $(".html2md-view" + suffix).prop("disabled", true);
  1274. }
  1275. $(".html2md-view" + suffix).click(function () {
  1276. var target, removedChildren;
  1277. if (type === "problem") {
  1278. target = $(parent).children().next().next().get(0);
  1279. } else if (type === "problem_QA") {
  1280. target = $(this).parent().parent().get(0);
  1281. removedChildren = $(this).parent().parent().children().eq(0).detach();
  1282. } else if (type === "upper_level_2") {
  1283. target = parent;
  1284. removedChildren = $(parent).children().slice(0, 2).detach();
  1285. } else {
  1286. target = parent;
  1287. }
  1288. if (target.viewmd) {
  1289. target.viewmd = false;
  1290. $(this).text("MarkDown视图");
  1291. $(this).removeClass("mdViewed");
  1292. $(target).html(target.original_html);
  1293. } else {
  1294. target.viewmd = true;
  1295. if (!target.original_html) {
  1296. target.original_html = $(target).html();
  1297. }
  1298. if (!target.markdown) {
  1299. target.markdown = turndownService.turndown($(target).html());
  1300. }
  1301. $(this).text("原始内容");
  1302. $(this).addClass("mdViewed");
  1303. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1304. }
  1305. // 恢复删除的元素
  1306. if (type === "problem_QA" || type === "upper_level_2") $(target).prepend(removedChildren);
  1307. });
  1308. }
  1309.  
  1310. function addButtonWithCopy(parent, suffix, type) {
  1311. if(is_oldLatex){
  1312. $(".html2md-cb" + suffix).css({
  1313. "cursor": "not-allowed",
  1314. "background-color": "#e6e6e638",
  1315. "color": "#72737896",
  1316. });
  1317. $(".html2md-cb" + suffix).prop("disabled", true);
  1318. }
  1319. $(".html2md-cb" + suffix).click(function () {
  1320. var target, removedChildren;
  1321. if (type === "problem") {
  1322. target = $($(parent).children().next().next().get(0)).clone();
  1323. } else if (type === "problem_QA") {
  1324. target = $(this).parent().parent().eq(0).clone();
  1325. $(target).children(':first').remove();
  1326. } else if (type === "upper_level_2") {
  1327. target = $(parent).clone();
  1328. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1329. $(target).children(':first').remove();
  1330. } else {
  1331. target = $(parent).clone();
  1332. }
  1333. if (!target.markdown) {
  1334. target.markdown = turndownService.turndown($(target).html());
  1335. }
  1336. const textarea = document.createElement('textarea');
  1337. textarea.value = target.markdown;
  1338. document.body.appendChild(textarea);
  1339. textarea.select();
  1340. document.execCommand('copy');
  1341. document.body.removeChild(textarea);
  1342. $(this).addClass("copied");
  1343. $(this).text("Copied");
  1344. // 更新复制按钮文本
  1345. setTimeout(() => {
  1346. $(this).removeClass("copied");
  1347. $(this).text("Copy");
  1348. }, 2000);
  1349. $(target).remove();
  1350. });
  1351. }
  1352.  
  1353. function addButtonWithTranslation(parent, suffix, type) {
  1354. $(".translateButton" + suffix).click(async function () {
  1355. var target, removedChildren;
  1356. if (type === "problem") {
  1357. target = $($(parent).children().next().next().get(0)).clone();
  1358. } else if (type === "problem_QA") {
  1359. target = $(this).parent().parent().eq(0).clone();
  1360. $(target).children(':first').remove();
  1361. } else if (type === "upper_level_2") {
  1362. target = $(parent).clone();
  1363. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1364. $(target).children(':first').remove();
  1365. } else {
  1366. target = $(parent).clone();
  1367. }
  1368. if (is_oldLatex) {
  1369. target.markdown = $(target).html();
  1370. } else if (!target.markdown) {
  1371. target.markdown = turndownService.turndown($(target).html());
  1372. }
  1373. const textarea = document.createElement('textarea');
  1374. textarea.value = target.markdown;
  1375. // 翻译处理
  1376. $(this).removeClass("translated");
  1377. $(this).text("翻译中");
  1378. $(this).css("cursor", "not-allowed");
  1379. var element_node;
  1380. if (type === "problem") {
  1381. element_node = $(parent).children()[2]; // 题面特殊处理
  1382. } else if (type === "problem_QA") {
  1383. element_node = $(parent).children().last().get(0);
  1384. } else {
  1385. element_node = parent;
  1386. }
  1387. var translateDiv = await translateProblemStatement(textarea.value, element_node);
  1388. //
  1389. $(this).addClass("translated");
  1390. $(this).text("已翻译");
  1391. $(this).prop("disabled", true);
  1392. $(target).remove();
  1393. // 重新翻译
  1394. if ($(this).next('.reTranslation').length === 0) {
  1395. const reTranslateBtn = $('<button>').addClass('html2mdButton reTranslation').html('&circlearrowright;').attr('title', '重新翻译');
  1396. reTranslateBtn.on('click', function() {
  1397. $(translateDiv).remove();
  1398. $(this).prev().click();
  1399. });
  1400. $(this).after(reTranslateBtn);
  1401. }else {
  1402. const reTranslateBtn = $(this).next('.reTranslation');
  1403. reTranslateBtn.off('click').on('click', function() {
  1404. $(translateDiv).remove();
  1405. $(this).prev().click();
  1406. });
  1407. }
  1408. });
  1409. }
  1410.  
  1411.  
  1412. window.onload = function () {
  1413. // 添加按钮到题面部分
  1414. $("div[class='problem-statement']").each(function () {
  1415. var problem_id = "_comment_" + getRandomNumber(8);
  1416. addButtonPanel(this, problem_id, "problem");
  1417. addButtonWithHTML2MD(this, problem_id, "problem");
  1418. addButtonWithCopy(this, problem_id, "problem");
  1419. addButtonWithTranslation(this, problem_id, "problem");
  1420. });
  1421.  
  1422. // 添加按钮到input部分
  1423. $("div[class='input-specification']").each(function () {
  1424. var id = "_" + getRandomNumber(8);
  1425. addButtonPanel(this, id, "upper_level_2");
  1426. addButtonWithHTML2MD(this, id, "upper_level_2");
  1427. addButtonWithCopy(this, id, "upper_level_2");
  1428. addButtonWithTranslation(this, id, "upper_level_2");
  1429. });
  1430.  
  1431. // 添加按钮到output部分
  1432. $("div[class='output-specification']").each(function () {
  1433. var id = "_" + getRandomNumber(8);
  1434. addButtonPanel(this, id, "upper_level_2");
  1435. addButtonWithHTML2MD(this, id, "upper_level_2");
  1436. addButtonWithCopy(this, id, "upper_level_2");
  1437. addButtonWithTranslation(this, id, "upper_level_2");
  1438. });
  1439.  
  1440. // 添加按钮到note部分
  1441. $("div[class='note']").each(function () {
  1442. var id = "_" + getRandomNumber(8);
  1443. addButtonPanel(this, id, "upper_level_2");
  1444. addButtonWithHTML2MD(this, id, "upper_level_2");
  1445. addButtonWithCopy(this, id, "upper_level_2");
  1446. addButtonWithTranslation(this, id, "upper_level_2");
  1447. });
  1448.  
  1449. // 添加按钮到ttypography部分
  1450. $(".ttypography").each(function () {
  1451. // 题目页特判
  1452. if (!$(this).parent().hasClass('problemindexholder')) {
  1453. var comment_id = "_comment_" + getRandomNumber(8);
  1454. addButtonPanel(this, comment_id, "this_level");
  1455. addButtonWithHTML2MD(this, comment_id, "this_level");
  1456. addButtonWithCopy(this, comment_id, "this_level");
  1457. addButtonWithTranslation(this, comment_id, "this_level");
  1458. }
  1459. });
  1460.  
  1461. // 添加按钮到titled部分
  1462. (function () {
  1463. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  1464. $.each(elements, function (index, value) {
  1465. $(value).each(function () {
  1466. var titled_id = "_titled_" + getRandomNumber(8);
  1467. var $nextDiv = $(this).next().get(0);
  1468. addButtonPanel($nextDiv, titled_id, "this_level", true);
  1469. addButtonWithTranslation($nextDiv, titled_id, "this_level");
  1470. });
  1471. });
  1472. })();
  1473.  
  1474. // 添加按钮到比赛QA部分
  1475. $(".question-requestText-td").each(function () {
  1476. var $nextDiv = $(this).children().get(0);
  1477. var question_id = "_question_" + getRandomNumber(8);
  1478. addButtonPanel($nextDiv, question_id, "problem_QA", true);
  1479. addButtonWithTranslation(this, question_id, "problem_QA");
  1480. });
  1481. };
  1482.  
  1483. /* alert弹窗汉化
  1484. var _alert = window.alert;
  1485. window.alert = async function(msg){
  1486. _alert(msg+"\n=========翻译=========\n"+await translate_deepl(msg));
  1487. return true;
  1488. }
  1489. */
  1490.  
  1491. // 翻译框/翻译处理器
  1492. var translatedText = "";
  1493. async function translateProblemStatement(text, element_node) {
  1494. let id = Math.floor(Date.now() / 1000);
  1495. let matches = [];
  1496. let replacements = {};
  1497. // 创建元素并放在element_node的后面
  1498. const translateDiv = document.createElement('div');
  1499. translateDiv.setAttribute('id', id);
  1500. translateDiv.classList.add('translate-problem-statement');
  1501. const spanElement = document.createElement('span');
  1502. translateDiv.appendChild(spanElement);
  1503. element_node.insertAdjacentElement('afterend', translateDiv);
  1504. // 替换latex公式
  1505. if (is_oldLatex) {
  1506. //去除开头结尾的<p>标签
  1507. text = text.replace(/^<p>/i, "");
  1508. text = text.replace(/<\/p>$/i, "");
  1509. //
  1510. let i = 0;
  1511. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  1512. matches = text.match(regex);
  1513. try {
  1514. for (i; i < matches.length; i++) {
  1515. let match = matches[i];
  1516. text = text.replace(match, `【${i + 1}】`);
  1517. replacements[`【${i + 1}】`] = match;
  1518. }
  1519. } catch (e) { }
  1520. } else if (GM_getValue("translation") != "api2d" && GM_getValue("translation") != "openai") {
  1521. // 使用GPT翻译时不必替换latex公式
  1522. let i = 0;
  1523. // 块公式
  1524. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1525. try {
  1526. for (i; i < matches.length; i++) {
  1527. let match = matches[i];
  1528. text = text.replace(match, `【${i + 1}】`);
  1529. replacements[`【${i + 1}】`] = match;
  1530. }
  1531. } catch (e) { }
  1532. // 行内公式
  1533. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1534. try {
  1535. for (i; i < matches.length; i++) {
  1536. let match = matches[i];
  1537. text = text.replace(match, `【${i + 1}】`);
  1538. replacements[`【${i + 1}】`] = match;
  1539. }
  1540. } catch (e) { }
  1541. }
  1542. // 翻译
  1543. var translation = GM_getValue("translation");
  1544. if (translation === 'undefined' || translation === '') {
  1545. GM_setValue("translation", "deepl");
  1546. translation = "deepl";
  1547. }
  1548. if (translation == "deepl") {
  1549. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1550. translatedText = await translate_deepl(text);
  1551. } else if (translation == "youdao") {
  1552. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1553. translatedText = await translate_youdao_mobile(text);
  1554. } else if (translation == "baidu") {
  1555. var baidu_appid = GM_getValue("baidu_uid");
  1556. var baidu_key = GM_getValue("baidu_key");
  1557. } else if (translation == "openai") {
  1558. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1559. translatedText = await translate_openai(text);
  1560. } else if (translation == "api2d") {
  1561. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1562. translatedText = await translate_api2d(text);
  1563. }
  1564. // 还原latex公式
  1565. if (is_oldLatex) {
  1566. translatedText = "<p>" + translatedText;
  1567. translatedText += "</p>";
  1568. try {
  1569. for (let i = 0; i < matches.length; i++) {
  1570. let match = matches[i];
  1571. let replacement = replacements[`【${i + 1}】`];
  1572. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1573. }
  1574. } catch (e) { }
  1575. }
  1576. else if (GM_getValue("translation") != "api2d" && GM_getValue("translation") != "openai") {
  1577. try {
  1578. for (let i = 0; i < matches.length; i++) {
  1579. let match = matches[i];
  1580. let replacement = replacements[`【${i + 1}】`];
  1581. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1582. }
  1583. } catch (e) { }
  1584. }
  1585. // 使符合mathjx的转换语法
  1586. translatedText = translatedText.replace(/(\$\$)/g, "");
  1587. translatedText = translatedText.replace(/(?<!\$)\$(?!\$)/g, "$$$$$");
  1588. // 更新
  1589. if (is_oldLatex) {
  1590. // oldlatex
  1591. translatedText = $.parseHTML(translatedText);
  1592. $(translateDiv).empty().append($(translatedText));
  1593. } else {
  1594. translateDiv.innerHTML = translatedText;
  1595. // 渲染MarkDown
  1596. var md = window.markdownit();
  1597. var html = md.render(translateDiv.innerText);
  1598. translateDiv.innerHTML = html;
  1599. // 渲染Latex
  1600. MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById(id)]);
  1601. }
  1602. return translateDiv;
  1603. }
  1604.  
  1605. // ChatGPT
  1606. async function translate_openai(raw) {
  1607. var openai_key = GM_getValue("openai_key");
  1608. var openai_retext = "";
  1609. var data;
  1610. if (is_oldLatex) {
  1611. data = {
  1612. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1613. max_tokens: 2048,
  1614. model: "text-davinci-003",
  1615. };
  1616. } else {
  1617. data = {
  1618. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1619. max_tokens: 2048,
  1620. model: "text-davinci-003",
  1621. };
  1622. };
  1623. return new Promise(function (resolve, reject) {
  1624. GM_xmlhttpRequest({
  1625. method: 'POST',
  1626. url: 'https://api.openai.com/v1/completions',
  1627. data: JSON.stringify(data),
  1628. headers: {
  1629. 'Content-Type': 'application/json',
  1630. 'Authorization': 'Bearer ' + GM_getValue("openai_key") + ''
  1631. },
  1632. responseType: 'json',
  1633. onload: function (res) {
  1634. if (res.status === 200) {
  1635. openai_retext = res.response.choices[0].text;
  1636. openai_retext = openai_retext.replace(/^\s+/, '');
  1637. resolve(openai_retext);
  1638. }
  1639. else {
  1640. console.error(res.statusText);
  1641. reject(res.statusText);
  1642. }
  1643. }
  1644. });
  1645. });
  1646. }
  1647.  
  1648. // api2d
  1649. async function translate_api2d(raw) {
  1650. var api2d_key = GM_getValue("api2d_key");
  1651. var api2d_retext = "";
  1652. var postData;
  1653. if (is_oldLatex) {
  1654. postData = JSON.stringify({
  1655. model: 'gpt-3.5-turbo',
  1656. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1657. });
  1658. } else {
  1659. postData = JSON.stringify({
  1660. model: 'gpt-3.5-turbo',
  1661. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1662. });
  1663. }
  1664. const options = {
  1665. method: 'POST',
  1666. headers: {
  1667. 'Content-Type': 'application/json',
  1668. Authorization: 'Bearer ' + api2d_key,
  1669. },
  1670. data: postData,
  1671. };
  1672.  
  1673. return new Promise(function (resolve, reject) {
  1674. GM_xmlhttpRequest({
  1675. method: options.method,
  1676. url: `https://openai.api2d.net/v1/chat/completions`,
  1677. headers: options.headers,
  1678. data: options.data,
  1679. responseType: 'json',
  1680. onload: function (response) {
  1681. api2d_retext = response.response.choices[0].message.content;
  1682. resolve(api2d_retext);
  1683. },
  1684. onerror: function (response) {
  1685. console.error(response.statusText);
  1686. reject(response.statusText);
  1687. },
  1688. });
  1689. });
  1690. }
  1691. //
  1692.  
  1693. //--有道翻译m--start
  1694. async function translate_youdao_mobile(raw) {
  1695. const options = {
  1696. method: "POST",
  1697. url: 'http://m.youdao.com/translate',
  1698. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  1699. anonymous: true,
  1700. headers: {
  1701. "Content-Type": "application/x-www-form-urlencoded"
  1702. }
  1703. }
  1704. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1705. }
  1706. //--有道翻译m--end
  1707.  
  1708. //--Deepl翻译--start
  1709. function getTimeStamp(iCount) {
  1710. const ts = Date.now();
  1711. if (iCount !== 0) {
  1712. iCount = iCount + 1;
  1713. return ts - (ts % iCount) + iCount;
  1714. } else {
  1715. return ts;
  1716. }
  1717. }
  1718.  
  1719. async function translate_deepl(raw) {
  1720. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  1721. const data = {
  1722. jsonrpc: '2.0',
  1723. method: 'LMT_handle_texts',
  1724. id,
  1725. params: {
  1726. splitting: 'newlines',
  1727. lang: {
  1728. source_lang_user_selected: 'auto',
  1729. target_lang: 'ZH',
  1730. },
  1731. texts: [{
  1732. text: raw,
  1733. requestAlternatives: 3
  1734. }],
  1735. timestamp: getTimeStamp(raw.split('i').length - 1)
  1736. }
  1737. }
  1738. let postData = JSON.stringify(data);
  1739. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1740. postData = postData.replace('"method":"', '"method" : "');
  1741. } else {
  1742. postData = postData.replace('"method":"', '"method": "');
  1743. }
  1744. const options = {
  1745. method: 'POST',
  1746. url: 'https://www2.deepl.com/jsonrpc',
  1747. data: postData,
  1748. headers: {
  1749. 'Content-Type': 'application/json',
  1750. 'Host': 'www.deepl.com',
  1751. 'Origin': 'https://www.deepl.com',
  1752. 'Referer': 'https://www.deepl.com/'
  1753. },
  1754. anonymous: true,
  1755. nocache: true,
  1756. }
  1757. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  1758. }
  1759.  
  1760. //--Deepl翻译--end
  1761.  
  1762. //--异步请求包装工具--start
  1763. async function PromiseRetryWrap(task, options, ...values) {
  1764. const { RetryTimes, ErrProcesser } = options || {};
  1765. let retryTimes = RetryTimes || 5;
  1766. const usedErrProcesser = ErrProcesser || (err => { throw err });
  1767. if (!task) return;
  1768. while (true) {
  1769. try {
  1770. return await task(...values);
  1771. } catch (err) {
  1772. if (!--retryTimes) {
  1773. console.log(err);
  1774. return usedErrProcesser(err);
  1775. }
  1776. }
  1777. }
  1778. }
  1779.  
  1780. async function BaseTranslate(name, raw, options, processer) {
  1781. const toDo = async () => {
  1782. var tmp;
  1783. try {
  1784. const data = await Request(options);
  1785. tmp = data.responseText;
  1786. const result = await processer(tmp);
  1787. if (result) sessionStorage.setItem(name + '-' + raw, result);
  1788. return result
  1789. } catch (err) {
  1790. throw {
  1791. responseText: tmp,
  1792. err: err
  1793. }
  1794. }
  1795. }
  1796. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错" })
  1797. }
  1798.  
  1799. function Request(options) {
  1800. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  1801. }
  1802.  
  1803. //--异步请求包装工具--end
  1804.  
  1805. // 随机数生成
  1806. function getRandomNumber(numDigits) {
  1807. let min = Math.pow(10, numDigits - 1);
  1808. let max = Math.pow(10, numDigits) - 1;
  1809. return Math.floor(Math.random() * (max - min + 1)) + min;
  1810. }
  1811.  
  1812. // 旧配置迁移(临时,将在1.38版本后删除)
  1813. if(getCookie("translation")){GM_setValue("translation",getCookie("translation"));deleteCookie("translation");}
  1814. if(getCookie("baidu_uid")){GM_setValue("baidu_uid",getCookie("baidu_uid"));deleteCookie("baidu_uid");}
  1815. if(getCookie("baidu_key")){GM_setValue("baidu_key",getCookie("baidu_key"));deleteCookie("baidu_key");}
  1816. if(getCookie("openai_key")){GM_setValue("openai_key",getCookie("openai_key"));deleteCookie("openai_key");}
  1817. if(getCookie("api2d_key")){GM_setValue("api2d_key",getCookie("api2d_key"));deleteCookie("api2d_key");}
  1818. if(getCookie("bottomZh_CN")){GM_setValue("bottomZh_CN",getCookie("bottomZh_CN")==="true");deleteCookie("bottomZh_CN");}
  1819. function deleteCookie(name){document.cookie=name+"=; expires=Thu, 01 Jan 1970 00:00:01 GMT;";}
  1820. function getCookie(cname) {var name = cname + "=";var decodedCookie = decodeURIComponent(document.cookie);var ca = decodedCookie.split(';');for (var i = 0; i < ca.length; i++) {var c = ca[i];while (c.charAt(0) == ' ') {c = c.substring(1);}if (c.indexOf(name) == 0) {return c.substring(name.length, c.length);}}return "";}