Codeforces Better!

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

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

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